Load.php 109 KB

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