Load.php 109 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605
  1. <?php
  2. /**
  3. * This file has the hefty job of loading information for the forum.
  4. *
  5. * Simple Machines Forum (SMF)
  6. *
  7. * @package SMF
  8. * @author Simple Machines http://www.simplemachines.org
  9. * @copyright 2011 Simple Machines
  10. * @license http://www.simplemachines.org/about/smf/license.php BSD
  11. *
  12. * @version 2.0
  13. */
  14. if (!defined('SMF'))
  15. die('Hacking attempt...');
  16. /**
  17. * Load the $modSettings array.
  18. * @todo okay question of the day: why a function loading settings is called
  19. * reloadSettings()
  20. */
  21. function reloadSettings()
  22. {
  23. global $modSettings, $boarddir, $smcFunc, $txt, $db_character_set, $context, $sourcedir;
  24. // Most database systems have not set UTF-8 as their default input charset.
  25. if (!empty($db_character_set))
  26. $smcFunc['db_query']('set_character_set', '
  27. SET NAMES ' . $db_character_set,
  28. array(
  29. )
  30. );
  31. // Try to load it from the cache first; it'll never get cached if the setting is off.
  32. if (($modSettings = cache_get_data('modSettings', 90)) == null)
  33. {
  34. $request = $smcFunc['db_query']('', '
  35. SELECT variable, value
  36. FROM {db_prefix}settings',
  37. array(
  38. )
  39. );
  40. $modSettings = array();
  41. if (!$request)
  42. db_fatal_error();
  43. while ($row = $smcFunc['db_fetch_row']($request))
  44. $modSettings[$row[0]] = $row[1];
  45. $smcFunc['db_free_result']($request);
  46. // Do a few things to protect against missing settings or settings with invalid values...
  47. if (empty($modSettings['defaultMaxTopics']) || $modSettings['defaultMaxTopics'] <= 0 || $modSettings['defaultMaxTopics'] > 999)
  48. $modSettings['defaultMaxTopics'] = 20;
  49. if (empty($modSettings['defaultMaxMessages']) || $modSettings['defaultMaxMessages'] <= 0 || $modSettings['defaultMaxMessages'] > 999)
  50. $modSettings['defaultMaxMessages'] = 15;
  51. if (empty($modSettings['defaultMaxMembers']) || $modSettings['defaultMaxMembers'] <= 0 || $modSettings['defaultMaxMembers'] > 999)
  52. $modSettings['defaultMaxMembers'] = 30;
  53. if (!empty($modSettings['cache_enable']))
  54. cache_put_data('modSettings', $modSettings, 90);
  55. }
  56. // UTF-8 in regular expressions is unsupported on PHP(win) versions < 4.2.3.
  57. $utf8 = (empty($modSettings['global_character_set']) ? $txt['lang_character_set'] : $modSettings['global_character_set']) === 'UTF-8' && (strpos(strtolower(PHP_OS), 'win') === false || @version_compare(PHP_VERSION, '4.2.3') != -1);
  58. // Set a list of common functions.
  59. $ent_list = empty($modSettings['disableEntityCheck']) ? '&(#\d{1,7}|quot|amp|lt|gt|nbsp);' : '&(#021|quot|amp|lt|gt|nbsp);';
  60. $ent_check = empty($modSettings['disableEntityCheck']) ? array('preg_replace(\'~(&#(\d{1,7}|x[0-9a-fA-F]{1,6});)~e\', \'$smcFunc[\\\'entity_fix\\\'](\\\'\\2\\\')\', ', ')') : array('', '');
  61. // Preg_replace can handle complex characters only for higher PHP versions.
  62. $space_chars = $utf8 ? (@version_compare(PHP_VERSION, '4.3.3') != -1 ? '\x{A0}\x{AD}\x{2000}-\x{200F}\x{201F}\x{202F}\x{3000}\x{FEFF}' : "\xC2\xA0\xC2\xAD\xE2\x80\x80-\xE2\x80\x8F\xE2\x80\x9F\xE2\x80\xAF\xE2\x80\x9F\xE3\x80\x80\xEF\xBB\xBF") : '\x00-\x08\x0B\x0C\x0E-\x19\xA0';
  63. $smcFunc += array(
  64. 'entity_fix' => create_function('$string', '
  65. $num = substr($string, 0, 1) === \'x\' ? hexdec(substr($string, 1)) : (int) $string;
  66. return $num < 0x20 || $num > 0x10FFFF || ($num >= 0xD800 && $num <= 0xDFFF) || $num == 0x202E ? \'\' : \'&#\' . $num . \';\';'),
  67. 'htmlspecialchars' => create_function('$string, $quote_style = ENT_COMPAT, $charset = \'ISO-8859-1\'', '
  68. global $smcFunc;
  69. return ' . strtr($ent_check[0], array('&' => '&amp;')) . 'htmlspecialchars($string, $quote_style, ' . ($utf8 ? '\'UTF-8\'' : '$charset') . ')' . $ent_check[1] . ';'),
  70. 'htmltrim' => create_function('$string', '
  71. global $smcFunc;
  72. return preg_replace(\'~^(?:[ \t\n\r\x0B\x00' . $space_chars . ']|&nbsp;)+|(?:[ \t\n\r\x0B\x00' . $space_chars . ']|&nbsp;)+$~' . ($utf8 ? 'u' : '') . '\', \'\', ' . implode('$string', $ent_check) . ');'),
  73. 'strlen' => create_function('$string', '
  74. global $smcFunc;
  75. return strlen(preg_replace(\'~' . $ent_list . ($utf8 ? '|.~u' : '~') . '\', \'_\', ' . implode('$string', $ent_check) . '));'),
  76. 'strpos' => create_function('$haystack, $needle, $offset = 0', '
  77. global $smcFunc;
  78. $haystack_arr = preg_split(\'~(&#' . (empty($modSettings['disableEntityCheck']) ? '\d{1,7}' : '021') . ';|&quot;|&amp;|&lt;|&gt;|&nbsp;|.)~' . ($utf8 ? 'u' : '') . '\', ' . implode('$haystack', $ent_check) . ', -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
  79. $haystack_size = count($haystack_arr);
  80. if (strlen($needle) === 1)
  81. {
  82. $result = array_search($needle, array_slice($haystack_arr, $offset));
  83. return is_int($result) ? $result + $offset : false;
  84. }
  85. else
  86. {
  87. $needle_arr = preg_split(\'~(&#' . (empty($modSettings['disableEntityCheck']) ? '\d{1,7}' : '021') . ';|&quot;|&amp;|&lt;|&gt;|&nbsp;|.)~' . ($utf8 ? 'u' : '') . '\', ' . implode('$needle', $ent_check) . ', -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
  88. $needle_size = count($needle_arr);
  89. $result = array_search($needle_arr[0], array_slice($haystack_arr, $offset));
  90. while (is_int($result))
  91. {
  92. $offset += $result;
  93. if (array_slice($haystack_arr, $offset, $needle_size) === $needle_arr)
  94. return $offset;
  95. $result = array_search($needle_arr[0], array_slice($haystack_arr, ++$offset));
  96. }
  97. return false;
  98. }'),
  99. 'substr' => create_function('$string, $start, $length = null', '
  100. global $smcFunc;
  101. $ent_arr = preg_split(\'~(&#' . (empty($modSettings['disableEntityCheck']) ? '\d{1,7}' : '021') . ';|&quot;|&amp;|&lt;|&gt;|&nbsp;|.)~' . ($utf8 ? 'u' : '') . '\', ' . implode('$string', $ent_check) . ', -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
  102. return $length === null ? implode(\'\', array_slice($ent_arr, $start)) : implode(\'\', array_slice($ent_arr, $start, $length));'),
  103. 'strtolower' => $utf8 ? (function_exists('mb_strtolower') ? create_function('$string', '
  104. return mb_strtolower($string, \'UTF-8\');') : create_function('$string', '
  105. global $sourcedir;
  106. require_once($sourcedir . \'/Subs-Charset.php\');
  107. return utf8_strtolower($string);')) : 'strtolower',
  108. 'strtoupper' => $utf8 ? (function_exists('mb_strtoupper') ? create_function('$string', '
  109. return mb_strtoupper($string, \'UTF-8\');') : create_function('$string', '
  110. global $sourcedir;
  111. require_once($sourcedir . \'/Subs-Charset.php\');
  112. return utf8_strtoupper($string);')) : 'strtoupper',
  113. 'truncate' => create_function('$string, $length', (empty($modSettings['disableEntityCheck']) ? '
  114. global $smcFunc;
  115. $string = ' . implode('$string', $ent_check) . ';' : '') . '
  116. preg_match(\'~^(' . $ent_list . '|.){\' . $smcFunc[\'strlen\'](substr($string, 0, $length)) . \'}~'. ($utf8 ? 'u' : '') . '\', $string, $matches);
  117. $string = $matches[0];
  118. while (strlen($string) > $length)
  119. $string = preg_replace(\'~(?:' . $ent_list . '|.)$~'. ($utf8 ? 'u' : '') . '\', \'\', $string);
  120. return $string;'),
  121. 'ucfirst' => $utf8 ? create_function('$string', '
  122. global $smcFunc;
  123. return $smcFunc[\'strtoupper\']($smcFunc[\'substr\']($string, 0, 1)) . $smcFunc[\'substr\']($string, 1);') : 'ucfirst',
  124. 'ucwords' => $utf8 ? create_function('$string', '
  125. global $smcFunc;
  126. $words = preg_split(\'~([\s\r\n\t]+)~\', $string, -1, PREG_SPLIT_DELIM_CAPTURE);
  127. for ($i = 0, $n = count($words); $i < $n; $i += 2)
  128. $words[$i] = $smcFunc[\'ucfirst\']($words[$i]);
  129. return implode(\'\', $words);') : 'ucwords',
  130. );
  131. // Setting the timezone is a requirement for some functions in PHP >= 5.1.
  132. if (isset($modSettings['default_timezone']) && function_exists('date_default_timezone_set'))
  133. date_default_timezone_set($modSettings['default_timezone']);
  134. // Check the load averages?
  135. if (!empty($modSettings['loadavg_enable']))
  136. {
  137. if (($modSettings['load_average'] = cache_get_data('loadavg', 90)) == null)
  138. {
  139. $modSettings['load_average'] = @file_get_contents('/proc/loadavg');
  140. if (!empty($modSettings['load_average']) && preg_match('~^([^ ]+?) ([^ ]+?) ([^ ]+)~', $modSettings['load_average'], $matches) != 0)
  141. $modSettings['load_average'] = (float) $matches[1];
  142. elseif (($modSettings['load_average'] = @`uptime`) != null && preg_match('~load average[s]?: (\d+\.\d+), (\d+\.\d+), (\d+\.\d+)~i', $modSettings['load_average'], $matches) != 0)
  143. $modSettings['load_average'] = (float) $matches[1];
  144. else
  145. unset($modSettings['load_average']);
  146. if (!empty($modSettings['load_average']))
  147. cache_put_data('loadavg', $modSettings['load_average'], 90);
  148. }
  149. if (!empty($modSettings['loadavg_forum']) && !empty($modSettings['load_average']) && $modSettings['load_average'] >= $modSettings['loadavg_forum'])
  150. db_fatal_error(true);
  151. }
  152. // Is post moderation alive and well?
  153. $modSettings['postmod_active'] = isset($modSettings['admin_features']) ? in_array('pm', explode(',', $modSettings['admin_features'])) : true;
  154. // Integration is cool.
  155. if (defined('SMF_INTEGRATION_SETTINGS'))
  156. {
  157. $integration_settings = unserialize(SMF_INTEGRATION_SETTINGS);
  158. foreach ($integration_settings as $hook => $function)
  159. add_integration_function($hook, $function, false);
  160. }
  161. // Any files to pre include?
  162. if (!empty($modSettings['integrate_pre_include']))
  163. {
  164. $pre_includes = explode(',', $modSettings['integrate_pre_include']);
  165. foreach ($pre_includes as $include)
  166. {
  167. $include = strtr(trim($include), array('$boarddir' => $boarddir, '$sourcedir' => $sourcedir));
  168. if (file_exists($include))
  169. require_once($include);
  170. }
  171. }
  172. // Call pre load integration functions.
  173. call_integration_hook('integrate_pre_load');
  174. }
  175. /**
  176. * Load all the important user information.
  177. * What it does:
  178. * - sets up the $user_info array
  179. - assigns $user_info['query_wanna_see_board'] for what boards the user can see.
  180. - first checks for cookie or integration validation.
  181. - uses the current session if no integration function or cookie is found.
  182. - checks password length, if member is activated and the login span isn't over.
  183. - if validation fails for the user, $id_member is set to 0.
  184. - updates the last visit time when needed.
  185. */
  186. function loadUserSettings()
  187. {
  188. global $modSettings, $user_settings, $sourcedir, $smcFunc;
  189. global $cookiename, $user_info, $language;
  190. // Check first the integration, then the cookie, and last the session.
  191. if (count($integration_ids = call_integration_hook('integrate_verify_user')) > 0)
  192. {
  193. $id_member = 0;
  194. foreach ($integration_ids as $integration_id)
  195. {
  196. $integration_id = (int) $integration_id;
  197. if ($integration_id > 0)
  198. {
  199. $id_member = $integration_id;
  200. $already_verified = true;
  201. break;
  202. }
  203. }
  204. }
  205. else
  206. $id_member = 0;
  207. if (empty($id_member) && isset($_COOKIE[$cookiename]))
  208. {
  209. // Fix a security hole in PHP 4.3.9 and below...
  210. if (preg_match('~^a:[34]:\{i:0;(i:\d{1,6}|s:[1-8]:"\d{1,8}");i:1;s:(0|40):"([a-fA-F0-9]{40})?";i:2;[id]:\d{1,14};(i:3;i:\d;)?\}$~i', $_COOKIE[$cookiename]) == 1)
  211. {
  212. list ($id_member, $password) = @unserialize($_COOKIE[$cookiename]);
  213. $id_member = !empty($id_member) && strlen($password) > 0 ? (int) $id_member : 0;
  214. }
  215. else
  216. $id_member = 0;
  217. }
  218. elseif (empty($id_member) && isset($_SESSION['login_' . $cookiename]) && ($_SESSION['USER_AGENT'] == $_SERVER['HTTP_USER_AGENT'] || !empty($modSettings['disableCheckUA'])))
  219. {
  220. // !!! Perhaps we can do some more checking on this, such as on the first octet of the IP?
  221. list ($id_member, $password, $login_span) = @unserialize($_SESSION['login_' . $cookiename]);
  222. $id_member = !empty($id_member) && strlen($password) == 40 && $login_span > time() ? (int) $id_member : 0;
  223. }
  224. // Only load this stuff if the user isn't a guest.
  225. if ($id_member != 0)
  226. {
  227. // Is the member data cached?
  228. if (empty($modSettings['cache_enable']) || $modSettings['cache_enable'] < 2 || ($user_settings = cache_get_data('user_settings-' . $id_member, 60)) == null)
  229. {
  230. $request = $smcFunc['db_query']('', '
  231. SELECT mem.*, IFNULL(a.id_attach, 0) AS id_attach, a.filename, a.attachment_type
  232. FROM {db_prefix}members AS mem
  233. LEFT JOIN {db_prefix}attachments AS a ON (a.id_member = {int:id_member})
  234. WHERE mem.id_member = {int:id_member}
  235. LIMIT 1',
  236. array(
  237. 'id_member' => $id_member,
  238. )
  239. );
  240. $user_settings = $smcFunc['db_fetch_assoc']($request);
  241. $smcFunc['db_free_result']($request);
  242. if (!empty($modSettings['cache_enable']) && $modSettings['cache_enable'] >= 2)
  243. cache_put_data('user_settings-' . $id_member, $user_settings, 60);
  244. }
  245. // Did we find 'im? If not, junk it.
  246. if (!empty($user_settings))
  247. {
  248. // As much as the password should be right, we can assume the integration set things up.
  249. if (!empty($already_verified) && $already_verified === true)
  250. $check = true;
  251. // SHA-1 passwords should be 40 characters long.
  252. elseif (strlen($password) == 40)
  253. $check = sha1($user_settings['passwd'] . $user_settings['password_salt']) == $password;
  254. else
  255. $check = false;
  256. // Wrong password or not activated - either way, you're going nowhere.
  257. $id_member = $check && ($user_settings['is_activated'] == 1 || $user_settings['is_activated'] == 11) ? $user_settings['id_member'] : 0;
  258. }
  259. else
  260. $id_member = 0;
  261. // If we no longer have the member maybe they're being all hackey, stop brute force!
  262. if (!$id_member)
  263. {
  264. require_once($sourcedir . '/LogInOut.php');
  265. validatePasswordFlood(!empty($user_settings['id_member']) ? $user_settings['id_member'] : $id_member, !empty($user_settings['passwd_flood']) ? $user_settings['passwd_flood'] : false, $id_member != 0);
  266. }
  267. }
  268. // Found 'im, let's set up the variables.
  269. if ($id_member != 0)
  270. {
  271. // Let's not update the last visit time in these cases...
  272. // 1. SSI doesn't count as visiting the forum.
  273. // 2. RSS feeds and XMLHTTP requests don't count either.
  274. // 3. If it was set within this session, no need to set it again.
  275. // 4. New session, yet updated < five hours ago? Maybe cache can help.
  276. if (SMF != 'SSI' && !isset($_REQUEST['xml']) && (!isset($_REQUEST['action']) || $_REQUEST['action'] != '.xml') && empty($_SESSION['id_msg_last_visit']) && (empty($modSettings['cache_enable']) || ($_SESSION['id_msg_last_visit'] = cache_get_data('user_last_visit-' . $id_member, 5 * 3600)) === null))
  277. {
  278. // Do a quick query to make sure this isn't a mistake.
  279. $result = $smcFunc['db_query']('', '
  280. SELECT poster_time
  281. FROM {db_prefix}messages
  282. WHERE id_msg = {int:id_msg}
  283. LIMIT 1',
  284. array(
  285. 'id_msg' => $user_settings['id_msg_last_visit'],
  286. )
  287. );
  288. list ($visitTime) = $smcFunc['db_fetch_row']($result);
  289. $smcFunc['db_free_result']($result);
  290. $_SESSION['id_msg_last_visit'] = $user_settings['id_msg_last_visit'];
  291. // If it was *at least* five hours ago...
  292. if ($visitTime < time() - 5 * 3600)
  293. {
  294. updateMemberData($id_member, array('id_msg_last_visit' => (int) $modSettings['maxMsgID'], 'last_login' => time(), 'member_ip' => $_SERVER['REMOTE_ADDR'], 'member_ip2' => $_SERVER['BAN_CHECK_IP']));
  295. $user_settings['last_login'] = time();
  296. if (!empty($modSettings['cache_enable']) && $modSettings['cache_enable'] >= 2)
  297. cache_put_data('user_settings-' . $id_member, $user_settings, 60);
  298. if (!empty($modSettings['cache_enable']))
  299. cache_put_data('user_last_visit-' . $id_member, $_SESSION['id_msg_last_visit'], 5 * 3600);
  300. }
  301. }
  302. elseif (empty($_SESSION['id_msg_last_visit']))
  303. $_SESSION['id_msg_last_visit'] = $user_settings['id_msg_last_visit'];
  304. $username = $user_settings['member_name'];
  305. if (empty($user_settings['additional_groups']))
  306. $user_info = array(
  307. 'groups' => array($user_settings['id_group'], $user_settings['id_post_group'])
  308. );
  309. else
  310. $user_info = array(
  311. 'groups' => array_merge(
  312. array($user_settings['id_group'], $user_settings['id_post_group']),
  313. explode(',', $user_settings['additional_groups'])
  314. )
  315. );
  316. // Because history has proven that it is possible for groups to go bad - clean up in case.
  317. foreach ($user_info['groups'] as $k => $v)
  318. $user_info['groups'][$k] = (int) $v;
  319. // This is a logged in user, so definitely not a spider.
  320. $user_info['possibly_robot'] = false;
  321. }
  322. // If the user is a guest, initialize all the critical user settings.
  323. else
  324. {
  325. // This is what a guest's variables should be.
  326. $username = '';
  327. $user_info = array('groups' => array(-1));
  328. $user_settings = array();
  329. if (isset($_COOKIE[$cookiename]))
  330. $_COOKIE[$cookiename] = '';
  331. // Do we perhaps think this is a search robot? Check every five minutes just in case...
  332. if ((!empty($modSettings['spider_mode']) || !empty($modSettings['spider_group'])) && (!isset($_SESSION['robot_check']) || $_SESSION['robot_check'] < time() - 300))
  333. {
  334. require_once($sourcedir . '/ManageSearchEngines.php');
  335. $user_info['possibly_robot'] = SpiderCheck();
  336. }
  337. elseif (!empty($modSettings['spider_mode']))
  338. $user_info['possibly_robot'] = isset($_SESSION['id_robot']) ? $_SESSION['id_robot'] : 0;
  339. // If we haven't turned on proper spider hunts then have a guess!
  340. else
  341. {
  342. $ci_user_agent = strtolower($_SERVER['HTTP_USER_AGENT']);
  343. $user_info['possibly_robot'] = (strpos($_SERVER['HTTP_USER_AGENT'], 'Mozilla') === false && strpos($_SERVER['HTTP_USER_AGENT'], 'Opera') === false) || strpos($ci_user_agent, 'googlebot') !== false || strpos($ci_user_agent, 'slurp') !== false || strpos($ci_user_agent, 'crawl') !== false;
  344. }
  345. }
  346. // Set up the $user_info array.
  347. $user_info += array(
  348. 'id' => $id_member,
  349. 'username' => $username,
  350. 'name' => isset($user_settings['real_name']) ? $user_settings['real_name'] : '',
  351. 'email' => isset($user_settings['email_address']) ? $user_settings['email_address'] : '',
  352. 'passwd' => isset($user_settings['passwd']) ? $user_settings['passwd'] : '',
  353. 'language' => empty($user_settings['lngfile']) || empty($modSettings['userLanguage']) ? $language : $user_settings['lngfile'],
  354. 'is_guest' => $id_member == 0,
  355. 'is_admin' => in_array(1, $user_info['groups']),
  356. 'theme' => empty($user_settings['id_theme']) ? 0 : $user_settings['id_theme'],
  357. 'last_login' => empty($user_settings['last_login']) ? 0 : $user_settings['last_login'],
  358. 'ip' => $_SERVER['REMOTE_ADDR'],
  359. 'ip2' => $_SERVER['BAN_CHECK_IP'],
  360. 'posts' => empty($user_settings['posts']) ? 0 : $user_settings['posts'],
  361. 'time_format' => empty($user_settings['time_format']) ? $modSettings['time_format'] : $user_settings['time_format'],
  362. 'time_offset' => empty($user_settings['time_offset']) ? 0 : $user_settings['time_offset'],
  363. 'avatar' => array(
  364. 'url' => isset($user_settings['avatar']) ? $user_settings['avatar'] : '',
  365. 'filename' => empty($user_settings['filename']) ? '' : $user_settings['filename'],
  366. 'custom_dir' => !empty($user_settings['attachment_type']) && $user_settings['attachment_type'] == 1,
  367. 'id_attach' => isset($user_settings['id_attach']) ? $user_settings['id_attach'] : 0
  368. ),
  369. 'smiley_set' => isset($user_settings['smiley_set']) ? $user_settings['smiley_set'] : '',
  370. 'messages' => empty($user_settings['instant_messages']) ? 0 : $user_settings['instant_messages'],
  371. 'unread_messages' => empty($user_settings['unread_messages']) ? 0 : $user_settings['unread_messages'],
  372. 'total_time_logged_in' => empty($user_settings['total_time_logged_in']) ? 0 : $user_settings['total_time_logged_in'],
  373. 'buddies' => !empty($modSettings['enable_buddylist']) && !empty($user_settings['buddy_list']) ? explode(',', $user_settings['buddy_list']) : array(),
  374. 'ignoreboards' => !empty($user_settings['ignore_boards']) && !empty($modSettings['allow_ignore_boards']) ? explode(',', $user_settings['ignore_boards']) : array(),
  375. 'ignoreusers' => !empty($user_settings['pm_ignore_list']) ? explode(',', $user_settings['pm_ignore_list']) : array(),
  376. 'warning' => isset($user_settings['warning']) ? $user_settings['warning'] : 0,
  377. 'permissions' => array(),
  378. );
  379. $user_info['groups'] = array_unique($user_info['groups']);
  380. // Make sure that the last item in the ignore boards array is valid. If the list was too long it could have an ending comma that could cause problems.
  381. if (!empty($user_info['ignoreboards']) && empty($user_info['ignoreboards'][$tmp = count($user_info['ignoreboards']) - 1]))
  382. unset($user_info['ignoreboards'][$tmp]);
  383. // Do we have any languages to validate this?
  384. if (!empty($modSettings['userLanguage']) && (!empty($_GET['language']) || !empty($_SESSION['language'])))
  385. $languages = getLanguages();
  386. // Allow the user to change their language if its valid.
  387. if (!empty($modSettings['userLanguage']) && !empty($_GET['language']) && isset($languages[strtr($_GET['language'], './\\:', '____')]))
  388. {
  389. $user_info['language'] = strtr($_GET['language'], './\\:', '____');
  390. $_SESSION['language'] = $user_info['language'];
  391. }
  392. elseif (!empty($modSettings['userLanguage']) && !empty($_SESSION['language']) && isset($languages[strtr($_SESSION['language'], './\\:', '____')]))
  393. $user_info['language'] = strtr($_SESSION['language'], './\\:', '____');
  394. // Just build this here, it makes it easier to change/use - administrators can see all boards.
  395. if ($user_info['is_admin'])
  396. $user_info['query_see_board'] = '1=1';
  397. // Otherwise just the groups in $user_info['groups'].
  398. else
  399. $user_info['query_see_board'] = '(FIND_IN_SET(' . implode(', b.member_groups) != 0 OR FIND_IN_SET(', $user_info['groups']) . ', b.member_groups) != 0' . (isset($user_info['mod_cache']) ? ' OR ' . $user_info['mod_cache']['mq'] : '') . ')';
  400. // Build the list of boards they WANT to see.
  401. // This will take the place of query_see_boards in certain spots, so it better include the boards they can see also
  402. // If they aren't ignoring any boards then they want to see all the boards they can see
  403. if (empty($user_info['ignoreboards']))
  404. $user_info['query_wanna_see_board'] = $user_info['query_see_board'];
  405. // Ok I guess they don't want to see all the boards
  406. else
  407. $user_info['query_wanna_see_board'] = '(' . $user_info['query_see_board'] . ' AND b.id_board NOT IN (' . implode(',', $user_info['ignoreboards']) . '))';
  408. }
  409. /**
  410. * Check for moderators and see if they have access to the board.
  411. * What it does:
  412. * - sets up the $board_info array for current board information.
  413. * - if cache is enabled, the $board_info array is stored in cache.
  414. * - redirects to appropriate post if only message id is requested.
  415. * - is only used when inside a topic or board.
  416. * - determines the local moderators for the board.
  417. * - adds group id 3 if the user is a local moderator for the board they are in.
  418. * - prevents access if user is not in proper group nor a local moderator of the board.
  419. */
  420. function loadBoard()
  421. {
  422. global $txt, $scripturl, $context, $modSettings;
  423. global $board_info, $board, $topic, $user_info, $smcFunc;
  424. // Assume they are not a moderator.
  425. $user_info['is_mod'] = false;
  426. $context['user']['is_mod'] = &$user_info['is_mod'];
  427. // Start the linktree off empty..
  428. $context['linktree'] = array();
  429. // Have they by chance specified a message id but nothing else?
  430. if (empty($_REQUEST['action']) && empty($topic) && empty($board) && !empty($_REQUEST['msg']))
  431. {
  432. // Make sure the message id is really an int.
  433. $_REQUEST['msg'] = (int) $_REQUEST['msg'];
  434. // Looking through the message table can be slow, so try using the cache first.
  435. if (($topic = cache_get_data('msg_topic-' . $_REQUEST['msg'], 120)) === NULL)
  436. {
  437. $request = $smcFunc['db_query']('', '
  438. SELECT id_topic
  439. FROM {db_prefix}messages
  440. WHERE id_msg = {int:id_msg}
  441. LIMIT 1',
  442. array(
  443. 'id_msg' => $_REQUEST['msg'],
  444. )
  445. );
  446. // So did it find anything?
  447. if ($smcFunc['db_num_rows']($request))
  448. {
  449. list ($topic) = $smcFunc['db_fetch_row']($request);
  450. $smcFunc['db_free_result']($request);
  451. // Save save save.
  452. cache_put_data('msg_topic-' . $_REQUEST['msg'], $topic, 120);
  453. }
  454. }
  455. // Remember redirection is the key to avoiding fallout from your bosses.
  456. if (!empty($topic))
  457. redirectexit('topic=' . $topic . '.msg' . $_REQUEST['msg'] . '#msg' . $_REQUEST['msg']);
  458. else
  459. {
  460. loadPermissions();
  461. loadTheme();
  462. fatal_lang_error('topic_gone', false);
  463. }
  464. }
  465. // Load this board only if it is specified.
  466. if (empty($board) && empty($topic))
  467. {
  468. $board_info = array('moderators' => array());
  469. return;
  470. }
  471. if (!empty($modSettings['cache_enable']) && (empty($topic) || $modSettings['cache_enable'] >= 3))
  472. {
  473. // !!! SLOW?
  474. if (!empty($topic))
  475. $temp = cache_get_data('topic_board-' . $topic, 120);
  476. else
  477. $temp = cache_get_data('board-' . $board, 120);
  478. if (!empty($temp))
  479. {
  480. $board_info = $temp;
  481. $board = $board_info['id'];
  482. }
  483. }
  484. if (empty($temp))
  485. {
  486. $request = $smcFunc['db_query']('', '
  487. SELECT
  488. c.id_cat, b.name AS bname, b.description, b.num_topics, b.member_groups,
  489. b.id_parent, c.name AS cname, IFNULL(mem.id_member, 0) AS id_moderator,
  490. mem.real_name' . (!empty($topic) ? ', b.id_board' : '') . ', b.child_level,
  491. b.id_theme, b.override_theme, b.count_posts, b.id_profile, b.redirect,
  492. b.unapproved_topics, b.unapproved_posts' . (!empty($topic) ? ', t.approved, t.id_member_started' : '') . '
  493. FROM {db_prefix}boards AS b' . (!empty($topic) ? '
  494. INNER JOIN {db_prefix}topics AS t ON (t.id_topic = {int:current_topic})' : '') . '
  495. LEFT JOIN {db_prefix}categories AS c ON (c.id_cat = b.id_cat)
  496. LEFT JOIN {db_prefix}moderators AS mods ON (mods.id_board = {raw:board_link})
  497. LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = mods.id_member)
  498. WHERE b.id_board = {raw:board_link}',
  499. array(
  500. 'current_topic' => $topic,
  501. 'board_link' => empty($topic) ? $smcFunc['db_quote']('{int:current_board}', array('current_board' => $board)) : 't.id_board',
  502. )
  503. );
  504. // If there aren't any, skip.
  505. if ($smcFunc['db_num_rows']($request) > 0)
  506. {
  507. $row = $smcFunc['db_fetch_assoc']($request);
  508. // Set the current board.
  509. if (!empty($row['id_board']))
  510. $board = $row['id_board'];
  511. // Basic operating information. (globals... :/)
  512. $board_info = array(
  513. 'id' => $board,
  514. 'moderators' => array(),
  515. 'cat' => array(
  516. 'id' => $row['id_cat'],
  517. 'name' => $row['cname']
  518. ),
  519. 'name' => $row['bname'],
  520. 'description' => $row['description'],
  521. 'num_topics' => $row['num_topics'],
  522. 'unapproved_topics' => $row['unapproved_topics'],
  523. 'unapproved_posts' => $row['unapproved_posts'],
  524. 'unapproved_user_topics' => 0,
  525. 'parent_boards' => getBoardParents($row['id_parent']),
  526. 'parent' => $row['id_parent'],
  527. 'child_level' => $row['child_level'],
  528. 'theme' => $row['id_theme'],
  529. 'override_theme' => !empty($row['override_theme']),
  530. 'profile' => $row['id_profile'],
  531. 'redirect' => $row['redirect'],
  532. 'posts_count' => empty($row['count_posts']),
  533. 'cur_topic_approved' => empty($topic) || $row['approved'],
  534. 'cur_topic_starter' => empty($topic) ? 0 : $row['id_member_started'],
  535. );
  536. // Load the membergroups allowed, and check permissions.
  537. $board_info['groups'] = $row['member_groups'] == '' ? array() : explode(',', $row['member_groups']);
  538. do
  539. {
  540. if (!empty($row['id_moderator']))
  541. $board_info['moderators'][$row['id_moderator']] = array(
  542. 'id' => $row['id_moderator'],
  543. 'name' => $row['real_name'],
  544. 'href' => $scripturl . '?action=profile;u=' . $row['id_moderator'],
  545. 'link' => '<a href="' . $scripturl . '?action=profile;u=' . $row['id_moderator'] . '">' . $row['real_name'] . '</a>'
  546. );
  547. }
  548. while ($row = $smcFunc['db_fetch_assoc']($request));
  549. // If the board only contains unapproved posts and the user isn't an approver then they can't see any topics.
  550. // If that is the case do an additional check to see if they have any topics waiting to be approved.
  551. if ($board_info['num_topics'] == 0 && $modSettings['postmod_active'] && !allowedTo('approve_posts'))
  552. {
  553. $smcFunc['db_free_result']($request); // Free the previous result
  554. $request = $smcFunc['db_query']('', '
  555. SELECT COUNT(id_topic)
  556. FROM {db_prefix}topics
  557. WHERE id_member_started={int:id_member}
  558. AND approved = {int:unapproved}
  559. AND id_board = {int:board}',
  560. array(
  561. 'id_member' => $user_info['id'],
  562. 'unapproved' => 0,
  563. 'board' => $board,
  564. )
  565. );
  566. list ($board_info['unapproved_user_topics']) = $smcFunc['db_fetch_row']($request);
  567. }
  568. if (!empty($modSettings['cache_enable']) && (empty($topic) || $modSettings['cache_enable'] >= 3))
  569. {
  570. // !!! SLOW?
  571. if (!empty($topic))
  572. cache_put_data('topic_board-' . $topic, $board_info, 120);
  573. cache_put_data('board-' . $board, $board_info, 120);
  574. }
  575. }
  576. else
  577. {
  578. // Otherwise the topic is invalid, there are no moderators, etc.
  579. $board_info = array(
  580. 'moderators' => array(),
  581. 'error' => 'exist'
  582. );
  583. $topic = null;
  584. $board = 0;
  585. }
  586. $smcFunc['db_free_result']($request);
  587. }
  588. if (!empty($topic))
  589. $_GET['board'] = (int) $board;
  590. if (!empty($board))
  591. {
  592. // Now check if the user is a moderator.
  593. $user_info['is_mod'] = isset($board_info['moderators'][$user_info['id']]);
  594. if (count(array_intersect($user_info['groups'], $board_info['groups'])) == 0 && !$user_info['is_admin'])
  595. $board_info['error'] = 'access';
  596. // Build up the linktree.
  597. $context['linktree'] = array_merge(
  598. $context['linktree'],
  599. array(array(
  600. 'url' => $scripturl . '#c' . $board_info['cat']['id'],
  601. 'name' => $board_info['cat']['name']
  602. )),
  603. array_reverse($board_info['parent_boards']),
  604. array(array(
  605. 'url' => $scripturl . '?board=' . $board . '.0',
  606. 'name' => $board_info['name']
  607. ))
  608. );
  609. }
  610. // Set the template contextual information.
  611. $context['user']['is_mod'] = &$user_info['is_mod'];
  612. $context['current_topic'] = $topic;
  613. $context['current_board'] = $board;
  614. // Hacker... you can't see this topic, I'll tell you that. (but moderators can!)
  615. if (!empty($board_info['error']) && ($board_info['error'] != 'access' || !$user_info['is_mod']))
  616. {
  617. // The permissions and theme need loading, just to make sure everything goes smoothly.
  618. loadPermissions();
  619. loadTheme();
  620. $_GET['board'] = '';
  621. $_GET['topic'] = '';
  622. // The linktree should not give the game away mate!
  623. $context['linktree'] = array(
  624. array(
  625. 'url' => $scripturl,
  626. 'name' => $context['forum_name_html_safe']
  627. )
  628. );
  629. // If it's a prefetching agent or we're requesting an attachment.
  630. if ((isset($_SERVER['HTTP_X_MOZ']) && $_SERVER['HTTP_X_MOZ'] == 'prefetch') || (!empty($_REQUEST['action']) && $_REQUEST['action'] === 'dlattach'))
  631. {
  632. ob_end_clean();
  633. header('HTTP/1.1 403 Forbidden');
  634. die;
  635. }
  636. elseif ($user_info['is_guest'])
  637. {
  638. loadLanguage('Errors');
  639. is_not_guest($txt['topic_gone']);
  640. }
  641. else
  642. fatal_lang_error('topic_gone', false);
  643. }
  644. if ($user_info['is_mod'])
  645. $user_info['groups'][] = 3;
  646. }
  647. /**
  648. * Load this user's permissions.
  649. */
  650. function loadPermissions()
  651. {
  652. global $user_info, $board, $board_info, $modSettings, $smcFunc, $sourcedir;
  653. if ($user_info['is_admin'])
  654. {
  655. banPermissions();
  656. return;
  657. }
  658. if (!empty($modSettings['cache_enable']))
  659. {
  660. $cache_groups = $user_info['groups'];
  661. asort($cache_groups);
  662. $cache_groups = implode(',', $cache_groups);
  663. // If it's a spider then cache it different.
  664. if ($user_info['possibly_robot'])
  665. $cache_groups .= '-spider';
  666. if ($modSettings['cache_enable'] >= 2 && !empty($board) && ($temp = cache_get_data('permissions:' . $cache_groups . ':' . $board, 240)) != null && time() - 240 > $modSettings['settings_updated'])
  667. {
  668. list ($user_info['permissions']) = $temp;
  669. banPermissions();
  670. return;
  671. }
  672. elseif (($temp = cache_get_data('permissions:' . $cache_groups, 240)) != null && time() - 240 > $modSettings['settings_updated'])
  673. list ($user_info['permissions'], $removals) = $temp;
  674. }
  675. // If it is detected as a robot, and we are restricting permissions as a special group - then implement this.
  676. $spider_restrict = $user_info['possibly_robot'] && !empty($modSettings['spider_group']) ? ' OR (id_group = {int:spider_group} && add_deny = 0)' : '';
  677. if (empty($user_info['permissions']))
  678. {
  679. // Get the general permissions.
  680. $request = $smcFunc['db_query']('', '
  681. SELECT permission, add_deny
  682. FROM {db_prefix}permissions
  683. WHERE id_group IN ({array_int:member_groups})
  684. ' . $spider_restrict,
  685. array(
  686. 'member_groups' => $user_info['groups'],
  687. 'spider_group' => !empty($modSettings['spider_group']) ? $modSettings['spider_group'] : 0,
  688. )
  689. );
  690. $removals = array();
  691. while ($row = $smcFunc['db_fetch_assoc']($request))
  692. {
  693. if (empty($row['add_deny']))
  694. $removals[] = $row['permission'];
  695. else
  696. $user_info['permissions'][] = $row['permission'];
  697. }
  698. $smcFunc['db_free_result']($request);
  699. if (isset($cache_groups))
  700. cache_put_data('permissions:' . $cache_groups, array($user_info['permissions'], $removals), 240);
  701. }
  702. // Get the board permissions.
  703. if (!empty($board))
  704. {
  705. // Make sure the board (if any) has been loaded by loadBoard().
  706. if (!isset($board_info['profile']))
  707. fatal_lang_error('no_board');
  708. $request = $smcFunc['db_query']('', '
  709. SELECT permission, add_deny
  710. FROM {db_prefix}board_permissions
  711. WHERE (id_group IN ({array_int:member_groups})
  712. ' . $spider_restrict . ')
  713. AND id_profile = {int:id_profile}',
  714. array(
  715. 'member_groups' => $user_info['groups'],
  716. 'id_profile' => $board_info['profile'],
  717. 'spider_group' => !empty($modSettings['spider_group']) ? $modSettings['spider_group'] : 0,
  718. )
  719. );
  720. while ($row = $smcFunc['db_fetch_assoc']($request))
  721. {
  722. if (empty($row['add_deny']))
  723. $removals[] = $row['permission'];
  724. else
  725. $user_info['permissions'][] = $row['permission'];
  726. }
  727. $smcFunc['db_free_result']($request);
  728. }
  729. // Remove all the permissions they shouldn't have ;).
  730. if (!empty($modSettings['permission_enable_deny']))
  731. $user_info['permissions'] = array_diff($user_info['permissions'], $removals);
  732. if (isset($cache_groups) && !empty($board) && $modSettings['cache_enable'] >= 2)
  733. cache_put_data('permissions:' . $cache_groups . ':' . $board, array($user_info['permissions'], null), 240);
  734. // Banned? Watch, don't touch..
  735. banPermissions();
  736. // Load the mod cache so we can know what additional boards they should see, but no sense in doing it for guests
  737. if (!$user_info['is_guest'])
  738. {
  739. if (!isset($_SESSION['mc']) || $_SESSION['mc']['time'] <= $modSettings['settings_updated'])
  740. {
  741. require_once($sourcedir . '/Subs-Auth.php');
  742. rebuildModCache();
  743. }
  744. else
  745. $user_info['mod_cache'] = $_SESSION['mc'];
  746. }
  747. }
  748. /**
  749. * Loads an array of users' data by ID or member_name.
  750. *
  751. * @param $users
  752. * @param $is_name
  753. * @param string $set = 'normal'
  754. */
  755. function loadMemberData($users, $is_name = false, $set = 'normal')
  756. {
  757. global $user_profile, $modSettings, $board_info, $smcFunc;
  758. // Can't just look for no users :P.
  759. if (empty($users))
  760. return false;
  761. // Make sure it's an array.
  762. $users = !is_array($users) ? array($users) : array_unique($users);
  763. $loaded_ids = array();
  764. if (!$is_name && !empty($modSettings['cache_enable']) && $modSettings['cache_enable'] >= 3)
  765. {
  766. $users = array_values($users);
  767. for ($i = 0, $n = count($users); $i < $n; $i++)
  768. {
  769. $data = cache_get_data('member_data-' . $set . '-' . $users[$i], 240);
  770. if ($data == null)
  771. continue;
  772. $loaded_ids[] = $data['id_member'];
  773. $user_profile[$data['id_member']] = $data;
  774. unset($users[$i]);
  775. }
  776. }
  777. if ($set == 'normal')
  778. {
  779. $select_columns = '
  780. IFNULL(lo.log_time, 0) AS is_online, IFNULL(a.id_attach, 0) AS id_attach, a.filename, a.attachment_type,
  781. mem.signature, mem.personal_text, mem.location, mem.gender, mem.avatar, mem.id_member, mem.member_name,
  782. mem.real_name, mem.email_address, mem.hide_email, mem.date_registered, mem.website_title, mem.website_url,
  783. mem.birthdate, mem.member_ip, mem.member_ip2, mem.icq, mem.aim, mem.yim, mem.msn, mem.posts, mem.last_login,
  784. mem.karma_good, mem.id_post_group, mem.karma_bad, mem.lngfile, mem.id_group, mem.time_offset, mem.show_online,
  785. mem.buddy_list, mg.online_color AS member_group_color, IFNULL(mg.group_name, {string:blank_string}) AS member_group,
  786. pg.online_color AS post_group_color, IFNULL(pg.group_name, {string:blank_string}) AS post_group, mem.is_activated, mem.warning,
  787. CASE WHEN mem.id_group = 0 OR mg.stars = {string:blank_string} THEN pg.stars ELSE mg.stars END AS stars' . (!empty($modSettings['titlesEnable']) ? ',
  788. mem.usertitle' : '');
  789. $select_tables = '
  790. LEFT JOIN {db_prefix}log_online AS lo ON (lo.id_member = mem.id_member)
  791. LEFT JOIN {db_prefix}attachments AS a ON (a.id_member = mem.id_member)
  792. LEFT JOIN {db_prefix}membergroups AS pg ON (pg.id_group = mem.id_post_group)
  793. LEFT JOIN {db_prefix}membergroups AS mg ON (mg.id_group = mem.id_group)';
  794. }
  795. elseif ($set == 'profile')
  796. {
  797. $select_columns = '
  798. IFNULL(lo.log_time, 0) AS is_online, IFNULL(a.id_attach, 0) AS id_attach, a.filename, a.attachment_type,
  799. mem.signature, mem.personal_text, mem.location, mem.gender, mem.avatar, mem.id_member, mem.member_name,
  800. mem.real_name, mem.email_address, mem.hide_email, mem.date_registered, mem.website_title, mem.website_url,
  801. mem.openid_uri, mem.birthdate, mem.icq, mem.aim, mem.yim, mem.msn, mem.posts, mem.last_login, mem.karma_good,
  802. mem.karma_bad, mem.member_ip, mem.member_ip2, mem.lngfile, mem.id_group, mem.id_theme, mem.buddy_list,
  803. mem.pm_ignore_list, mem.pm_email_notify, mem.pm_receive_from, mem.time_offset' . (!empty($modSettings['titlesEnable']) ? ', mem.usertitle' : '') . ',
  804. mem.time_format, mem.secret_question, mem.is_activated, mem.additional_groups, mem.smiley_set, mem.show_online,
  805. mem.total_time_logged_in, mem.id_post_group, mem.notify_announcements, mem.notify_regularity, mem.notify_send_body,
  806. mem.notify_types, lo.url, mg.online_color AS member_group_color, IFNULL(mg.group_name, {string:blank_string}) AS member_group,
  807. pg.online_color AS post_group_color, IFNULL(pg.group_name, {string:blank_string}) AS post_group, mem.ignore_boards, mem.warning,
  808. CASE WHEN mem.id_group = 0 OR mg.stars = {string:blank_string} THEN pg.stars ELSE mg.stars END AS stars, mem.password_salt, mem.pm_prefs';
  809. $select_tables = '
  810. LEFT JOIN {db_prefix}log_online AS lo ON (lo.id_member = mem.id_member)
  811. LEFT JOIN {db_prefix}attachments AS a ON (a.id_member = mem.id_member)
  812. LEFT JOIN {db_prefix}membergroups AS pg ON (pg.id_group = mem.id_post_group)
  813. LEFT JOIN {db_prefix}membergroups AS mg ON (mg.id_group = mem.id_group)';
  814. }
  815. elseif ($set == 'minimal')
  816. {
  817. $select_columns = '
  818. mem.id_member, mem.member_name, mem.real_name, mem.email_address, mem.hide_email, mem.date_registered,
  819. mem.posts, mem.last_login, mem.member_ip, mem.member_ip2, mem.lngfile, mem.id_group';
  820. $select_tables = '';
  821. }
  822. else
  823. trigger_error('loadMemberData(): Invalid member data set \'' . $set . '\'', E_USER_WARNING);
  824. if (!empty($users))
  825. {
  826. // Load the member's data.
  827. $request = $smcFunc['db_query']('', '
  828. SELECT' . $select_columns . '
  829. FROM {db_prefix}members AS mem' . $select_tables . '
  830. WHERE mem.' . ($is_name ? 'member_name' : 'id_member') . (count($users) == 1 ? ' = {' . ($is_name ? 'string' : 'int') . ':users}' : ' IN ({' . ($is_name ? 'array_string' : 'array_int') . ':users})'),
  831. array(
  832. 'blank_string' => '',
  833. 'users' => count($users) == 1 ? current($users) : $users,
  834. )
  835. );
  836. $new_loaded_ids = array();
  837. while ($row = $smcFunc['db_fetch_assoc']($request))
  838. {
  839. $new_loaded_ids[] = $row['id_member'];
  840. $loaded_ids[] = $row['id_member'];
  841. $row['options'] = array();
  842. $user_profile[$row['id_member']] = $row;
  843. }
  844. $smcFunc['db_free_result']($request);
  845. }
  846. if (!empty($new_loaded_ids) && $set !== 'minimal')
  847. {
  848. $request = $smcFunc['db_query']('', '
  849. SELECT *
  850. FROM {db_prefix}themes
  851. WHERE id_member' . (count($new_loaded_ids) == 1 ? ' = {int:loaded_ids}' : ' IN ({array_int:loaded_ids})'),
  852. array(
  853. 'loaded_ids' => count($new_loaded_ids) == 1 ? $new_loaded_ids[0] : $new_loaded_ids,
  854. )
  855. );
  856. while ($row = $smcFunc['db_fetch_assoc']($request))
  857. $user_profile[$row['id_member']]['options'][$row['variable']] = $row['value'];
  858. $smcFunc['db_free_result']($request);
  859. }
  860. if (!empty($new_loaded_ids) && !empty($modSettings['cache_enable']) && $modSettings['cache_enable'] >= 3)
  861. {
  862. for ($i = 0, $n = count($new_loaded_ids); $i < $n; $i++)
  863. cache_put_data('member_data-' . $set . '-' . $new_loaded_ids[$i], $user_profile[$new_loaded_ids[$i]], 240);
  864. }
  865. // Are we loading any moderators? If so, fix their group data...
  866. if (!empty($loaded_ids) && !empty($board_info['moderators']) && $set === 'normal' && count($temp_mods = array_intersect($loaded_ids, array_keys($board_info['moderators']))) !== 0)
  867. {
  868. if (($row = cache_get_data('moderator_group_info', 480)) == null)
  869. {
  870. $request = $smcFunc['db_query']('', '
  871. SELECT group_name AS member_group, online_color AS member_group_color, stars
  872. FROM {db_prefix}membergroups
  873. WHERE id_group = {int:moderator_group}
  874. LIMIT 1',
  875. array(
  876. 'moderator_group' => 3,
  877. )
  878. );
  879. $row = $smcFunc['db_fetch_assoc']($request);
  880. $smcFunc['db_free_result']($request);
  881. cache_put_data('moderator_group_info', $row, 480);
  882. }
  883. foreach ($temp_mods as $id)
  884. {
  885. // By popular demand, don't show admins or global moderators as moderators.
  886. if ($user_profile[$id]['id_group'] != 1 && $user_profile[$id]['id_group'] != 2)
  887. $user_profile[$id]['member_group'] = $row['member_group'];
  888. // If the Moderator group has no color or stars, but their group does... don't overwrite.
  889. if (!empty($row['stars']))
  890. $user_profile[$id]['stars'] = $row['stars'];
  891. if (!empty($row['member_group_color']))
  892. $user_profile[$id]['member_group_color'] = $row['member_group_color'];
  893. }
  894. }
  895. return empty($loaded_ids) ? false : $loaded_ids;
  896. }
  897. /**
  898. * Loads the user's basic values... meant for template/theme usage.
  899. *
  900. * @param $user
  901. * @param bool $display_custom_fields
  902. */
  903. function loadMemberContext($user, $display_custom_fields = false)
  904. {
  905. global $memberContext, $user_profile, $txt, $scripturl, $user_info;
  906. global $context, $modSettings, $board_info, $settings;
  907. global $smcFunc;
  908. static $dataLoaded = array();
  909. // If this person's data is already loaded, skip it.
  910. if (isset($dataLoaded[$user]))
  911. return true;
  912. // We can't load guests or members not loaded by loadMemberData()!
  913. if ($user == 0)
  914. return false;
  915. if (!isset($user_profile[$user]))
  916. {
  917. trigger_error('loadMemberContext(): member id ' . $user . ' not previously loaded by loadMemberData()', E_USER_WARNING);
  918. return false;
  919. }
  920. // Well, it's loaded now anyhow.
  921. $dataLoaded[$user] = true;
  922. $profile = $user_profile[$user];
  923. // Censor everything.
  924. censorText($profile['signature']);
  925. censorText($profile['personal_text']);
  926. censorText($profile['location']);
  927. // Set things up to be used before hand.
  928. $gendertxt = $profile['gender'] == 2 ? $txt['female'] : ($profile['gender'] == 1 ? $txt['male'] : '');
  929. $profile['signature'] = str_replace(array("\n", "\r"), array('<br />', ''), $profile['signature']);
  930. $profile['signature'] = parse_bbc($profile['signature'], true, 'sig' . $profile['id_member']);
  931. $profile['is_online'] = (!empty($profile['show_online']) || allowedTo('moderate_forum')) && $profile['is_online'] > 0;
  932. $profile['stars'] = empty($profile['stars']) ? array('', '') : explode('#', $profile['stars']);
  933. // Setup the buddy status here (One whole in_array call saved :P)
  934. $profile['buddy'] = in_array($profile['id_member'], $user_info['buddies']);
  935. $buddy_list = !empty($profile['buddy_list']) ? explode(',', $profile['buddy_list']) : array();
  936. // If we're always html resizing, assume it's too large.
  937. if ($modSettings['avatar_action_too_large'] == 'option_html_resize' || $modSettings['avatar_action_too_large'] == 'option_js_resize')
  938. {
  939. $avatar_width = !empty($modSettings['avatar_max_width_external']) ? ' width="' . $modSettings['avatar_max_width_external'] . '"' : '';
  940. $avatar_height = !empty($modSettings['avatar_max_height_external']) ? ' height="' . $modSettings['avatar_max_height_external'] . '"' : '';
  941. }
  942. else
  943. {
  944. $avatar_width = '';
  945. $avatar_height = '';
  946. }
  947. // What a monstrous array...
  948. $memberContext[$user] = array(
  949. 'username' => $profile['member_name'],
  950. 'name' => $profile['real_name'],
  951. 'id' => $profile['id_member'],
  952. 'is_buddy' => $profile['buddy'],
  953. 'is_reverse_buddy' => in_array($user_info['id'], $buddy_list),
  954. 'buddies' => $buddy_list,
  955. 'title' => !empty($modSettings['titlesEnable']) ? $profile['usertitle'] : '',
  956. 'href' => $scripturl . '?action=profile;u=' . $profile['id_member'],
  957. 'link' => '<a href="' . $scripturl . '?action=profile;u=' . $profile['id_member'] . '" title="' . $txt['profile_of'] . ' ' . $profile['real_name'] . '">' . $profile['real_name'] . '</a>',
  958. 'email' => $profile['email_address'],
  959. 'show_email' => showEmailAddress(!empty($profile['hide_email']), $profile['id_member']),
  960. 'registered' => empty($profile['date_registered']) ? $txt['not_applicable'] : timeformat($profile['date_registered']),
  961. 'registered_timestamp' => empty($profile['date_registered']) ? 0 : forum_time(true, $profile['date_registered']),
  962. 'blurb' => $profile['personal_text'],
  963. 'gender' => array(
  964. 'name' => $gendertxt,
  965. 'image' => !empty($profile['gender']) ? '<img class="gender" src="' . $settings['images_url'] . '/' . ($profile['gender'] == 1 ? 'Male' : 'Female') . '.gif" alt="' . $gendertxt . '" />' : ''
  966. ),
  967. 'website' => array(
  968. 'title' => $profile['website_title'],
  969. 'url' => $profile['website_url'],
  970. ),
  971. 'birth_date' => empty($profile['birthdate']) || $profile['birthdate'] === '0001-01-01' ? '0000-00-00' : (substr($profile['birthdate'], 0, 4) === '0004' ? '0000' . substr($profile['birthdate'], 4) : $profile['birthdate']),
  972. 'signature' => $profile['signature'],
  973. 'location' => $profile['location'],
  974. 'icq' => $profile['icq'] != '' && (empty($modSettings['guest_hideContacts']) || !$user_info['is_guest']) ? array(
  975. 'name' => $profile['icq'],
  976. 'href' => 'http://www.icq.com/whitepages/about_me.php?uin=' . $profile['icq'],
  977. 'link' => '<a class="icq new_win" href="http://www.icq.com/whitepages/about_me.php?uin=' . $profile['icq'] . '" target="_blank" title="' . $txt['icq_title'] . ' - ' . $profile['icq'] . '"><img src="http://status.icq.com/online.gif?img=5&amp;icq=' . $profile['icq'] . '" alt="' . $txt['icq_title'] . ' - ' . $profile['icq'] . '" width="18" height="18" /></a>',
  978. 'link_text' => '<a class="icq extern" href="http://www.icq.com/whitepages/about_me.php?uin=' . $profile['icq'] . '" title="' . $txt['icq_title'] . ' - ' . $profile['icq'] . '">' . $profile['icq'] . '</a>',
  979. ) : array('name' => '', 'add' => '', 'href' => '', 'link' => '', 'link_text' => ''),
  980. 'aim' => $profile['aim'] != '' && (empty($modSettings['guest_hideContacts']) || !$user_info['is_guest']) ? array(
  981. 'name' => $profile['aim'],
  982. 'href' => 'aim:goim?screenname=' . urlencode(strtr($profile['aim'], array(' ' => '%20'))) . '&amp;message=' . $txt['aim_default_message'],
  983. 'link' => '<a class="aim" href="aim:goim?screenname=' . urlencode(strtr($profile['aim'], array(' ' => '%20'))) . '&amp;message=' . $txt['aim_default_message'] . '" title="' . $txt['aim_title'] . ' - ' . $profile['aim'] . '"><img src="' . $settings['images_url'] . '/aim.gif" alt="' . $txt['aim_title'] . ' - ' . $profile['aim'] . '" /></a>',
  984. 'link_text' => '<a class="aim" href="aim:goim?screenname=' . urlencode(strtr($profile['aim'], array(' ' => '%20'))) . '&amp;message=' . $txt['aim_default_message'] . '" title="' . $txt['aim_title'] . ' - ' . $profile['aim'] . '">' . $profile['aim'] . '</a>'
  985. ) : array('name' => '', 'href' => '', 'link' => '', 'link_text' => ''),
  986. 'yim' => $profile['yim'] != '' && (empty($modSettings['guest_hideContacts']) || !$user_info['is_guest']) ? array(
  987. 'name' => $profile['yim'],
  988. 'href' => 'http://edit.yahoo.com/config/send_webmesg?.target=' . urlencode($profile['yim']),
  989. 'link' => '<a class="yim" href="http://edit.yahoo.com/config/send_webmesg?.target=' . urlencode($profile['yim']) . '" title="' . $txt['yim_title'] . ' - ' . $profile['yim'] . '"><img src="http://opi.yahoo.com/online?u=' . urlencode($profile['yim']) . '&amp;m=g&amp;t=0" alt="' . $txt['yim_title'] . ' - ' . $profile['yim'] . '" /></a>',
  990. 'link_text' => '<a class="yim" href="http://edit.yahoo.com/config/send_webmesg?.target=' . urlencode($profile['yim']) . '" title="' . $txt['yim_title'] . ' - ' . $profile['yim'] . '">' . $profile['yim'] . '</a>'
  991. ) : array('name' => '', 'href' => '', 'link' => '', 'link_text' => ''),
  992. 'msn' => $profile['msn'] !='' && (empty($modSettings['guest_hideContacts']) || !$user_info['is_guest']) ? array(
  993. 'name' => $profile['msn'],
  994. 'href' => 'http://members.msn.com/' . $profile['msn'],
  995. 'link' => '<a class="msn new_win" href="http://members.msn.com/' . $profile['msn'] . '" title="' . $txt['msn_title'] . ' - ' . $profile['msn'] . '"><img src="' . $settings['images_url'] . '/msntalk.gif" alt="' . $txt['msn_title'] . ' - ' . $profile['msn'] . '" /></a>',
  996. 'link_text' => '<a class="msn new_win" href="http://members.msn.com/' . $profile['msn'] . '" title="' . $txt['msn_title'] . ' - ' . $profile['msn'] . '">' . $profile['msn'] . '</a>'
  997. ) : array('name' => '', 'href' => '', 'link' => '', 'link_text' => ''),
  998. 'real_posts' => $profile['posts'],
  999. 'posts' => $profile['posts'] > 500000 ? $txt['geek'] : comma_format($profile['posts']),
  1000. 'avatar' => array(
  1001. 'name' => $profile['avatar'],
  1002. 'image' => $profile['avatar'] == '' ? ($profile['id_attach'] > 0 ? '<img class="avatar" src="' . (empty($profile['attachment_type']) ? $scripturl . '?action=dlattach;attach=' . $profile['id_attach'] . ';type=avatar' : $modSettings['custom_avatar_url'] . '/' . $profile['filename']) . '" alt="" />' : '') : (stristr($profile['avatar'], 'http://') ? '<img class="avatar" src="' . $profile['avatar'] . '"' . $avatar_width . $avatar_height . ' alt="" />' : '<img class="avatar" src="' . $modSettings['avatar_url'] . '/' . htmlspecialchars($profile['avatar']) . '" alt="" />'),
  1003. 'href' => $profile['avatar'] == '' ? ($profile['id_attach'] > 0 ? (empty($profile['attachment_type']) ? $scripturl . '?action=dlattach;attach=' . $profile['id_attach'] . ';type=avatar' : $modSettings['custom_avatar_url'] . '/' . $profile['filename']) : '') : (stristr($profile['avatar'], 'http://') ? $profile['avatar'] : $modSettings['avatar_url'] . '/' . $profile['avatar']),
  1004. 'url' => $profile['avatar'] == '' ? '' : (stristr($profile['avatar'], 'http://') ? $profile['avatar'] : $modSettings['avatar_url'] . '/' . $profile['avatar'])
  1005. ),
  1006. 'last_login' => empty($profile['last_login']) ? $txt['never'] : timeformat($profile['last_login']),
  1007. 'last_login_timestamp' => empty($profile['last_login']) ? 0 : forum_time(0, $profile['last_login']),
  1008. 'karma' => array(
  1009. 'good' => $profile['karma_good'],
  1010. 'bad' => $profile['karma_bad'],
  1011. 'allow' => !$user_info['is_guest'] && !empty($modSettings['karmaMode']) && $user_info['id'] != $user && allowedTo('karma_edit') &&
  1012. ($user_info['posts'] >= $modSettings['karmaMinPosts'] || $user_info['is_admin']),
  1013. ),
  1014. 'ip' => htmlspecialchars($profile['member_ip']),
  1015. 'ip2' => htmlspecialchars($profile['member_ip2']),
  1016. 'online' => array(
  1017. 'is_online' => $profile['is_online'],
  1018. 'text' => $txt[$profile['is_online'] ? 'online' : 'offline'],
  1019. 'href' => $scripturl . '?action=pm;sa=send;u=' . $profile['id_member'],
  1020. 'link' => '<a href="' . $scripturl . '?action=pm;sa=send;u=' . $profile['id_member'] . '">' . $txt[$profile['is_online'] ? 'online' : 'offline'] . '</a>',
  1021. 'image_href' => $settings['images_url'] . '/' . ($profile['buddy'] ? 'buddy_' : '') . ($profile['is_online'] ? 'useron' : 'useroff') . '.gif',
  1022. 'label' => $txt[$profile['is_online'] ? 'online' : 'offline']
  1023. ),
  1024. 'language' => $smcFunc['ucwords'](strtr($profile['lngfile'], array('_' => ' ', '-utf8' => ''))),
  1025. 'is_activated' => isset($profile['is_activated']) ? $profile['is_activated'] : 1,
  1026. 'is_banned' => isset($profile['is_activated']) ? $profile['is_activated'] >= 10 : 0,
  1027. 'options' => $profile['options'],
  1028. 'is_guest' => false,
  1029. 'group' => $profile['member_group'],
  1030. 'group_color' => $profile['member_group_color'],
  1031. 'group_id' => $profile['id_group'],
  1032. 'post_group' => $profile['post_group'],
  1033. 'post_group_color' => $profile['post_group_color'],
  1034. 'group_stars' => str_repeat('<img src="' . str_replace('$language', $context['user']['language'], isset($profile['stars'][1]) ? $settings['images_url'] . '/' . $profile['stars'][1] : '') . '" alt="*" />', empty($profile['stars'][0]) || empty($profile['stars'][1]) ? 0 : $profile['stars'][0]),
  1035. 'warning' => $profile['warning'],
  1036. 'warning_status' => !empty($modSettings['warning_mute']) && $modSettings['warning_mute'] <= $profile['warning'] ? 'mute' : (!empty($modSettings['warning_moderate']) && $modSettings['warning_moderate'] <= $profile['warning'] ? 'moderate' : (!empty($modSettings['warning_watch']) && $modSettings['warning_watch'] <= $profile['warning'] ? 'watch' : (''))),
  1037. 'local_time' => timeformat(time() + ($profile['time_offset'] - $user_info['time_offset']) * 3600, false),
  1038. );
  1039. // First do a quick run through to make sure there is something to be shown.
  1040. $memberContext[$user]['has_messenger'] = false;
  1041. foreach (array('icq', 'msn', 'aim', 'yim') as $messenger)
  1042. {
  1043. if (!isset($context['disabled_fields'][$messenger]) && !empty($memberContext[$user][$messenger]['link']))
  1044. {
  1045. $memberContext[$user]['has_messenger'] = true;
  1046. break;
  1047. }
  1048. }
  1049. // Are we also loading the members custom fields into context?
  1050. if ($display_custom_fields && !empty($modSettings['displayFields']))
  1051. {
  1052. $memberContext[$user]['custom_fields'] = array();
  1053. if (!isset($context['display_fields']))
  1054. $context['display_fields'] = unserialize($modSettings['displayFields']);
  1055. foreach ($context['display_fields'] as $custom)
  1056. {
  1057. if (empty($custom['title']) || empty($profile['options'][$custom['colname']]))
  1058. continue;
  1059. $value = $profile['options'][$custom['colname']];
  1060. // BBC?
  1061. if ($custom['bbc'])
  1062. $value = parse_bbc($value);
  1063. // ... or checkbox?
  1064. elseif (isset($custom['type']) && $custom['type'] == 'check')
  1065. $value = $value ? $txt['yes'] : $txt['no'];
  1066. // Enclosing the user input within some other text?
  1067. if (!empty($custom['enclose']))
  1068. $value = strtr($custom['enclose'], array(
  1069. '{SCRIPTURL}' => $scripturl,
  1070. '{IMAGES_URL}' => $settings['images_url'],
  1071. '{DEFAULT_IMAGES_URL}' => $settings['default_images_url'],
  1072. '{INPUT}' => $value,
  1073. ));
  1074. $memberContext[$user]['custom_fields'][] = array(
  1075. 'title' => $custom['title'],
  1076. 'colname' => $custom['colname'],
  1077. 'value' => $value,
  1078. 'placement' => !empty($custom['placement']) ? $custom['placement'] : 0,
  1079. );
  1080. }
  1081. }
  1082. return true;
  1083. }
  1084. /**
  1085. * This function is... detecting the browser, right.
  1086. */
  1087. function detectBrowser()
  1088. {
  1089. global $context, $user_info;
  1090. // The following determines the user agent (browser) as best it can.
  1091. $context['browser'] = array(
  1092. 'is_opera' => strpos($_SERVER['HTTP_USER_AGENT'], 'Opera') !== false,
  1093. 'is_opera6' => strpos($_SERVER['HTTP_USER_AGENT'], 'Opera 6') !== false,
  1094. 'is_opera7' => strpos($_SERVER['HTTP_USER_AGENT'], 'Opera 7') !== false || strpos($_SERVER['HTTP_USER_AGENT'], 'Opera/7') !== false,
  1095. 'is_opera8' => strpos($_SERVER['HTTP_USER_AGENT'], 'Opera 8') !== false || strpos($_SERVER['HTTP_USER_AGENT'], 'Opera/8') !== false,
  1096. 'is_opera9' => preg_match('~Opera[ /]9(?!\\.[89])~', $_SERVER['HTTP_USER_AGENT']) === 1,
  1097. 'is_opera10' => preg_match('~Opera[ /]10\\.~', $_SERVER['HTTP_USER_AGENT']) === 1 || (preg_match('~Opera[ /]9\\.[89]~', $_SERVER['HTTP_USER_AGENT']) === 1 && preg_match('~Version/1[0-9]\\.~', $_SERVER['HTTP_USER_AGENT']) === 1),
  1098. 'is_ie4' => strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE 4') !== false && strpos($_SERVER['HTTP_USER_AGENT'], 'WebTV') === false,
  1099. 'is_webkit' => strpos($_SERVER['HTTP_USER_AGENT'], 'AppleWebKit') !== false,
  1100. 'is_mac_ie' => strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE 5.') !== false && strpos($_SERVER['HTTP_USER_AGENT'], 'Mac') !== false,
  1101. 'is_web_tv' => strpos($_SERVER['HTTP_USER_AGENT'], 'WebTV') !== false,
  1102. 'is_konqueror' => strpos($_SERVER['HTTP_USER_AGENT'], 'Konqueror') !== false,
  1103. 'is_firefox' => preg_match('~(?:Firefox|Ice[wW]easel|IceCat)/~', $_SERVER['HTTP_USER_AGENT']) === 1,
  1104. 'is_firefox1' => preg_match('~(?:Firefox|Ice[wW]easel|IceCat)/1\\.~', $_SERVER['HTTP_USER_AGENT']) === 1,
  1105. 'is_firefox2' => preg_match('~(?:Firefox|Ice[wW]easel|IceCat)/2\\.~', $_SERVER['HTTP_USER_AGENT']) === 1,
  1106. 'is_firefox3' => preg_match('~(?:Firefox|Ice[wW]easel|IceCat|Shiretoko|Minefield)/3\\.~', $_SERVER['HTTP_USER_AGENT']) === 1,
  1107. 'is_iphone' => strpos($_SERVER['HTTP_USER_AGENT'], 'iPhone') !== false || strpos($_SERVER['HTTP_USER_AGENT'], 'iPod') !== false,
  1108. 'is_android' => strpos($_SERVER['HTTP_USER_AGENT'], 'Android') !== false,
  1109. );
  1110. $context['browser']['is_chrome'] = $context['browser']['is_webkit'] && strpos($_SERVER['HTTP_USER_AGENT'], 'Chrome') !== false;
  1111. $context['browser']['is_safari'] = !$context['browser']['is_chrome'] && strpos($_SERVER['HTTP_USER_AGENT'], 'Safari') !== false;
  1112. $context['browser']['is_gecko'] = strpos($_SERVER['HTTP_USER_AGENT'], 'Gecko') !== false && !$context['browser']['is_webkit'] && !$context['browser']['is_konqueror'];
  1113. // Internet Explorer 5 and 6 are often "emulated".
  1114. $context['browser']['is_ie8'] = !$context['browser']['is_opera'] && !$context['browser']['is_gecko'] && !$context['browser']['is_web_tv'] && strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE 8') !== false;
  1115. $context['browser']['is_ie7'] = !$context['browser']['is_opera'] && !$context['browser']['is_gecko'] && !$context['browser']['is_web_tv'] && strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE 7') !== false && !$context['browser']['is_ie8'];
  1116. $context['browser']['is_ie6'] = !$context['browser']['is_opera'] && !$context['browser']['is_gecko'] && !$context['browser']['is_web_tv'] && strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE 6') !== false && !$context['browser']['is_ie8'] && !$context['browser']['is_ie7'];
  1117. $context['browser']['is_ie5.5'] = !$context['browser']['is_opera'] && !$context['browser']['is_gecko'] && !$context['browser']['is_web_tv'] && strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE 5.5') !== false;
  1118. $context['browser']['is_ie5'] = !$context['browser']['is_opera'] && !$context['browser']['is_gecko'] && !$context['browser']['is_web_tv'] && strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE 5.0') !== false;
  1119. $context['browser']['is_ie'] = $context['browser']['is_ie4'] || $context['browser']['is_ie5'] || $context['browser']['is_ie5.5'] || $context['browser']['is_ie6'] || $context['browser']['is_ie7'] || $context['browser']['is_ie8'];
  1120. // Before IE8 we need to fix IE... lots!
  1121. $context['browser']['ie_standards_fix'] = !$context['browser']['is_ie8'];
  1122. $context['browser']['needs_size_fix'] = ($context['browser']['is_ie5'] || $context['browser']['is_ie5.5'] || $context['browser']['is_ie4'] || $context['browser']['is_opera6']) && strpos($_SERVER['HTTP_USER_AGENT'], 'Mac') === false;
  1123. // This isn't meant to be reliable, it's just meant to catch most bots to prevent PHPSESSID from showing up.
  1124. $context['browser']['possibly_robot'] = !empty($user_info['possibly_robot']);
  1125. // Robots shouldn't be logging in or registering. So, they aren't a bot. Better to be wrong than sorry (or people won't be able to log in!), anyway.
  1126. if ((isset($_REQUEST['action']) && in_array($_REQUEST['action'], array('login', 'login2', 'register'))) || !$user_info['is_guest'])
  1127. $context['browser']['possibly_robot'] = false;
  1128. }
  1129. /**
  1130. * Load a theme, by ID.
  1131. *
  1132. * @param int $id_theme = 0
  1133. * @parambool $initialize = true
  1134. */
  1135. function loadTheme($id_theme = 0, $initialize = true)
  1136. {
  1137. global $user_info, $user_settings, $board_info, $sc, $boarddir;
  1138. global $txt, $boardurl, $scripturl, $mbname, $modSettings, $language;
  1139. global $context, $settings, $options, $sourcedir, $ssi_theme, $smcFunc;
  1140. // The theme was specified by parameter.
  1141. if (!empty($id_theme))
  1142. $id_theme = (int) $id_theme;
  1143. // The theme was specified by REQUEST.
  1144. elseif (!empty($_REQUEST['theme']) && (!empty($modSettings['theme_allow']) || allowedTo('admin_forum')))
  1145. {
  1146. $id_theme = (int) $_REQUEST['theme'];
  1147. $_SESSION['id_theme'] = $id_theme;
  1148. }
  1149. // The theme was specified by REQUEST... previously.
  1150. elseif (!empty($_SESSION['id_theme']) && (!empty($modSettings['theme_allow']) || allowedTo('admin_forum')))
  1151. $id_theme = (int) $_SESSION['id_theme'];
  1152. // The theme is just the user's choice. (might use ?board=1;theme=0 to force board theme.)
  1153. elseif (!empty($user_info['theme']) && !isset($_REQUEST['theme']) && (!empty($modSettings['theme_allow']) || allowedTo('admin_forum')))
  1154. $id_theme = $user_info['theme'];
  1155. // The theme was specified by the board.
  1156. elseif (!empty($board_info['theme']))
  1157. $id_theme = $board_info['theme'];
  1158. // The theme is the forum's default.
  1159. else
  1160. $id_theme = $modSettings['theme_guests'];
  1161. // Verify the id_theme... no foul play.
  1162. // Always allow the board specific theme, if they are overriding.
  1163. if (!empty($board_info['theme']) && $board_info['override_theme'])
  1164. $id_theme = $board_info['theme'];
  1165. // If they have specified a particular theme to use with SSI allow it to be used.
  1166. elseif (!empty($ssi_theme) && $id_theme == $ssi_theme)
  1167. $id_theme = (int) $id_theme;
  1168. elseif (!empty($modSettings['knownThemes']) && !allowedTo('admin_forum'))
  1169. {
  1170. $themes = explode(',', $modSettings['knownThemes']);
  1171. if (!in_array($id_theme, $themes))
  1172. $id_theme = $modSettings['theme_guests'];
  1173. else
  1174. $id_theme = (int) $id_theme;
  1175. }
  1176. else
  1177. $id_theme = (int) $id_theme;
  1178. $member = empty($user_info['id']) ? -1 : $user_info['id'];
  1179. if (!empty($modSettings['cache_enable']) && $modSettings['cache_enable'] >= 2 && ($temp = cache_get_data('theme_settings-' . $id_theme . ':' . $member, 60)) != null && time() - 60 > $modSettings['settings_updated'])
  1180. {
  1181. $themeData = $temp;
  1182. $flag = true;
  1183. }
  1184. elseif (($temp = cache_get_data('theme_settings-' . $id_theme, 90)) != null && time() - 60 > $modSettings['settings_updated'])
  1185. $themeData = $temp + array($member => array());
  1186. else
  1187. $themeData = array(-1 => array(), 0 => array(), $member => array());
  1188. if (empty($flag))
  1189. {
  1190. // Load variables from the current or default theme, global or this user's.
  1191. $result = $smcFunc['db_query']('', '
  1192. SELECT variable, value, id_member, id_theme
  1193. FROM {db_prefix}themes
  1194. WHERE id_member' . (empty($themeData[0]) ? ' IN (-1, 0, {int:id_member})' : ' = {int:id_member}') . '
  1195. AND id_theme' . ($id_theme == 1 ? ' = {int:id_theme}' : ' IN ({int:id_theme}, 1)'),
  1196. array(
  1197. 'id_theme' => $id_theme,
  1198. 'id_member' => $member,
  1199. )
  1200. );
  1201. // Pick between $settings and $options depending on whose data it is.
  1202. while ($row = $smcFunc['db_fetch_assoc']($result))
  1203. {
  1204. // There are just things we shouldn't be able to change as members.
  1205. if ($row['id_member'] != 0 && in_array($row['variable'], array('actual_theme_url', 'actual_images_url', 'base_theme_dir', 'base_theme_url', 'default_images_url', 'default_theme_dir', 'default_theme_url', 'default_template', 'images_url', 'number_recent_posts', 'smiley_sets_default', 'theme_dir', 'theme_id', 'theme_layers', 'theme_templates', 'theme_url')))
  1206. continue;
  1207. // If this is the theme_dir of the default theme, store it.
  1208. if (in_array($row['variable'], array('theme_dir', 'theme_url', 'images_url')) && $row['id_theme'] == '1' && empty($row['id_member']))
  1209. $themeData[0]['default_' . $row['variable']] = $row['value'];
  1210. // If this isn't set yet, is a theme option, or is not the default theme..
  1211. if (!isset($themeData[$row['id_member']][$row['variable']]) || $row['id_theme'] != '1')
  1212. $themeData[$row['id_member']][$row['variable']] = substr($row['variable'], 0, 5) == 'show_' ? $row['value'] == '1' : $row['value'];
  1213. }
  1214. $smcFunc['db_free_result']($result);
  1215. if (!empty($themeData[-1]))
  1216. foreach ($themeData[-1] as $k => $v)
  1217. {
  1218. if (!isset($themeData[$member][$k]))
  1219. $themeData[$member][$k] = $v;
  1220. }
  1221. if (!empty($modSettings['cache_enable']) && $modSettings['cache_enable'] >= 2)
  1222. cache_put_data('theme_settings-' . $id_theme . ':' . $member, $themeData, 60);
  1223. // Only if we didn't already load that part of the cache...
  1224. elseif (!isset($temp))
  1225. cache_put_data('theme_settings-' . $id_theme, array(-1 => $themeData[-1], 0 => $themeData[0]), 90);
  1226. }
  1227. $settings = $themeData[0];
  1228. $options = $themeData[$member];
  1229. $settings['theme_id'] = $id_theme;
  1230. $settings['actual_theme_url'] = $settings['theme_url'];
  1231. $settings['actual_images_url'] = $settings['images_url'];
  1232. $settings['actual_theme_dir'] = $settings['theme_dir'];
  1233. $settings['template_dirs'] = array();
  1234. // This theme first.
  1235. $settings['template_dirs'][] = $settings['theme_dir'];
  1236. // Based on theme (if there is one).
  1237. if (!empty($settings['base_theme_dir']))
  1238. $settings['template_dirs'][] = $settings['base_theme_dir'];
  1239. // Lastly the default theme.
  1240. if ($settings['theme_dir'] != $settings['default_theme_dir'])
  1241. $settings['template_dirs'][] = $settings['default_theme_dir'];
  1242. if (!$initialize)
  1243. return;
  1244. // Check to see if they're accessing it from the wrong place.
  1245. if (isset($_SERVER['HTTP_HOST']) || isset($_SERVER['SERVER_NAME']))
  1246. {
  1247. $detected_url = isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) == 'on' ? 'https://' : 'http://';
  1248. $detected_url .= empty($_SERVER['HTTP_HOST']) ? $_SERVER['SERVER_NAME'] . (empty($_SERVER['SERVER_PORT']) || $_SERVER['SERVER_PORT'] == '80' ? '' : ':' . $_SERVER['SERVER_PORT']) : $_SERVER['HTTP_HOST'];
  1249. $temp = preg_replace('~/' . basename($scripturl) . '(/.+)?$~', '', strtr(dirname($_SERVER['PHP_SELF']), '\\', '/'));
  1250. if ($temp != '/')
  1251. $detected_url .= $temp;
  1252. }
  1253. if (isset($detected_url) && $detected_url != $boardurl)
  1254. {
  1255. // Try #1 - check if it's in a list of alias addresses.
  1256. if (!empty($modSettings['forum_alias_urls']))
  1257. {
  1258. $aliases = explode(',', $modSettings['forum_alias_urls']);
  1259. foreach ($aliases as $alias)
  1260. {
  1261. // Rip off all the boring parts, spaces, etc.
  1262. if ($detected_url == trim($alias) || strtr($detected_url, array('http://' => '', 'https://' => '')) == trim($alias))
  1263. $do_fix = true;
  1264. }
  1265. }
  1266. // Hmm... check #2 - is it just different by a www? Send them to the correct place!!
  1267. if (empty($do_fix) && strtr($detected_url, array('://' => '://www.')) == $boardurl && (empty($_GET) || count($_GET) == 1) && SMF != 'SSI')
  1268. {
  1269. // Okay, this seems weird, but we don't want an endless loop - this will make $_GET not empty ;).
  1270. if (empty($_GET))
  1271. redirectexit('wwwRedirect');
  1272. else
  1273. {
  1274. list ($k, $v) = each($_GET);
  1275. if ($k != 'wwwRedirect')
  1276. redirectexit('wwwRedirect;' . $k . '=' . $v);
  1277. }
  1278. }
  1279. // #3 is just a check for SSL...
  1280. if (strtr($detected_url, array('https://' => 'http://')) == $boardurl)
  1281. $do_fix = true;
  1282. // Okay, #4 - perhaps it's an IP address? We're gonna want to use that one, then. (assuming it's the IP or something...)
  1283. if (!empty($do_fix) || preg_match('~^http[s]?://(?:[\d\.:]+|\[[\d:]+\](?::\d+)?)(?:$|/)~', $detected_url) == 1)
  1284. {
  1285. // Caching is good ;).
  1286. $oldurl = $boardurl;
  1287. // Fix $boardurl and $scripturl.
  1288. $boardurl = $detected_url;
  1289. $scripturl = strtr($scripturl, array($oldurl => $boardurl));
  1290. $_SERVER['REQUEST_URL'] = strtr($_SERVER['REQUEST_URL'], array($oldurl => $boardurl));
  1291. // Fix the theme urls...
  1292. $settings['theme_url'] = strtr($settings['theme_url'], array($oldurl => $boardurl));
  1293. $settings['default_theme_url'] = strtr($settings['default_theme_url'], array($oldurl => $boardurl));
  1294. $settings['actual_theme_url'] = strtr($settings['actual_theme_url'], array($oldurl => $boardurl));
  1295. $settings['images_url'] = strtr($settings['images_url'], array($oldurl => $boardurl));
  1296. $settings['default_images_url'] = strtr($settings['default_images_url'], array($oldurl => $boardurl));
  1297. $settings['actual_images_url'] = strtr($settings['actual_images_url'], array($oldurl => $boardurl));
  1298. // And just a few mod settings :).
  1299. $modSettings['smileys_url'] = strtr($modSettings['smileys_url'], array($oldurl => $boardurl));
  1300. $modSettings['avatar_url'] = strtr($modSettings['avatar_url'], array($oldurl => $boardurl));
  1301. // Clean up after loadBoard().
  1302. if (isset($board_info['moderators']))
  1303. {
  1304. foreach ($board_info['moderators'] as $k => $dummy)
  1305. {
  1306. $board_info['moderators'][$k]['href'] = strtr($dummy['href'], array($oldurl => $boardurl));
  1307. $board_info['moderators'][$k]['link'] = strtr($dummy['link'], array('"' . $oldurl => '"' . $boardurl));
  1308. }
  1309. }
  1310. foreach ($context['linktree'] as $k => $dummy)
  1311. $context['linktree'][$k]['url'] = strtr($dummy['url'], array($oldurl => $boardurl));
  1312. }
  1313. }
  1314. // Set up the contextual user array.
  1315. $context['user'] = array(
  1316. 'id' => $user_info['id'],
  1317. 'is_logged' => !$user_info['is_guest'],
  1318. 'is_guest' => &$user_info['is_guest'],
  1319. 'is_admin' => &$user_info['is_admin'],
  1320. 'is_mod' => &$user_info['is_mod'],
  1321. // A user can mod if they have permission to see the mod center, or they are a board/group/approval moderator.
  1322. 'can_mod' => allowedTo('access_mod_center') || (!$user_info['is_guest'] && ($user_info['mod_cache']['gq'] != '0=1' || $user_info['mod_cache']['bq'] != '0=1' || ($modSettings['postmod_active'] && !empty($user_info['mod_cache']['ap'])))),
  1323. 'username' => $user_info['username'],
  1324. 'language' => $user_info['language'],
  1325. 'email' => $user_info['email'],
  1326. 'ignoreusers' => $user_info['ignoreusers'],
  1327. );
  1328. if (!$context['user']['is_guest'])
  1329. $context['user']['name'] = $user_info['name'];
  1330. elseif ($context['user']['is_guest'] && !empty($txt['guest_title']))
  1331. $context['user']['name'] = $txt['guest_title'];
  1332. // Determine the current smiley set.
  1333. $user_info['smiley_set'] = (!in_array($user_info['smiley_set'], explode(',', $modSettings['smiley_sets_known'])) && $user_info['smiley_set'] != 'none') || empty($modSettings['smiley_sets_enable']) ? (!empty($settings['smiley_sets_default']) ? $settings['smiley_sets_default'] : $modSettings['smiley_sets_default']) : $user_info['smiley_set'];
  1334. $context['user']['smiley_set'] = $user_info['smiley_set'];
  1335. // Some basic information...
  1336. if (!isset($context['html_headers']))
  1337. $context['html_headers'] = '';
  1338. $context['menu_separator'] = !empty($settings['use_image_buttons']) ? ' ' : ' | ';
  1339. $context['session_var'] = $_SESSION['session_var'];
  1340. $context['session_id'] = $_SESSION['session_value'];
  1341. $context['forum_name'] = $mbname;
  1342. $context['forum_name_html_safe'] = $smcFunc['htmlspecialchars']($context['forum_name']);
  1343. $context['header_logo_url_html_safe'] = empty($settings['header_logo_url']) ? '' : $smcFunc['htmlspecialchars']($settings['header_logo_url']);
  1344. $context['current_action'] = isset($_REQUEST['action']) ? $_REQUEST['action'] : null;
  1345. $context['current_subaction'] = isset($_REQUEST['sa']) ? $_REQUEST['sa'] : null;
  1346. if (isset($modSettings['load_average']))
  1347. $context['load_average'] = $modSettings['load_average'];
  1348. // Set some permission related settings.
  1349. $context['show_login_bar'] = $user_info['is_guest'] && !empty($modSettings['enableVBStyleLogin']);
  1350. // This determines the server... not used in many places, except for login fixing.
  1351. $context['server'] = array(
  1352. 'is_iis' => isset($_SERVER['SERVER_SOFTWARE']) && strpos($_SERVER['SERVER_SOFTWARE'], 'Microsoft-IIS') !== false,
  1353. 'is_apache' => isset($_SERVER['SERVER_SOFTWARE']) && strpos($_SERVER['SERVER_SOFTWARE'], 'Apache') !== false,
  1354. 'is_lighttpd' => isset($_SERVER['SERVER_SOFTWARE']) && strpos($_SERVER['SERVER_SOFTWARE'], 'lighttpd') !== false,
  1355. 'is_nginx' => isset($_SERVER['SERVER_SOFTWARE']) && strpos($_SERVER['SERVER_SOFTWARE'], 'nginx') !== false,
  1356. 'is_cgi' => isset($_SERVER['SERVER_SOFTWARE']) && strpos(php_sapi_name(), 'cgi') !== false,
  1357. 'is_windows' => strpos(PHP_OS, 'WIN') === 0,
  1358. 'iso_case_folding' => ord(strtolower(chr(138))) === 154,
  1359. 'complex_preg_chars' => @version_compare(PHP_VERSION, '4.3.3') != -1,
  1360. );
  1361. // A bug in some versions of IIS under CGI (older ones) makes cookie setting not work with Location: headers.
  1362. $context['server']['needs_login_fix'] = $context['server']['is_cgi'] && $context['server']['is_iis'];
  1363. // Detect the browser. This is separated out because it's also used in attachment downloads
  1364. detectBrowser();
  1365. // Set the top level linktree up.
  1366. array_unshift($context['linktree'], array(
  1367. 'url' => $scripturl,
  1368. 'name' => $context['forum_name_html_safe']
  1369. ));
  1370. // This allows sticking some HTML on the page output - useful for controls.
  1371. $context['insert_after_template'] = '';
  1372. if (!isset($txt))
  1373. $txt = array();
  1374. $simpleActions = array(
  1375. 'findmember',
  1376. 'helpadmin',
  1377. 'printpage',
  1378. 'quotefast',
  1379. 'spellcheck',
  1380. );
  1381. // Wireless mode? Load up the wireless stuff.
  1382. if (WIRELESS)
  1383. {
  1384. $context['template_layers'] = array(WIRELESS_PROTOCOL);
  1385. loadTemplate('Wireless');
  1386. loadLanguage('Wireless+index+Modifications');
  1387. }
  1388. // Output is fully XML, so no need for the index template.
  1389. elseif (isset($_REQUEST['xml']))
  1390. {
  1391. loadLanguage('index+Modifications');
  1392. loadTemplate('Xml');
  1393. $context['template_layers'] = array();
  1394. }
  1395. // These actions don't require the index template at all.
  1396. elseif (!empty($_REQUEST['action']) && in_array($_REQUEST['action'], $simpleActions))
  1397. {
  1398. loadLanguage('index+Modifications');
  1399. $context['template_layers'] = array();
  1400. }
  1401. else
  1402. {
  1403. // Custom templates to load, or just default?
  1404. if (isset($settings['theme_templates']))
  1405. $templates = explode(',', $settings['theme_templates']);
  1406. else
  1407. $templates = array('index');
  1408. // Load each template...
  1409. foreach ($templates as $template)
  1410. loadTemplate($template);
  1411. // ...and attempt to load their associated language files.
  1412. $required_files = implode('+', array_merge($templates, array('Modifications')));
  1413. loadLanguage($required_files, '', false);
  1414. // Custom template layers?
  1415. if (isset($settings['theme_layers']))
  1416. $context['template_layers'] = explode(',', $settings['theme_layers']);
  1417. else
  1418. $context['template_layers'] = array('html', 'body');
  1419. }
  1420. // Initialize the theme.
  1421. loadSubTemplate('init', 'ignore');
  1422. // Load the compatibility stylesheet if the theme hasn't been updated for 2.0 RC2 (yet).
  1423. if (isset($settings['theme_version']) && (version_compare($settings['theme_version'], '2.0 RC2', '<') || strpos($settings['theme_version'], '2.0 Beta') !== false))
  1424. loadTemplate(false, 'compat');
  1425. // Guests may still need a name.
  1426. if ($context['user']['is_guest'] && empty($context['user']['name']))
  1427. $context['user']['name'] = $txt['guest_title'];
  1428. // Any theme-related strings that need to be loaded?
  1429. if (!empty($settings['require_theme_strings']))
  1430. loadLanguage('ThemeStrings', '', false);
  1431. // We allow theme variants, because we're cool.
  1432. $context['theme_variant'] = '';
  1433. $context['theme_variant_url'] = '';
  1434. if (!empty($settings['theme_variants']))
  1435. {
  1436. // Overriding - for previews and that ilk.
  1437. if (!empty($_REQUEST['variant']))
  1438. $_SESSION['id_variant'] = $_REQUEST['variant'];
  1439. // User selection?
  1440. if (empty($settings['disable_user_variant']) || allowedTo('admin_forum'))
  1441. $context['theme_variant'] = !empty($_SESSION['id_variant']) ? $_SESSION['id_variant'] : (!empty($options['theme_variant']) ? $options['theme_variant'] : '');
  1442. // If not a user variant, select the default.
  1443. if ($context['theme_variant'] == '' || !in_array($context['theme_variant'], $settings['theme_variants']))
  1444. $context['theme_variant'] = !empty($settings['default_variant']) && in_array($settings['default_variant'], $settings['theme_variants']) ? $settings['default_variant'] : $settings['theme_variants'][0];
  1445. // Do this to keep things easier in the templates.
  1446. $context['theme_variant'] = '_' . $context['theme_variant'];
  1447. $context['theme_variant_url'] = $context['theme_variant'] . '/';
  1448. }
  1449. // Let's be compatible with old themes!
  1450. if (!function_exists('template_html_above') && in_array('html', $context['template_layers']))
  1451. $context['template_layers'] = array('main');
  1452. // Allow overriding the board wide time/number formats.
  1453. if (empty($user_settings['time_format']) && !empty($txt['time_format']))
  1454. $user_info['time_format'] = $txt['time_format'];
  1455. $txt['number_format'] = empty($txt['number_format']) ? empty($modSettings['number_format']) ? '' : $modSettings['number_format'] : $txt['number_format'];
  1456. if (isset($settings['use_default_images']) && $settings['use_default_images'] == 'always')
  1457. {
  1458. $settings['theme_url'] = $settings['default_theme_url'];
  1459. $settings['images_url'] = $settings['default_images_url'];
  1460. $settings['theme_dir'] = $settings['default_theme_dir'];
  1461. }
  1462. // Make a special URL for the language.
  1463. $settings['lang_images_url'] = $settings['images_url'] . '/' . (!empty($txt['image_lang']) ? $txt['image_lang'] : $user_info['language']);
  1464. // Set the character set from the template.
  1465. $context['character_set'] = empty($modSettings['global_character_set']) ? $txt['lang_character_set'] : $modSettings['global_character_set'];
  1466. $context['utf8'] = $context['character_set'] === 'UTF-8' && (strpos(strtolower(PHP_OS), 'win') === false || @version_compare(PHP_VERSION, '4.2.3') != -1);
  1467. $context['right_to_left'] = !empty($txt['lang_rtl']);
  1468. $context['tabindex'] = 1;
  1469. // Fix font size with HTML 4.01, etc.
  1470. if (isset($settings['doctype']))
  1471. $context['browser']['needs_size_fix'] |= $settings['doctype'] == 'html' && $context['browser']['is_ie6'];
  1472. // Compatibility.
  1473. if (!isset($settings['theme_version']))
  1474. $modSettings['memberCount'] = $modSettings['totalMembers'];
  1475. // This allows us to change the way things look for the admin.
  1476. $context['admin_features'] = isset($modSettings['admin_features']) ? explode(',', $modSettings['admin_features']) : array('cd,cp,k,w,rg,ml,pm');
  1477. // If we think we have mail to send, let's offer up some possibilities... robots get pain (Now with scheduled task support!)
  1478. if ((!empty($modSettings['mail_next_send']) && $modSettings['mail_next_send'] < time() && empty($modSettings['mail_queue_use_cron'])) || empty($modSettings['next_task_time']) || $modSettings['next_task_time'] < time())
  1479. {
  1480. if ($context['browser']['possibly_robot'])
  1481. {
  1482. //!!! Maybe move this somewhere better?!
  1483. require_once($sourcedir . '/ScheduledTasks.php');
  1484. // What to do, what to do?!
  1485. if (empty($modSettings['next_task_time']) || $modSettings['next_task_time'] < time())
  1486. AutoTask();
  1487. else
  1488. ReduceMailQueue();
  1489. }
  1490. else
  1491. {
  1492. $type = empty($modSettings['next_task_time']) || $modSettings['next_task_time'] < time() ? 'task' : 'mailq';
  1493. $ts = $type == 'mailq' ? $modSettings['mail_next_send'] : $modSettings['next_task_time'];
  1494. $context['html_headers'] .= '
  1495. <script type="text/javascript">
  1496. function smfAutoTask()
  1497. {
  1498. var tempImage = new Image();
  1499. tempImage.src = "' . $scripturl . '?scheduled=' . $type . ';ts=' . $ts . '";
  1500. }
  1501. window.setTimeout("smfAutoTask();", 1);
  1502. </script>';
  1503. }
  1504. }
  1505. // Any files to include at this point?
  1506. if (!empty($modSettings['integrate_theme_include']))
  1507. {
  1508. $theme_includes = explode(',', $modSettings['integrate_theme_include']);
  1509. foreach ($theme_includes as $include)
  1510. {
  1511. $include = strtr(trim($include), array('$boarddir' => $boarddir, '$sourcedir' => $sourcedir, '$themedir' => $settings['theme_dir']));
  1512. if (file_exists($include))
  1513. require_once($include);
  1514. }
  1515. }
  1516. // Call load theme integration functions.
  1517. call_integration_hook('integrate_load_theme');
  1518. // We are ready to go.
  1519. $context['theme_loaded'] = true;
  1520. }
  1521. /**
  1522. * Load a template - if the theme doesn't include it, use the default.
  1523. * What this function does:
  1524. * - loads a template file with the name template_name from the current, default,
  1525. * or base theme.
  1526. * - uses the template_include() function to include the file.
  1527. * - detects a wrong default theme directory and tries to work around it.
  1528. * - if fatal is true, dies with an error message if the template cannot be found.
  1529. * @param string $template_name
  1530. * @param array $style_sheets = array()
  1531. * @param bool $fatal = true
  1532. */
  1533. function loadTemplate($template_name, $style_sheets = array(), $fatal = true)
  1534. {
  1535. global $context, $settings, $txt, $scripturl, $boarddir, $db_show_debug;
  1536. // Do any style sheets first, cause we're easy with those.
  1537. if (!empty($style_sheets))
  1538. {
  1539. if (!is_array($style_sheets))
  1540. $style_sheets = array($style_sheets);
  1541. foreach ($style_sheets as $sheet)
  1542. {
  1543. // Prevent the style sheet from being included twice.
  1544. if (strpos($context['html_headers'], 'id="' . $sheet . '_css"') !== false)
  1545. continue;
  1546. $sheet_path = file_exists($settings['theme_dir']. '/css/' . $sheet . '.css') ? 'theme_url' : (file_exists($settings['default_theme_dir']. '/css/' . $sheet . '.css') ? 'default_theme_url' : '');
  1547. if ($sheet_path)
  1548. {
  1549. $context['html_headers'] .= "\n\t" . '<link rel="stylesheet" type="text/css" id="' . $sheet . '_css" href="' . $settings[$sheet_path] . '/css/' . $sheet . '.css" />';
  1550. if ($db_show_debug === true)
  1551. $context['debug']['sheets'][] = $sheet . ' (' . basename($settings[$sheet_path]) . ')';
  1552. }
  1553. }
  1554. }
  1555. // No template to load?
  1556. if ($template_name === false)
  1557. return true;
  1558. $loaded = false;
  1559. foreach ($settings['template_dirs'] as $template_dir)
  1560. {
  1561. if (file_exists($template_dir . '/' . $template_name . '.template.php'))
  1562. {
  1563. $loaded = true;
  1564. template_include($template_dir . '/' . $template_name . '.template.php', true);
  1565. break;
  1566. }
  1567. }
  1568. if ($loaded)
  1569. {
  1570. // For compatibility reasons, if this is the index template without new functions, include compatible stuff.
  1571. if (substr($template_name, 0, 5) == 'index' && !function_exists('template_button_strip'))
  1572. loadTemplate('Compat');
  1573. if ($db_show_debug === true)
  1574. $context['debug']['templates'][] = $template_name . ' (' . basename($template_dir) . ')';
  1575. // If they have specified an initialization function for this template, go ahead and call it now.
  1576. if (function_exists('template_' . $template_name . '_init'))
  1577. call_user_func('template_' . $template_name . '_init');
  1578. }
  1579. // Hmmm... doesn't exist?! I don't suppose the directory is wrong, is it?
  1580. elseif (!file_exists($settings['default_theme_dir']) && file_exists($boarddir . '/Themes/default'))
  1581. {
  1582. $settings['default_theme_dir'] = $boarddir . '/Themes/default';
  1583. $settings['template_dirs'][] = $settings['default_theme_dir'];
  1584. if (!empty($context['user']['is_admin']) && !isset($_GET['th']))
  1585. {
  1586. loadLanguage('Errors');
  1587. echo '
  1588. <div class="alert errorbox">
  1589. <a href="', $scripturl . '?action=admin;area=theme;sa=settings;th=1;' . $context['session_var'] . '=' . $context['session_id'], '" class="alert">', $txt['theme_dir_wrong'], '</a>
  1590. </div>';
  1591. }
  1592. loadTemplate($template_name);
  1593. }
  1594. // Cause an error otherwise.
  1595. elseif ($template_name != 'Errors' && $template_name != 'index' && $fatal)
  1596. fatal_lang_error('theme_template_error', 'template', array((string) $template_name));
  1597. elseif ($fatal)
  1598. die(log_error(sprintf(isset($txt['theme_template_error']) ? $txt['theme_template_error'] : 'Unable to load Themes/default/%s.template.php!', (string) $template_name), 'template'));
  1599. else
  1600. return false;
  1601. }
  1602. /**
  1603. * Load a sub-template.
  1604. * What it does:
  1605. * - loads the sub template specified by sub_template_name, which must be in an already-loaded
  1606. * template.
  1607. * - if ?debug is in the query string, shows administrators a marker after every sub template
  1608. * for debugging purposes.
  1609. * @todo get rid of reading $_REQUEST directly
  1610. * @param string $sub_template_name
  1611. * @param bool $fatal = false, $fatal = true is for templates that shouldn't get a 'pretty' error screen.
  1612. */
  1613. function loadSubTemplate($sub_template_name, $fatal = false)
  1614. {
  1615. global $context, $settings, $options, $txt, $db_show_debug;
  1616. if ($db_show_debug === true)
  1617. $context['debug']['sub_templates'][] = $sub_template_name;
  1618. // Figure out what the template function is named.
  1619. $theme_function = 'template_' . $sub_template_name;
  1620. if (function_exists($theme_function))
  1621. $theme_function();
  1622. elseif ($fatal === false)
  1623. fatal_lang_error('theme_template_error', 'template', array((string) $sub_template_name));
  1624. elseif ($fatal !== 'ignore')
  1625. die(log_error(sprintf(isset($txt['theme_template_error']) ? $txt['theme_template_error'] : 'Unable to load the %s sub template!', (string) $sub_template_name), 'template'));
  1626. // Are we showing debugging for templates? Just make sure not to do it before the doctype...
  1627. if (allowedTo('admin_forum') && isset($_REQUEST['debug']) && !in_array($sub_template_name, array('init', 'main_below')) && ob_get_length() > 0 && !isset($_REQUEST['xml']))
  1628. {
  1629. echo '
  1630. <div style="font-size: 8pt; border: 1px dashed red; background: orange; text-align: center; font-weight: bold;">---- ', $sub_template_name, ' ends ----</div>';
  1631. }
  1632. }
  1633. /**
  1634. * Load a language file. Tries the current and default themes as well as the user and global languages.
  1635. *
  1636. * @param string $template_name
  1637. * @param string $lang
  1638. * @param bool $fatal = true
  1639. * @param bool $force_reload = false
  1640. */
  1641. function loadLanguage($template_name, $lang = '', $fatal = true, $force_reload = false)
  1642. {
  1643. global $user_info, $language, $settings, $context, $modSettings;
  1644. global $cachedir, $db_show_debug, $sourcedir, $txt;
  1645. static $already_loaded = array();
  1646. // Default to the user's language.
  1647. if ($lang == '')
  1648. $lang = isset($user_info['language']) ? $user_info['language'] : $language;
  1649. // Do we want the English version of language file as fallback?
  1650. if (empty($modSettings['disable_language_fallback']) && $lang != 'english')
  1651. loadLanguage($template_name, 'english', false);
  1652. if (!$force_reload && isset($already_loaded[$template_name]) && $already_loaded[$template_name] == $lang)
  1653. return $lang;
  1654. // Make sure we have $settings - if not we're in trouble and need to find it!
  1655. if (empty($settings['default_theme_dir']))
  1656. {
  1657. require_once($sourcedir . '/ScheduledTasks.php');
  1658. loadEssentialThemeData();
  1659. }
  1660. // What theme are we in?
  1661. $theme_name = basename($settings['theme_url']);
  1662. if (empty($theme_name))
  1663. $theme_name = 'unknown';
  1664. // For each file open it up and write it out!
  1665. foreach (explode('+', $template_name) as $template)
  1666. {
  1667. // Obviously, the current theme is most important to check.
  1668. $attempts = array(
  1669. array($settings['theme_dir'], $template, $lang, $settings['theme_url']),
  1670. array($settings['theme_dir'], $template, $language, $settings['theme_url']),
  1671. );
  1672. // Do we have a base theme to worry about?
  1673. if (isset($settings['base_theme_dir']))
  1674. {
  1675. $attempts[] = array($settings['base_theme_dir'], $template, $lang, $settings['base_theme_url']);
  1676. $attempts[] = array($settings['base_theme_dir'], $template, $language, $settings['base_theme_url']);
  1677. }
  1678. // Fall back on the default theme if necessary.
  1679. $attempts[] = array($settings['default_theme_dir'], $template, $lang, $settings['default_theme_url']);
  1680. $attempts[] = array($settings['default_theme_dir'], $template, $language, $settings['default_theme_url']);
  1681. // Fall back on the English language if none of the preferred languages can be found.
  1682. if (!in_array('english', array($lang, $language)))
  1683. {
  1684. $attempts[] = array($settings['theme_dir'], $template, 'english', $settings['theme_url']);
  1685. $attempts[] = array($settings['default_theme_dir'], $template, 'english', $settings['default_theme_url']);
  1686. }
  1687. // Try to find the language file.
  1688. $found = false;
  1689. foreach ($attempts as $k => $file)
  1690. {
  1691. if (file_exists($file[0] . '/languages/' . $file[1] . '.' . $file[2] . '.php'))
  1692. {
  1693. // Include it!
  1694. template_include($file[0] . '/languages/' . $file[1] . '.' . $file[2] . '.php');
  1695. // Note that we found it.
  1696. $found = true;
  1697. break;
  1698. }
  1699. }
  1700. // That couldn't be found! Log the error, but *try* to continue normally.
  1701. if (!$found && $fatal)
  1702. {
  1703. log_error(sprintf($txt['theme_language_error'], $template_name . '.' . $lang, 'template'));
  1704. break;
  1705. }
  1706. }
  1707. // Keep track of what we're up to soldier.
  1708. if ($db_show_debug === true)
  1709. $context['debug']['language_files'][] = $template_name . '.' . $lang . ' (' . $theme_name . ')';
  1710. // Remember what we have loaded, and in which language.
  1711. $already_loaded[$template_name] = $lang;
  1712. // Return the language actually loaded.
  1713. return $lang;
  1714. }
  1715. /**
  1716. * Get all parent boards (requires first parent as parameter)
  1717. * It finds all the parents of id_parent, and that board itself.
  1718. * Additionally, it detects the moderators of said boards.
  1719. *
  1720. * @param int $id_parent
  1721. * @return an array of information about the boards found.
  1722. */
  1723. function getBoardParents($id_parent)
  1724. {
  1725. global $scripturl, $smcFunc;
  1726. // First check if we have this cached already.
  1727. if (($boards = cache_get_data('board_parents-' . $id_parent, 480)) === null)
  1728. {
  1729. $boards = array();
  1730. $original_parent = $id_parent;
  1731. // Loop while the parent is non-zero.
  1732. while ($id_parent != 0)
  1733. {
  1734. $result = $smcFunc['db_query']('', '
  1735. SELECT
  1736. b.id_parent, b.name, {int:board_parent} AS id_board, IFNULL(mem.id_member, 0) AS id_moderator,
  1737. mem.real_name, b.child_level
  1738. FROM {db_prefix}boards AS b
  1739. LEFT JOIN {db_prefix}moderators AS mods ON (mods.id_board = b.id_board)
  1740. LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = mods.id_member)
  1741. WHERE b.id_board = {int:board_parent}',
  1742. array(
  1743. 'board_parent' => $id_parent,
  1744. )
  1745. );
  1746. // In the EXTREMELY unlikely event this happens, give an error message.
  1747. if ($smcFunc['db_num_rows']($result) == 0)
  1748. fatal_lang_error('parent_not_found', 'critical');
  1749. while ($row = $smcFunc['db_fetch_assoc']($result))
  1750. {
  1751. if (!isset($boards[$row['id_board']]))
  1752. {
  1753. $id_parent = $row['id_parent'];
  1754. $boards[$row['id_board']] = array(
  1755. 'url' => $scripturl . '?board=' . $row['id_board'] . '.0',
  1756. 'name' => $row['name'],
  1757. 'level' => $row['child_level'],
  1758. 'moderators' => array()
  1759. );
  1760. }
  1761. // If a moderator exists for this board, add that moderator for all children too.
  1762. if (!empty($row['id_moderator']))
  1763. foreach ($boards as $id => $dummy)
  1764. {
  1765. $boards[$id]['moderators'][$row['id_moderator']] = array(
  1766. 'id' => $row['id_moderator'],
  1767. 'name' => $row['real_name'],
  1768. 'href' => $scripturl . '?action=profile;u=' . $row['id_moderator'],
  1769. 'link' => '<a href="' . $scripturl . '?action=profile;u=' . $row['id_moderator'] . '">' . $row['real_name'] . '</a>'
  1770. );
  1771. }
  1772. }
  1773. $smcFunc['db_free_result']($result);
  1774. }
  1775. cache_put_data('board_parents-' . $original_parent, $boards, 480);
  1776. }
  1777. return $boards;
  1778. }
  1779. /**
  1780. * Attempt to reload our known languages.
  1781. * It will try to choose only utf8 or non-utf8 languages.
  1782. *
  1783. * @param bool $use_cache = true
  1784. * @param bool $favor_utf8 = true
  1785. */
  1786. function getLanguages($use_cache = true, $favor_utf8 = true)
  1787. {
  1788. global $context, $smcFunc, $settings, $modSettings;
  1789. // Either we don't use the cache, or its expired.
  1790. if (!$use_cache || ($context['languages'] = cache_get_data('known_languages' . ($favor_utf8 ? '' : '_all'), !empty($modSettings['cache_enable']) && $modSettings['cache_enable'] < 1 ? 86400 : 3600)) == null)
  1791. {
  1792. // If we don't have our theme information yet, lets get it.
  1793. if (empty($settings['default_theme_dir']))
  1794. loadTheme(0, false);
  1795. // Default language directories to try.
  1796. $language_directories = array(
  1797. $settings['default_theme_dir'] . '/languages',
  1798. $settings['actual_theme_dir'] . '/languages',
  1799. );
  1800. // We possibly have a base theme directory.
  1801. if (!empty($settings['base_theme_dir']))
  1802. $language_directories[] = $settings['base_theme_dir'] . '/languages';
  1803. // Remove any duplicates.
  1804. $language_directories = array_unique($language_directories);
  1805. foreach ($language_directories as $language_dir)
  1806. {
  1807. // Can't look in here... doesn't exist!
  1808. if (!file_exists($language_dir))
  1809. continue;
  1810. $dir = dir($language_dir);
  1811. while ($entry = $dir->read())
  1812. {
  1813. // Look for the index language file....
  1814. if (!preg_match('~^index\.(.+)\.php$~', $entry, $matches))
  1815. continue;
  1816. $context['languages'][$matches[1]] = array(
  1817. 'name' => $smcFunc['ucwords'](strtr($matches[1], array('_' => ' '))),
  1818. 'selected' => false,
  1819. 'filename' => $matches[1],
  1820. 'location' => $language_dir . '/index.' . $matches[1] . '.php',
  1821. );
  1822. }
  1823. $dir->close();
  1824. }
  1825. // Favoring UTF8? Then prevent us from selecting non-UTF8 versions.
  1826. if ($favor_utf8)
  1827. {
  1828. foreach ($context['languages'] as $lang)
  1829. if (substr($lang['filename'], strlen($lang['filename']) - 5, 5) != '-utf8' && isset($context['languages'][$lang['filename'] . '-utf8']))
  1830. unset($context['languages'][$lang['filename']]);
  1831. }
  1832. // Lets cash in on this deal.
  1833. if (!empty($modSettings['cache_enable']))
  1834. cache_put_data('known_languages' . ($favor_utf8 ? '' : '_all'), $context['languages'], !empty($modSettings['cache_enable']) && $modSettings['cache_enable'] < 1 ? 86400 : 3600);
  1835. }
  1836. return $context['languages'];
  1837. }
  1838. /**
  1839. * Replace all vulgar words with respective proper words. (substring or whole words..)
  1840. * What this function does:
  1841. * - it censors the passed string.
  1842. * - if the theme setting allow_no_censored is on, and the theme option
  1843. * show_no_censored is enabled, does not censor - unless force is set.
  1844. * - it caches the list of censored words to reduce parsing.
  1845. * @todo what is this function doing here?
  1846. * @param $text
  1847. * @param $force
  1848. */
  1849. function &censorText(&$text, $force = false)
  1850. {
  1851. global $modSettings, $options, $settings, $txt;
  1852. static $censor_vulgar = null, $censor_proper;
  1853. if ((!empty($options['show_no_censored']) && $settings['allow_no_censored'] && !$force) || empty($modSettings['censor_vulgar']))
  1854. return $text;
  1855. // If they haven't yet been loaded, load them.
  1856. if ($censor_vulgar == null)
  1857. {
  1858. $censor_vulgar = explode("\n", $modSettings['censor_vulgar']);
  1859. $censor_proper = explode("\n", $modSettings['censor_proper']);
  1860. // Quote them for use in regular expressions.
  1861. for ($i = 0, $n = count($censor_vulgar); $i < $n; $i++)
  1862. {
  1863. $censor_vulgar[$i] = strtr(preg_quote($censor_vulgar[$i], '/'), array('\\\\\\*' => '[*]', '\\*' => '[^\s]*?', '&' => '&amp;'));
  1864. $censor_vulgar[$i] = (empty($modSettings['censorWholeWord']) ? '/' . $censor_vulgar[$i] . '/' : '/(?<=^|\W)' . $censor_vulgar[$i] . '(?=$|\W)/') . (empty($modSettings['censorIgnoreCase']) ? '' : 'i') . ((empty($modSettings['global_character_set']) ? $txt['lang_character_set'] : $modSettings['global_character_set']) === 'UTF-8' ? 'u' : '');
  1865. if (strpos($censor_vulgar[$i], '\'') !== false)
  1866. {
  1867. $censor_proper[count($censor_vulgar)] = $censor_proper[$i];
  1868. $censor_vulgar[count($censor_vulgar)] = strtr($censor_vulgar[$i], array('\'' => '&#039;'));
  1869. }
  1870. }
  1871. }
  1872. // Censoring isn't so very complicated :P.
  1873. $text = preg_replace($censor_vulgar, $censor_proper, $text);
  1874. return $text;
  1875. }
  1876. /**
  1877. * Load the template/language file using eval or require? (with eval we can show an error message!)
  1878. * - loads the template or language file specified by filename.
  1879. * - uses eval unless disableTemplateEval is enabled.
  1880. * - outputs a parse error if the file did not exist or contained errors.
  1881. * - attempts to detect the error and line, and show detailed information.
  1882. *
  1883. * @param string $filename
  1884. * @param bool $once = false, if true only includes the file once (like include_once)
  1885. */
  1886. function template_include($filename, $once = false)
  1887. {
  1888. global $context, $settings, $options, $txt, $scripturl, $modSettings;
  1889. global $user_info, $boardurl, $boarddir, $sourcedir;
  1890. global $maintenance, $mtitle, $mmessage;
  1891. static $templates = array();
  1892. // We want to be able to figure out any errors...
  1893. @ini_set('track_errors', '1');
  1894. // Don't include the file more than once, if $once is true.
  1895. if ($once && in_array($filename, $templates))
  1896. return;
  1897. // Add this file to the include list, whether $once is true or not.
  1898. else
  1899. $templates[] = $filename;
  1900. // Are we going to use eval?
  1901. if (empty($modSettings['disableTemplateEval']))
  1902. {
  1903. $file_found = file_exists($filename) && eval('?' . '>' . rtrim(file_get_contents($filename))) !== false;
  1904. $settings['current_include_filename'] = $filename;
  1905. }
  1906. else
  1907. {
  1908. $file_found = file_exists($filename);
  1909. if ($once && $file_found)
  1910. require_once($filename);
  1911. elseif ($file_found)
  1912. require($filename);
  1913. }
  1914. if ($file_found !== true)
  1915. {
  1916. ob_end_clean();
  1917. if (!empty($modSettings['enableCompressedOutput']))
  1918. @ob_start('ob_gzhandler');
  1919. else
  1920. ob_start();
  1921. if (isset($_GET['debug']) && !WIRELESS)
  1922. header('Content-Type: application/xhtml+xml; charset=' . (empty($context['character_set']) ? 'ISO-8859-1' : $context['character_set']));
  1923. // Don't cache error pages!!
  1924. header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
  1925. header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
  1926. header('Cache-Control: no-cache');
  1927. if (!isset($txt['template_parse_error']))
  1928. {
  1929. $txt['template_parse_error'] = 'Template Parse Error!';
  1930. $txt['template_parse_error_message'] = 'It seems something has gone sour on the forum with the template system. This problem should only be temporary, so please come back later and try again. If you continue to see this message, please contact the administrator.<br /><br />You can also try <a href="javascript:location.reload();">refreshing this page</a>.';
  1931. $txt['template_parse_error_details'] = 'There was a problem loading the <tt><strong>%1$s</strong></tt> template or language file. Please check the syntax and try again - remember, single quotes (<tt>\'</tt>) often have to be escaped with a slash (<tt>\\</tt>). To see more specific error information from PHP, try <a href="' . $boardurl . '%1$s" class="extern">accessing the file directly</a>.<br /><br />You may want to try to <a href="javascript:location.reload();">refresh this page</a> or <a href="' . $scripturl . '?theme=1">use the default theme</a>.';
  1932. }
  1933. // First, let's get the doctype and language information out of the way.
  1934. echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  1935. <html xmlns="http://www.w3.org/1999/xhtml"', !empty($context['right_to_left']) ? ' dir="rtl"' : '', '>
  1936. <head>';
  1937. if (isset($context['character_set']))
  1938. echo '
  1939. <meta http-equiv="Content-Type" content="text/html; charset=', $context['character_set'], '" />';
  1940. if (!empty($maintenance) && !allowedTo('admin_forum'))
  1941. echo '
  1942. <title>', $mtitle, '</title>
  1943. </head>
  1944. <body>
  1945. <h3>', $mtitle, '</h3>
  1946. ', $mmessage, '
  1947. </body>
  1948. </html>';
  1949. elseif (!allowedTo('admin_forum'))
  1950. echo '
  1951. <title>', $txt['template_parse_error'], '</title>
  1952. </head>
  1953. <body>
  1954. <h3>', $txt['template_parse_error'], '</h3>
  1955. ', $txt['template_parse_error_message'], '
  1956. </body>
  1957. </html>';
  1958. else
  1959. {
  1960. require_once($sourcedir . '/Subs-Package.php');
  1961. $error = fetch_web_data($boardurl . strtr($filename, array($boarddir => '', strtr($boarddir, '\\', '/') => '')));
  1962. if (empty($error))
  1963. $error = $php_errormsg;
  1964. $error = strtr($error, array('<b>' => '<strong>', '</b>' => '</strong>'));
  1965. echo '
  1966. <title>', $txt['template_parse_error'], '</title>
  1967. </head>
  1968. <body>
  1969. <h3>', $txt['template_parse_error'], '</h3>
  1970. ', sprintf($txt['template_parse_error_details'], strtr($filename, array($boarddir => '', strtr($boarddir, '\\', '/') => '')));
  1971. if (!empty($error))
  1972. echo '
  1973. <hr />
  1974. <div style="margin: 0 20px;"><tt>', strtr(strtr($error, array('<strong>' . $boarddir => '<strong>...', '<strong>' . strtr($boarddir, '\\', '/') => '<strong>...')), '\\', '/'), '</tt></div>';
  1975. // I know, I know... this is VERY COMPLICATED. Still, it's good.
  1976. if (preg_match('~ <strong>(\d+)</strong><br( /)?' . '>$~i', $error, $match) != 0)
  1977. {
  1978. $data = file($filename);
  1979. $data2 = highlight_php_code(implode('', $data));
  1980. $data2 = preg_split('~\<br( /)?\>~', $data2);
  1981. // Fix the PHP code stuff...
  1982. if ($context['browser']['is_ie4'] || $context['browser']['is_ie5'] || $context['browser']['is_ie5.5'])
  1983. $data2 = str_replace("\t", '<pre style="display: inline;">' . "\t" . '</pre>', $data2);
  1984. elseif (!$context['browser']['is_gecko'])
  1985. $data2 = str_replace("\t", '<span style="white-space: pre;">' . "\t" . '</span>', $data2);
  1986. else
  1987. $data2 = str_replace('<pre style="display: inline;">' . "\t" . '</pre>', "\t", $data2);
  1988. // Now we get to work around a bug in PHP where it doesn't escape <br />s!
  1989. $j = -1;
  1990. foreach ($data as $line)
  1991. {
  1992. $j++;
  1993. if (substr_count($line, '<br />') == 0)
  1994. continue;
  1995. $n = substr_count($line, '<br />');
  1996. for ($i = 0; $i < $n; $i++)
  1997. {
  1998. $data2[$j] .= '&lt;br /&gt;' . $data2[$j + $i + 1];
  1999. unset($data2[$j + $i + 1]);
  2000. }
  2001. $j += $n;
  2002. }
  2003. $data2 = array_values($data2);
  2004. array_unshift($data2, '');
  2005. echo '
  2006. <div style="margin: 2ex 20px; width: 96%; overflow: auto;"><pre style="margin: 0;">';
  2007. // Figure out what the color coding was before...
  2008. $line = max($match[1] - 9, 1);
  2009. $last_line = '';
  2010. for ($line2 = $line - 1; $line2 > 1; $line2--)
  2011. if (strpos($data2[$line2], '<') !== false)
  2012. {
  2013. if (preg_match('~(<[^/>]+>)[^<]*$~', $data2[$line2], $color_match) != 0)
  2014. $last_line = $color_match[1];
  2015. break;
  2016. }
  2017. // Show the relevant lines...
  2018. for ($n = min($match[1] + 4, count($data2) + 1); $line <= $n; $line++)
  2019. {
  2020. if ($line == $match[1])
  2021. echo '</pre><div style="background-color: #ffb0b5;"><pre style="margin: 0;">';
  2022. echo '<span style="color: black;">', sprintf('%' . strlen($n) . 's', $line), ':</span> ';
  2023. if (isset($data2[$line]) && $data2[$line] != '')
  2024. echo substr($data2[$line], 0, 2) == '</' ? preg_replace('~^</[^>]+>~', '', $data2[$line]) : $last_line . $data2[$line];
  2025. if (isset($data2[$line]) && preg_match('~(<[^/>]+>)[^<]*$~', $data2[$line], $color_match) != 0)
  2026. {
  2027. $last_line = $color_match[1];
  2028. echo '</', substr($last_line, 1, 4), '>';
  2029. }
  2030. elseif ($last_line != '' && strpos($data2[$line], '<') !== false)
  2031. $last_line = '';
  2032. elseif ($last_line != '' && $data2[$line] != '')
  2033. echo '</', substr($last_line, 1, 4), '>';
  2034. if ($line == $match[1])
  2035. echo '</pre></div><pre style="margin: 0;">';
  2036. else
  2037. echo "\n";
  2038. }
  2039. echo '</pre></div>';
  2040. }
  2041. echo '
  2042. </body>
  2043. </html>';
  2044. }
  2045. die;
  2046. }
  2047. }
  2048. /**
  2049. * Initialize a database connection.
  2050. */
  2051. function loadDatabase()
  2052. {
  2053. global $db_persist, $db_connection, $db_server, $db_user, $db_passwd;
  2054. global $db_type, $db_name, $ssi_db_user, $ssi_db_passwd, $sourcedir, $db_prefix;
  2055. // Figure out what type of database we are using.
  2056. if (empty($db_type) || !file_exists($sourcedir . '/Subs-Db-' . $db_type . '.php'))
  2057. $db_type = 'mysql';
  2058. // Load the file for the database.
  2059. require_once($sourcedir . '/Subs-Db-' . $db_type . '.php');
  2060. // If we are in SSI try them first, but don't worry if it doesn't work, we have the normal username and password we can use.
  2061. if (SMF == 'SSI' && !empty($ssi_db_user) && !empty($ssi_db_passwd))
  2062. $db_connection = smf_db_initiate($db_server, $db_name, $ssi_db_user, $ssi_db_passwd, $db_prefix, array('persist' => $db_persist, 'non_fatal' => true, 'dont_select_db' => true));
  2063. // Either we aren't in SSI mode, or it failed.
  2064. if (empty($db_connection))
  2065. $db_connection = smf_db_initiate($db_server, $db_name, $db_user, $db_passwd, $db_prefix, array('persist' => $db_persist, 'dont_select_db' => SMF == 'SSI'));
  2066. // Safe guard here, if there isn't a valid connection lets put a stop to it.
  2067. if (!$db_connection)
  2068. db_fatal_error();
  2069. // If in SSI mode fix up the prefix.
  2070. if (SMF == 'SSI')
  2071. db_fix_prefix($db_prefix, $db_name);
  2072. }
  2073. /**
  2074. * Try to retrieve a cache entry. On failure, call the appropriate function.
  2075. * @todo find a better place for cache implementation
  2076. *
  2077. * @param $key
  2078. * @param $file
  2079. * @param $function
  2080. * @param $params
  2081. * @param int $level = 1
  2082. */
  2083. function cache_quick_get($key, $file, $function, $params, $level = 1)
  2084. {
  2085. global $modSettings, $sourcedir;
  2086. // Refresh the cache if either:
  2087. // 1. Caching is disabled.
  2088. // 2. The cache level isn't high enough.
  2089. // 3. The item has not been cached or the cached item expired.
  2090. // 4. The cached item has a custom expiration condition evaluating to true.
  2091. // 5. The expire time set in the cache item has passed (needed for Zend).
  2092. if (empty($modSettings['cache_enable']) || $modSettings['cache_enable'] < $level || !is_array($cache_block = cache_get_data($key, 3600)) || (!empty($cache_block['refresh_eval']) && eval($cache_block['refresh_eval'])) || (!empty($cache_block['expires']) && $cache_block['expires'] < time()))
  2093. {
  2094. require_once($sourcedir . '/' . $file);
  2095. $cache_block = call_user_func_array($function, $params);
  2096. if (!empty($modSettings['cache_enable']) && $modSettings['cache_enable'] >= $level)
  2097. cache_put_data($key, $cache_block, $cache_block['expires'] - time());
  2098. }
  2099. // Some cached data may need a freshening up after retrieval.
  2100. if (!empty($cache_block['post_retri_eval']))
  2101. eval($cache_block['post_retri_eval']);
  2102. return $cache_block['data'];
  2103. }
  2104. /**
  2105. * Puts value in the cache under key for ttl seconds.
  2106. * It may "miss" so shouldn't be depended on, and may go to any of many
  2107. * various caching servers.
  2108. * It supports eAccelerator, Turck MMCache, APC, ZPS, and memcached.
  2109. *
  2110. * @param string $key
  2111. * @param mixed $value
  2112. * @param int $ttl = 120
  2113. */
  2114. function cache_put_data($key, $value, $ttl = 120)
  2115. {
  2116. global $boardurl, $sourcedir, $modSettings, $memcached;
  2117. global $cache_hits, $cache_count, $db_show_debug, $cachedir;
  2118. if (empty($modSettings['cache_enable']) && !empty($modSettings))
  2119. return;
  2120. $cache_count = isset($cache_count) ? $cache_count + 1 : 1;
  2121. if (isset($db_show_debug) && $db_show_debug === true)
  2122. {
  2123. $cache_hits[$cache_count] = array('k' => $key, 'd' => 'put', 's' => $value === null ? 0 : strlen(serialize($value)));
  2124. $st = microtime();
  2125. }
  2126. $key = md5($boardurl . filemtime($sourcedir . '/Load.php')) . '-SMF-' . strtr($key, ':', '-');
  2127. $value = $value === null ? null : serialize($value);
  2128. // The simple yet efficient memcached.
  2129. if (function_exists('memcache_set') && isset($modSettings['cache_memcached']) && trim($modSettings['cache_memcached']) != '')
  2130. {
  2131. // Not connected yet?
  2132. if (empty($memcached))
  2133. get_memcached_server();
  2134. if (!$memcached)
  2135. return;
  2136. memcache_set($memcached, $key, $value, 0, $ttl);
  2137. }
  2138. // eAccelerator...
  2139. elseif (function_exists('eaccelerator_put'))
  2140. {
  2141. if (mt_rand(0, 10) == 1)
  2142. eaccelerator_gc();
  2143. if ($value === null)
  2144. @eaccelerator_rm($key);
  2145. else
  2146. eaccelerator_put($key, $value, $ttl);
  2147. }
  2148. // Turck MMCache?
  2149. elseif (function_exists('mmcache_put'))
  2150. {
  2151. if (mt_rand(0, 10) == 1)
  2152. mmcache_gc();
  2153. if ($value === null)
  2154. @mmcache_rm($key);
  2155. else
  2156. mmcache_put($key, $value, $ttl);
  2157. }
  2158. // Alternative PHP Cache, ahoy!
  2159. elseif (function_exists('apc_store'))
  2160. {
  2161. // An extended key is needed to counteract a bug in APC.
  2162. if ($value === null)
  2163. apc_delete($key . 'smf');
  2164. else
  2165. apc_store($key . 'smf', $value, $ttl);
  2166. }
  2167. // Zend Platform/ZPS/etc.
  2168. elseif (function_exists('output_cache_put'))
  2169. output_cache_put($key, $value);
  2170. elseif (function_exists('xcache_set') && ini_get('xcache.var_size') > 0)
  2171. {
  2172. if ($value === null)
  2173. xcache_unset($key);
  2174. else
  2175. xcache_set($key, $value, $ttl);
  2176. }
  2177. // Otherwise custom cache?
  2178. else
  2179. {
  2180. if ($value === null)
  2181. @unlink($cachedir . '/data_' . $key . '.php');
  2182. else
  2183. {
  2184. $cache_data = '<' . '?' . 'php if (!defined(\'SMF\')) die; if (' . (time() + $ttl) . ' < time()) $expired = true; else{$expired = false; $value = \'' . addcslashes($value, '\\\'') . '\';}' . '?' . '>';
  2185. $fh = @fopen($cachedir . '/data_' . $key . '.php', 'w');
  2186. if ($fh)
  2187. {
  2188. // Write the file.
  2189. set_file_buffer($fh, 0);
  2190. flock($fh, LOCK_EX);
  2191. $cache_bytes = fwrite($fh, $cache_data);
  2192. flock($fh, LOCK_UN);
  2193. fclose($fh);
  2194. // Check that the cache write was successful; all the data should be written
  2195. // If it fails due to low diskspace, remove the cache file
  2196. if ($cache_bytes != strlen($cache_data))
  2197. @unlink($cachedir . '/data_' . $key . '.php');
  2198. }
  2199. }
  2200. }
  2201. if (isset($db_show_debug) && $db_show_debug === true)
  2202. $cache_hits[$cache_count]['t'] = array_sum(explode(' ', microtime())) - array_sum(explode(' ', $st));
  2203. }
  2204. /**
  2205. * Gets the value from the cache specified by key, so long as it is not older
  2206. * than ttl seconds.
  2207. * It may often "miss", so shouldn't be depended on.
  2208. * It supports the same as cache_put_data().
  2209. *
  2210. * @param string $key
  2211. * @param int $ttl = 120
  2212. * @return string
  2213. */
  2214. function cache_get_data($key, $ttl = 120)
  2215. {
  2216. global $boardurl, $sourcedir, $modSettings, $memcached;
  2217. global $cache_hits, $cache_count, $db_show_debug, $cachedir;
  2218. if (empty($modSettings['cache_enable']) && !empty($modSettings))
  2219. return;
  2220. $cache_count = isset($cache_count) ? $cache_count + 1 : 1;
  2221. if (isset($db_show_debug) && $db_show_debug === true)
  2222. {
  2223. $cache_hits[$cache_count] = array('k' => $key, 'd' => 'get');
  2224. $st = microtime();
  2225. }
  2226. $key = md5($boardurl . filemtime($sourcedir . '/Load.php')) . '-SMF-' . strtr($key, ':', '-');
  2227. // Okay, let's go for it memcached!
  2228. if (function_exists('memcache_get') && isset($modSettings['cache_memcached']) && trim($modSettings['cache_memcached']) != '')
  2229. {
  2230. // Not connected yet?
  2231. if (empty($memcached))
  2232. get_memcached_server();
  2233. if (!$memcached)
  2234. return;
  2235. $value = memcache_get($memcached, $key);
  2236. }
  2237. // Again, eAccelerator.
  2238. elseif (function_exists('eaccelerator_get'))
  2239. $value = eaccelerator_get($key);
  2240. // The older, but ever-stable, Turck MMCache...
  2241. elseif (function_exists('mmcache_get'))
  2242. $value = mmcache_get($key);
  2243. // This is the free APC from PECL.
  2244. elseif (function_exists('apc_fetch'))
  2245. $value = apc_fetch($key . 'smf');
  2246. // Zend's pricey stuff.
  2247. elseif (function_exists('output_cache_get'))
  2248. $value = output_cache_get($key, $ttl);
  2249. elseif (function_exists('xcache_get') && ini_get('xcache.var_size') > 0)
  2250. $value = xcache_get($key);
  2251. // Otherwise it's SMF data!
  2252. elseif (file_exists($cachedir . '/data_' . $key . '.php') && filesize($cachedir . '/data_' . $key . '.php') > 10)
  2253. {
  2254. require($cachedir . '/data_' . $key . '.php');
  2255. if (!empty($expired) && isset($value))
  2256. {
  2257. @unlink($cachedir . '/data_' . $key . '.php');
  2258. unset($value);
  2259. }
  2260. }
  2261. if (isset($db_show_debug) && $db_show_debug === true)
  2262. {
  2263. $cache_hits[$cache_count]['t'] = array_sum(explode(' ', microtime())) - array_sum(explode(' ', $st));
  2264. $cache_hits[$cache_count]['s'] = isset($value) ? strlen($value) : 0;
  2265. }
  2266. if (empty($value))
  2267. return null;
  2268. // If it's broke, it's broke... so give up on it.
  2269. else
  2270. return @unserialize($value);
  2271. }
  2272. /**
  2273. * Get memcache servers.
  2274. * This function is used by cache_get_data() and cache_put_data().
  2275. * It attempts to connect to a random server in the cache_memcached setting.
  2276. * It recursively calls itself up to recursion_level times.
  2277. *
  2278. * @param int $level = 3
  2279. */
  2280. function get_memcached_server($level = 3)
  2281. {
  2282. global $modSettings, $memcached, $db_persist;
  2283. $servers = explode(',', $modSettings['cache_memcached']);
  2284. $server = explode(':', trim($servers[array_rand($servers)]));
  2285. // Don't try more times than we have servers!
  2286. $level = min(count($servers), $level);
  2287. // Don't wait too long: yes, we want the server, but we might be able to run the query faster!
  2288. if (empty($db_persist))
  2289. $memcached = memcache_connect($server[0], empty($server[1]) ? 11211 : $server[1]);
  2290. else
  2291. $memcached = memcache_pconnect($server[0], empty($server[1]) ? 11211 : $server[1]);
  2292. if (!$memcached && $level > 0)
  2293. get_memcached_server($level - 1);
  2294. }
  2295. ?>