Load.php 110 KB

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