Load.php 121 KB

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