ManageSearchEngines.php 29 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105
  1. <?php
  2. /**
  3. * This file contains all the screens that relate to search engines.
  4. *
  5. * Simple Machines Forum (SMF)
  6. *
  7. * @package SMF
  8. * @author Simple Machines http://www.simplemachines.org
  9. * @copyright 2014 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. * Entry point for this section.
  18. */
  19. function SearchEngines()
  20. {
  21. global $context, $txt, $scripturl, $modSettings;
  22. isAllowedTo('admin_forum');
  23. loadLanguage('Search');
  24. loadTemplate('ManageSearch');
  25. if (!empty($modSettings['spider_mode']))
  26. {
  27. $subActions = array(
  28. 'editspiders' => 'EditSpider',
  29. 'logs' => 'SpiderLogs',
  30. 'settings' => 'ManageSearchEngineSettings',
  31. 'spiders' => 'ViewSpiders',
  32. 'stats' => 'SpiderStats',
  33. );
  34. $default = 'stats';
  35. }
  36. else
  37. {
  38. $subActions = array(
  39. 'settings' => 'ManageSearchEngineSettings',
  40. );
  41. $default = 'settings';
  42. }
  43. call_integration_hook('integrate_manage_search_engines', array(&$subActions));
  44. // Ensure we have a valid subaction.
  45. $context['sub_action'] = isset($_REQUEST['sa']) && isset($subActions[$_REQUEST['sa']]) ? $_REQUEST['sa'] : $default;
  46. $context['page_title'] = $txt['search_engines'];
  47. // Some more tab data.
  48. $context[$context['admin_menu_name']]['tab_data'] = array(
  49. 'title' => $txt['search_engines'],
  50. 'description' => $txt['search_engines_description'],
  51. );
  52. // Call the function!
  53. $subActions[$context['sub_action']]();
  54. }
  55. /**
  56. * This is really just the settings page.
  57. *
  58. * @param bool $return_config = false
  59. */
  60. function ManageSearchEngineSettings($return_config = false)
  61. {
  62. global $context, $txt, $modSettings, $scripturl, $sourcedir, $smcFunc;
  63. $config_vars = array(
  64. // How much detail?
  65. array('select', 'spider_mode', 'subtext' => $txt['spider_mode_note'], array($txt['spider_mode_off'], $txt['spider_mode_standard'], $txt['spider_mode_high'], $txt['spider_mode_vhigh']), 'onchange' => 'disableFields();'),
  66. 'spider_group' => array('select', 'spider_group', 'subtext' => $txt['spider_group_note'], array($txt['spider_group_none'], $txt['membergroups_members'])),
  67. array('select', 'show_spider_online', array($txt['show_spider_online_no'], $txt['show_spider_online_summary'], $txt['show_spider_online_detail'], $txt['show_spider_online_detail_admin'])),
  68. );
  69. // Set up a message.
  70. $context['settings_message'] = '<span class="smalltext">' . sprintf($txt['spider_settings_desc'], $scripturl . '?action=admin;area=logs;sa=pruning;' . $context['session_var'] . '=' . $context['session_id']) . '</span>';
  71. // Do some javascript.
  72. $javascript_function = '
  73. function disableFields()
  74. {
  75. disabledState = document.getElementById(\'spider_mode\').value == 0;';
  76. foreach ($config_vars as $variable)
  77. if ($variable[1] != 'spider_mode')
  78. $javascript_function .= '
  79. if (document.getElementById(\'' . $variable[1] . '\'))
  80. document.getElementById(\'' . $variable[1] . '\').disabled = disabledState;';
  81. $javascript_function .= '
  82. }
  83. disableFields();';
  84. call_integration_hook('integrate_modify_search_engine_settings', array(&$config_vars));
  85. if ($return_config)
  86. return $config_vars;
  87. // We need to load the groups for the spider group thingy.
  88. $request = $smcFunc['db_query']('', '
  89. SELECT id_group, group_name
  90. FROM {db_prefix}membergroups
  91. WHERE id_group != {int:admin_group}
  92. AND id_group != {int:moderator_group}',
  93. array(
  94. 'admin_group' => 1,
  95. 'moderator_group' => 3,
  96. )
  97. );
  98. while ($row = $smcFunc['db_fetch_assoc']($request))
  99. $config_vars['spider_group'][2][$row['id_group']] = $row['group_name'];
  100. $smcFunc['db_free_result']($request);
  101. // Make sure it's valid - note that regular members are given id_group = 1 which is reversed in Load.php - no admins here!
  102. if (isset($_POST['spider_group']) && !isset($config_vars['spider_group'][2][$_POST['spider_group']]))
  103. $_POST['spider_group'] = 0;
  104. // We'll want this for our easy save.
  105. require_once($sourcedir . '/ManageServer.php');
  106. // Setup the template.
  107. $context['page_title'] = $txt['settings'];
  108. $context['sub_template'] = 'show_settings';
  109. // Are we saving them - are we??
  110. if (isset($_GET['save']))
  111. {
  112. checkSession();
  113. call_integration_hook('integrate_save_search_engine_settings');
  114. saveDBSettings($config_vars);
  115. recacheSpiderNames();
  116. $_SESSION['adm-save'] = true;
  117. redirectexit('action=admin;area=sengines;sa=settings');
  118. }
  119. // Final settings...
  120. $context['post_url'] = $scripturl . '?action=admin;area=sengines;save;sa=settings';
  121. $context['settings_title'] = $txt['settings'];
  122. $context['settings_insert_below'] = '
  123. <script type="text/javascript"><!-- // --><![CDATA[
  124. ' . $javascript_function . '
  125. // ]]></script>';
  126. // Prepare the settings...
  127. prepareDBSettingContext($config_vars);
  128. }
  129. /**
  130. * View a list of all the spiders we know about.
  131. */
  132. function ViewSpiders()
  133. {
  134. global $context, $txt, $sourcedir, $scripturl, $smcFunc;
  135. if (!isset($_SESSION['spider_stat']) || $_SESSION['spider_stat'] < time() - 60)
  136. {
  137. consolidateSpiderStats();
  138. $_SESSION['spider_stat'] = time();
  139. }
  140. // Are we adding a new one?
  141. if (!empty($_POST['addSpider']))
  142. return EditSpider();
  143. // User pressed the 'remove selection button'.
  144. elseif (!empty($_POST['removeSpiders']) && !empty($_POST['remove']) && is_array($_POST['remove']))
  145. {
  146. checkSession();
  147. validateToken('admin-ser');
  148. // Make sure every entry is a proper integer.
  149. foreach ($_POST['remove'] as $index => $spider_id)
  150. $_POST['remove'][(int) $index] = (int) $spider_id;
  151. // Delete them all!
  152. $smcFunc['db_query']('', '
  153. DELETE FROM {db_prefix}spiders
  154. WHERE id_spider IN ({array_int:remove_list})',
  155. array(
  156. 'remove_list' => $_POST['remove'],
  157. )
  158. );
  159. $smcFunc['db_query']('', '
  160. DELETE FROM {db_prefix}log_spider_hits
  161. WHERE id_spider IN ({array_int:remove_list})',
  162. array(
  163. 'remove_list' => $_POST['remove'],
  164. )
  165. );
  166. $smcFunc['db_query']('', '
  167. DELETE FROM {db_prefix}log_spider_stats
  168. WHERE id_spider IN ({array_int:remove_list})',
  169. array(
  170. 'remove_list' => $_POST['remove'],
  171. )
  172. );
  173. cache_put_data('spider_search', null, 300);
  174. recacheSpiderNames();
  175. }
  176. // Get the last seens.
  177. $request = $smcFunc['db_query']('', '
  178. SELECT id_spider, MAX(last_seen) AS last_seen_time
  179. FROM {db_prefix}log_spider_stats
  180. GROUP BY id_spider',
  181. array(
  182. )
  183. );
  184. $context['spider_last_seen'] = array();
  185. while ($row = $smcFunc['db_fetch_assoc']($request))
  186. $context['spider_last_seen'][$row['id_spider']] = $row['last_seen_time'];
  187. $smcFunc['db_free_result']($request);
  188. createToken('admin-ser');
  189. $listOptions = array(
  190. 'id' => 'spider_list',
  191. 'title' => $txt['spiders'],
  192. 'items_per_page' => 20,
  193. 'base_href' => $scripturl . '?action=admin;area=sengines;sa=spiders',
  194. 'default_sort_col' => 'name',
  195. 'get_items' => array(
  196. 'function' => 'list_getSpiders',
  197. ),
  198. 'get_count' => array(
  199. 'function' => 'list_getNumSpiders',
  200. ),
  201. 'no_items_label' => $txt['spiders_no_entries'],
  202. 'columns' => array(
  203. 'name' => array(
  204. 'header' => array(
  205. 'value' => $txt['spider_name'],
  206. ),
  207. 'data' => array(
  208. 'function' => create_function('$rowData', '
  209. global $scripturl, $smcFunc;
  210. return sprintf(\'<a href="%1$s?action=admin;area=sengines;sa=editspiders;sid=%2$d">%3$s</a>\', $scripturl, $rowData[\'id_spider\'], $smcFunc[\'htmlspecialchars\']($rowData[\'spider_name\']));
  211. '),
  212. ),
  213. 'sort' => array(
  214. 'default' => 'spider_name',
  215. 'reverse' => 'spider_name DESC',
  216. ),
  217. ),
  218. 'last_seen' => array(
  219. 'header' => array(
  220. 'value' => $txt['spider_last_seen'],
  221. ),
  222. 'data' => array(
  223. 'function' => create_function('$rowData', '
  224. global $context, $txt;
  225. return isset($context[\'spider_last_seen\'][$rowData[\'id_spider\']]) ? timeformat($context[\'spider_last_seen\'][$rowData[\'id_spider\']]) : $txt[\'spider_last_never\'];
  226. '),
  227. ),
  228. ),
  229. 'user_agent' => array(
  230. 'header' => array(
  231. 'value' => $txt['spider_agent'],
  232. ),
  233. 'data' => array(
  234. 'db_htmlsafe' => 'user_agent',
  235. ),
  236. 'sort' => array(
  237. 'default' => 'user_agent',
  238. 'reverse' => 'user_agent DESC',
  239. ),
  240. ),
  241. 'ip_info' => array(
  242. 'header' => array(
  243. 'value' => $txt['spider_ip_info'],
  244. ),
  245. 'data' => array(
  246. 'db_htmlsafe' => 'ip_info',
  247. 'class' => 'smalltext',
  248. ),
  249. 'sort' => array(
  250. 'default' => 'ip_info',
  251. 'reverse' => 'ip_info DESC',
  252. ),
  253. ),
  254. 'check' => array(
  255. 'header' => array(
  256. 'value' => '<input type="checkbox" onclick="invertAll(this, this.form);" class="input_check" />',
  257. 'class' => 'centercol',
  258. ),
  259. 'data' => array(
  260. 'sprintf' => array(
  261. 'format' => '<input type="checkbox" name="remove[]" value="%1$d" class="input_check" />',
  262. 'params' => array(
  263. 'id_spider' => false,
  264. ),
  265. ),
  266. 'class' => 'centercol',
  267. ),
  268. ),
  269. ),
  270. 'form' => array(
  271. 'href' => $scripturl . '?action=admin;area=sengines;sa=spiders',
  272. 'token' => 'admin-ser',
  273. ),
  274. 'additional_rows' => array(
  275. array(
  276. 'position' => 'bottom_of_list',
  277. 'value' => '
  278. <input type="submit" name="removeSpiders" value="' . $txt['spiders_remove_selected'] . '" onclick="return confirm(\'' . $txt['spider_remove_selected_confirm'] . '\');" class="button_submit" />
  279. <input type="submit" name="addSpider" value="' . $txt['spiders_add'] . '" class="button_submit" />
  280. ',
  281. ),
  282. ),
  283. );
  284. require_once($sourcedir . '/Subs-List.php');
  285. createList($listOptions);
  286. $context['sub_template'] = 'show_list';
  287. $context['default_list'] = 'spider_list';
  288. }
  289. /**
  290. * Callback function for createList()
  291. * @param int $start
  292. * @param int $items_per_page
  293. * @param string sort
  294. */
  295. function list_getSpiders($start, $items_per_page, $sort)
  296. {
  297. global $smcFunc;
  298. $request = $smcFunc['db_query']('', '
  299. SELECT id_spider, spider_name, user_agent, ip_info
  300. FROM {db_prefix}spiders
  301. ORDER BY ' . $sort . '
  302. LIMIT ' . $start . ', ' . $items_per_page,
  303. array(
  304. )
  305. );
  306. $spiders = array();
  307. while ($row = $smcFunc['db_fetch_assoc']($request))
  308. $spiders[$row['id_spider']] = $row;
  309. $smcFunc['db_free_result']($request);
  310. return $spiders;
  311. }
  312. /**
  313. * Callback function for createList()
  314. * @return int
  315. */
  316. function list_getNumSpiders()
  317. {
  318. global $smcFunc;
  319. $request = $smcFunc['db_query']('', '
  320. SELECT COUNT(*) AS num_spiders
  321. FROM {db_prefix}spiders',
  322. array(
  323. )
  324. );
  325. list ($numSpiders) = $smcFunc['db_fetch_row']($request);
  326. $smcFunc['db_free_result']($request);
  327. return $numSpiders;
  328. }
  329. /**
  330. * Here we can add, and edit, spider info!
  331. */
  332. function EditSpider()
  333. {
  334. global $context, $smcFunc, $txt;
  335. // Some standard stuff.
  336. $context['id_spider'] = !empty($_GET['sid']) ? (int) $_GET['sid'] : 0;
  337. $context['page_title'] = $context['id_spider'] ? $txt['spiders_edit'] : $txt['spiders_add'];
  338. $context['sub_template'] = 'spider_edit';
  339. // Are we saving?
  340. if (!empty($_POST['save']))
  341. {
  342. checkSession();
  343. validateToken('admin-ses');
  344. $ips = array();
  345. // Check the IP range is valid.
  346. $ip_sets = explode(',', $_POST['spider_ip']);
  347. foreach ($ip_sets as $set)
  348. {
  349. $test = ip2range(trim($set));
  350. if (!empty($test))
  351. $ips[] = $set;
  352. }
  353. $ips = implode(',', $ips);
  354. // Goes in as it is...
  355. if ($context['id_spider'])
  356. $smcFunc['db_query']('', '
  357. UPDATE {db_prefix}spiders
  358. SET spider_name = {string:spider_name}, user_agent = {string:spider_agent},
  359. ip_info = {string:ip_info}
  360. WHERE id_spider = {int:current_spider}',
  361. array(
  362. 'current_spider' => $context['id_spider'],
  363. 'spider_name' => $_POST['spider_name'],
  364. 'spider_agent' => $_POST['spider_agent'],
  365. 'ip_info' => $ips,
  366. )
  367. );
  368. else
  369. $smcFunc['db_insert']('insert',
  370. '{db_prefix}spiders',
  371. array(
  372. 'spider_name' => 'string', 'user_agent' => 'string', 'ip_info' => 'string',
  373. ),
  374. array(
  375. $_POST['spider_name'], $_POST['spider_agent'], $ips,
  376. ),
  377. array('id_spider')
  378. );
  379. cache_put_data('spider_search', null);
  380. recacheSpiderNames();
  381. redirectexit('action=admin;area=sengines;sa=spiders');
  382. }
  383. // The default is new.
  384. $context['spider'] = array(
  385. 'id' => 0,
  386. 'name' => '',
  387. 'agent' => '',
  388. 'ip_info' => '',
  389. );
  390. // An edit?
  391. if ($context['id_spider'])
  392. {
  393. $request = $smcFunc['db_query']('', '
  394. SELECT id_spider, spider_name, user_agent, ip_info
  395. FROM {db_prefix}spiders
  396. WHERE id_spider = {int:current_spider}',
  397. array(
  398. 'current_spider' => $context['id_spider'],
  399. )
  400. );
  401. if ($row = $smcFunc['db_fetch_assoc']($request))
  402. $context['spider'] = array(
  403. 'id' => $row['id_spider'],
  404. 'name' => $row['spider_name'],
  405. 'agent' => $row['user_agent'],
  406. 'ip_info' => $row['ip_info'],
  407. );
  408. $smcFunc['db_free_result']($request);
  409. }
  410. createToken('admin-ses');
  411. }
  412. /**
  413. * Do we think the current user is a spider?
  414. *
  415. * @todo Should this not be... you know... in a different file?
  416. * @return int
  417. */
  418. function SpiderCheck()
  419. {
  420. global $modSettings, $smcFunc;
  421. if (isset($_SESSION['id_robot']))
  422. unset($_SESSION['id_robot']);
  423. $_SESSION['robot_check'] = time();
  424. // We cache the spider data for ten minutes if we can.
  425. if (($spider_data = cache_get_data('spider_search', 600)) === null)
  426. {
  427. $request = $smcFunc['db_query']('', '
  428. SELECT id_spider, user_agent, ip_info
  429. FROM {db_prefix}spiders
  430. ORDER BY LENGTH(user_agent) DESC',
  431. array(
  432. )
  433. );
  434. $spider_data = array();
  435. while ($row = $smcFunc['db_fetch_assoc']($request))
  436. $spider_data[] = $row;
  437. $smcFunc['db_free_result']($request);
  438. cache_put_data('spider_search', $spider_data, 600);
  439. }
  440. if (empty($spider_data))
  441. return false;
  442. // Only do these bits once.
  443. $ci_user_agent = strtolower($_SERVER['HTTP_USER_AGENT']);
  444. // Always attempt IPv6 first.
  445. if (strpos($_SERVER['REMOTE_ADDR'], ':') !== false)
  446. $ip_parts = convertIPv6toInts($_SERVER['REMOTE_ADDR']);
  447. else
  448. preg_match('/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $_SERVER['REMOTE_ADDR'], $ip_parts);
  449. foreach ($spider_data as $spider)
  450. {
  451. // User agent is easy.
  452. if (!empty($spider['user_agent']) && strpos($ci_user_agent, strtolower($spider['user_agent'])) !== false)
  453. $_SESSION['id_robot'] = $spider['id_spider'];
  454. // IP stuff is harder.
  455. elseif (!empty($ip_parts))
  456. {
  457. $ips = explode(',', $spider['ip_info']);
  458. foreach ($ips as $ip)
  459. {
  460. $ip = ip2range($ip);
  461. if (!empty($ip))
  462. {
  463. foreach ($ip as $key => $value)
  464. {
  465. if ($value['low'] > $ip_parts[$key + 1] || $value['high'] < $ip_parts[$key + 1])
  466. break;
  467. elseif (($key == 7 && strpos($_SERVER['REMOTE_ADDR'], ':') !== false) || ($key == 3 && strpos($_SERVER['REMOTE_ADDR'], ':') === false))
  468. $_SESSION['id_robot'] = $spider['id_spider'];
  469. }
  470. }
  471. }
  472. }
  473. if (isset($_SESSION['id_robot']))
  474. break;
  475. }
  476. // If this is low server tracking then log the spider here as oppossed to the main logging function.
  477. if (!empty($modSettings['spider_mode']) && $modSettings['spider_mode'] == 1 && !empty($_SESSION['id_robot']))
  478. logSpider();
  479. return !empty($_SESSION['id_robot']) ? $_SESSION['id_robot'] : 0;
  480. }
  481. /**
  482. * Log the spider presence online.
  483. *
  484. * @todo Different file?
  485. */
  486. function logSpider()
  487. {
  488. global $smcFunc, $modSettings, $context;
  489. if (empty($modSettings['spider_mode']) || empty($_SESSION['id_robot']))
  490. return;
  491. // Attempt to update today's entry.
  492. if ($modSettings['spider_mode'] == 1)
  493. {
  494. $date = strftime('%Y-%m-%d', forum_time(false));
  495. $smcFunc['db_query']('', '
  496. UPDATE {db_prefix}log_spider_stats
  497. SET last_seen = {int:current_time}, page_hits = page_hits + 1
  498. WHERE id_spider = {int:current_spider}
  499. AND stat_date = {date:current_date}',
  500. array(
  501. 'current_date' => $date,
  502. 'current_time' => time(),
  503. 'current_spider' => $_SESSION['id_robot'],
  504. )
  505. );
  506. // Nothing updated?
  507. if ($smcFunc['db_affected_rows']() == 0)
  508. {
  509. $smcFunc['db_insert']('ignore',
  510. '{db_prefix}log_spider_stats',
  511. array(
  512. 'id_spider' => 'int', 'last_seen' => 'int', 'stat_date' => 'date', 'page_hits' => 'int',
  513. ),
  514. array(
  515. $_SESSION['id_robot'], time(), $date, 1,
  516. ),
  517. array('id_spider', 'stat_date')
  518. );
  519. }
  520. }
  521. // If we're tracking better stats than track, better stats - we sort out the today thing later.
  522. else
  523. {
  524. if ($modSettings['spider_mode'] > 2)
  525. {
  526. $url = $_GET + array('USER_AGENT' => $_SERVER['HTTP_USER_AGENT']);
  527. unset($url['sesc'], $url[$context['session_var']]);
  528. $url = serialize($url);
  529. }
  530. else
  531. $url = '';
  532. $smcFunc['db_insert']('insert',
  533. '{db_prefix}log_spider_hits',
  534. array('id_spider' => 'int', 'log_time' => 'int', 'url' => 'string'),
  535. array($_SESSION['id_robot'], time(), $url),
  536. array()
  537. );
  538. }
  539. }
  540. /**
  541. * This function takes any unprocessed hits and turns them into stats.
  542. */
  543. function consolidateSpiderStats()
  544. {
  545. global $smcFunc;
  546. $request = $smcFunc['db_query']('consolidate_spider_stats', '
  547. SELECT id_spider, MAX(log_time) AS last_seen, COUNT(*) AS num_hits
  548. FROM {db_prefix}log_spider_hits
  549. WHERE processed = {int:not_processed}
  550. GROUP BY id_spider, MONTH(log_time), DAYOFMONTH(log_time)',
  551. array(
  552. 'not_processed' => 0,
  553. )
  554. );
  555. $spider_hits = array();
  556. while ($row = $smcFunc['db_fetch_assoc']($request))
  557. $spider_hits[] = $row;
  558. $smcFunc['db_free_result']($request);
  559. if (empty($spider_hits))
  560. return;
  561. // Attempt to update the master data.
  562. $stat_inserts = array();
  563. foreach ($spider_hits as $stat)
  564. {
  565. // We assume the max date is within the right day.
  566. $date = strftime('%Y-%m-%d', $stat['last_seen']);
  567. $smcFunc['db_query']('', '
  568. UPDATE {db_prefix}log_spider_stats
  569. SET page_hits = page_hits + ' . $stat['num_hits'] . ',
  570. last_seen = CASE WHEN last_seen > {int:last_seen} THEN last_seen ELSE {int:last_seen} END
  571. WHERE id_spider = {int:current_spider}
  572. AND stat_date = {date:last_seen_date}',
  573. array(
  574. 'last_seen_date' => $date,
  575. 'last_seen' => $stat['last_seen'],
  576. 'current_spider' => $stat['id_spider'],
  577. )
  578. );
  579. if ($smcFunc['db_affected_rows']() == 0)
  580. $stat_inserts[] = array($date, $stat['id_spider'], $stat['num_hits'], $stat['last_seen']);
  581. }
  582. // New stats?
  583. if (!empty($stat_inserts))
  584. $smcFunc['db_insert']('ignore',
  585. '{db_prefix}log_spider_stats',
  586. array('stat_date' => 'date', 'id_spider' => 'int', 'page_hits' => 'int', 'last_seen' => 'int'),
  587. $stat_inserts,
  588. array('stat_date', 'id_spider')
  589. );
  590. // All processed.
  591. $smcFunc['db_query']('', '
  592. UPDATE {db_prefix}log_spider_hits
  593. SET processed = {int:is_processed}
  594. WHERE processed = {int:not_processed}',
  595. array(
  596. 'is_processed' => 1,
  597. 'not_processed' => 0,
  598. )
  599. );
  600. }
  601. /**
  602. * See what spiders have been up to.
  603. */
  604. function SpiderLogs()
  605. {
  606. global $context, $txt, $sourcedir, $scripturl, $smcFunc, $modSettings;
  607. // Load the template and language just incase.
  608. loadLanguage('Search');
  609. loadTemplate('ManageSearch');
  610. // Did they want to delete some entries?
  611. if (!empty($_POST['delete_entries']) && isset($_POST['older']))
  612. {
  613. checkSession();
  614. validateToken('admin-sl');
  615. $deleteTime = time() - (((int) $_POST['older']) * 24 * 60 * 60);
  616. // Delete the entires.
  617. $smcFunc['db_query']('', '
  618. DELETE FROM {db_prefix}log_spider_hits
  619. WHERE log_time < {int:delete_period}',
  620. array(
  621. 'delete_period' => $deleteTime,
  622. )
  623. );
  624. }
  625. $listOptions = array(
  626. 'id' => 'spider_logs',
  627. 'items_per_page' => 20,
  628. 'title' => $txt['spider_logs'],
  629. 'no_items_label' => $txt['spider_logs_empty'],
  630. 'base_href' => $context['admin_area'] == 'sengines' ? $scripturl . '?action=admin;area=sengines;sa=logs' : $scripturl . '?action=admin;area=logs;sa=spiderlog',
  631. 'default_sort_col' => 'log_time',
  632. 'get_items' => array(
  633. 'function' => 'list_getSpiderLogs',
  634. ),
  635. 'get_count' => array(
  636. 'function' => 'list_getNumSpiderLogs',
  637. ),
  638. 'columns' => array(
  639. 'name' => array(
  640. 'header' => array(
  641. 'value' => $txt['spider'],
  642. ),
  643. 'data' => array(
  644. 'db' => 'spider_name',
  645. ),
  646. 'sort' => array(
  647. 'default' => 's.spider_name',
  648. 'reverse' => 's.spider_name DESC',
  649. ),
  650. ),
  651. 'log_time' => array(
  652. 'header' => array(
  653. 'value' => $txt['spider_time'],
  654. ),
  655. 'data' => array(
  656. 'function' => create_function('$rowData', '
  657. return timeformat($rowData[\'log_time\']);
  658. '),
  659. ),
  660. 'sort' => array(
  661. 'default' => 'sl.id_hit DESC',
  662. 'reverse' => 'sl.id_hit',
  663. ),
  664. ),
  665. 'viewing' => array(
  666. 'header' => array(
  667. 'value' => $txt['spider_viewing'],
  668. ),
  669. 'data' => array(
  670. 'db' => 'url',
  671. ),
  672. ),
  673. ),
  674. 'form' => array(
  675. 'token' => 'admin-sl',
  676. 'href' => $scripturl . '?action=admin;area=sengines;sa=logs',
  677. ),
  678. 'additional_rows' => array(
  679. array(
  680. 'position' => 'after_title',
  681. 'value' => $txt['spider_logs_info'],
  682. 'class' => 'windowbg2',
  683. ),
  684. array(
  685. 'position' => 'below_table_data',
  686. 'value' => '<input type="submit" name="removeAll" value="' . $txt['spider_log_empty_log'] . '" onclick="return confirm(\'' . $txt['spider_log_empty_log_confirm'] . '\');" class="button_submit" />',
  687. ),
  688. ),
  689. );
  690. createToken('admin-sl');
  691. require_once($sourcedir . '/Subs-List.php');
  692. createList($listOptions);
  693. // Now determine the actions of the URLs.
  694. if (!empty($context['spider_logs']['rows']))
  695. {
  696. $urls = array();
  697. // Grab the current /url.
  698. foreach ($context['spider_logs']['rows'] as $k => $row)
  699. {
  700. // Feature disabled?
  701. if (empty($row['viewing']['value']) && isset($modSettings['spider_mode']) && $modSettings['spider_mode'] < 3)
  702. $context['spider_logs']['rows'][$k]['viewing']['value'] = '<em>' . $txt['spider_disabled'] . '</em>';
  703. else
  704. $urls[$k] = array($row['viewing']['value'], -1);
  705. }
  706. // Now stick in the new URLs.
  707. require_once($sourcedir . '/Who.php');
  708. $urls = determineActions($urls, 'whospider_');
  709. foreach ($urls as $k => $new_url)
  710. {
  711. $context['spider_logs']['rows'][$k]['viewing']['value'] = $new_url;
  712. }
  713. }
  714. $context['page_title'] = $txt['spider_logs'];
  715. $context['sub_template'] = 'show_spider_logs';
  716. $context['default_list'] = 'spider_logs';
  717. }
  718. /**
  719. * Callback function for createList()
  720. *
  721. * @param int $start
  722. * @param int $items_per_page
  723. * @param string $sort
  724. * @return array
  725. */
  726. function list_getSpiderLogs($start, $items_per_page, $sort)
  727. {
  728. global $smcFunc;
  729. $request = $smcFunc['db_query']('', '
  730. SELECT sl.id_spider, sl.url, sl.log_time, s.spider_name
  731. FROM {db_prefix}log_spider_hits AS sl
  732. INNER JOIN {db_prefix}spiders AS s ON (s.id_spider = sl.id_spider)
  733. ORDER BY ' . $sort . '
  734. LIMIT ' . $start . ', ' . $items_per_page,
  735. array(
  736. )
  737. );
  738. $spider_logs = array();
  739. while ($row = $smcFunc['db_fetch_assoc']($request))
  740. $spider_logs[] = $row;
  741. $smcFunc['db_free_result']($request);
  742. return $spider_logs;
  743. }
  744. /**
  745. * Callback function for createList()
  746. * @return int
  747. */
  748. function list_getNumSpiderLogs()
  749. {
  750. global $smcFunc;
  751. $request = $smcFunc['db_query']('', '
  752. SELECT COUNT(*) AS num_logs
  753. FROM {db_prefix}log_spider_hits',
  754. array(
  755. )
  756. );
  757. list ($numLogs) = $smcFunc['db_fetch_row']($request);
  758. $smcFunc['db_free_result']($request);
  759. return $numLogs;
  760. }
  761. /**
  762. * Show the spider statistics.
  763. */
  764. function SpiderStats()
  765. {
  766. global $context, $txt, $sourcedir, $scripturl, $smcFunc;
  767. // Force an update of the stats every 60 seconds.
  768. if (!isset($_SESSION['spider_stat']) || $_SESSION['spider_stat'] < time() - 60)
  769. {
  770. consolidateSpiderStats();
  771. $_SESSION['spider_stat'] = time();
  772. }
  773. // Are we cleaning up some old stats?
  774. if (!empty($_POST['delete_entries']) && isset($_POST['older']))
  775. {
  776. checkSession();
  777. validateToken('admin-ss');
  778. $deleteTime = time() - (((int) $_POST['older']) * 24 * 60 * 60);
  779. // Delete the entires.
  780. $smcFunc['db_query']('', '
  781. DELETE FROM {db_prefix}log_spider_stats
  782. WHERE last_seen < {int:delete_period}',
  783. array(
  784. 'delete_period' => $deleteTime,
  785. )
  786. );
  787. }
  788. // Get the earliest and latest dates.
  789. $request = $smcFunc['db_query']('', '
  790. SELECT MIN(stat_date) AS first_date, MAX(stat_date) AS last_date
  791. FROM {db_prefix}log_spider_stats',
  792. array(
  793. )
  794. );
  795. list ($min_date, $max_date) = $smcFunc['db_fetch_row']($request);
  796. $smcFunc['db_free_result']($request);
  797. $min_year = (int) substr($min_date, 0, 4);
  798. $max_year = (int) substr($max_date, 0, 4);
  799. $min_month = (int) substr($min_date, 5, 2);
  800. $max_month = (int) substr($max_date, 5, 2);
  801. // Prepare the dates for the drop down.
  802. $date_choices = array();
  803. for ($y = $min_year; $y <= $max_year; $y++)
  804. for ($m = 1; $m <= 12; $m++)
  805. {
  806. // This doesn't count?
  807. if ($y == $min_year && $m < $min_month)
  808. continue;
  809. if ($y == $max_year && $m > $max_month)
  810. break;
  811. $date_choices[$y . $m] = $txt['months_short'][$m] . ' ' . $y;
  812. }
  813. // What are we currently viewing?
  814. $current_date = isset($_REQUEST['new_date']) && isset($date_choices[$_REQUEST['new_date']]) ? $_REQUEST['new_date'] : $max_date;
  815. // Prepare the HTML.
  816. $date_select = '
  817. ' . $txt['spider_stats_select_month'] . ':
  818. <select name="new_date" onchange="document.spider_stat_list.submit();">';
  819. if (empty($date_choices))
  820. $date_select .= '
  821. <option></option>';
  822. else
  823. foreach ($date_choices as $id => $text)
  824. $date_select .= '
  825. <option value="' . $id . '"' . ($current_date == $id ? ' selected="selected"' : '') . '>' . $text . '</option>';
  826. $date_select .= '
  827. </select>
  828. <noscript>
  829. <input type="submit" name="go" value="' . $txt['go'] . '" class="button_submit" />
  830. </noscript>';
  831. // If we manually jumped to a date work out the offset.
  832. if (isset($_REQUEST['new_date']))
  833. {
  834. $date_query = sprintf('%04d-%02d-01', substr($current_date, 0, 4), substr($current_date, 4));
  835. $request = $smcFunc['db_query']('', '
  836. SELECT COUNT(*) AS offset
  837. FROM {db_prefix}log_spider_stats
  838. WHERE stat_date < {date:date_being_viewed}',
  839. array(
  840. 'date_being_viewed' => $date_query,
  841. )
  842. );
  843. list ($_REQUEST['start']) = $smcFunc['db_fetch_row']($request);
  844. $smcFunc['db_free_result']($request);
  845. }
  846. $listOptions = array(
  847. 'id' => 'spider_stat_list',
  848. 'title' => $txt['spider'] . ' ' . $txt['spider_stats'],
  849. 'items_per_page' => 20,
  850. 'base_href' => $scripturl . '?action=admin;area=sengines;sa=stats',
  851. 'default_sort_col' => 'stat_date',
  852. 'get_items' => array(
  853. 'function' => 'list_getSpiderStats',
  854. ),
  855. 'get_count' => array(
  856. 'function' => 'list_getNumSpiderStats',
  857. ),
  858. 'no_items_label' => $txt['spider_stats_no_entries'],
  859. 'columns' => array(
  860. 'stat_date' => array(
  861. 'header' => array(
  862. 'value' => $txt['date'],
  863. ),
  864. 'data' => array(
  865. 'db' => 'stat_date',
  866. ),
  867. 'sort' => array(
  868. 'default' => 'stat_date',
  869. 'reverse' => 'stat_date DESC',
  870. ),
  871. ),
  872. 'name' => array(
  873. 'header' => array(
  874. 'value' => $txt['spider_name'],
  875. ),
  876. 'data' => array(
  877. 'db' => 'spider_name',
  878. ),
  879. 'sort' => array(
  880. 'default' => 's.spider_name',
  881. 'reverse' => 's.spider_name DESC',
  882. ),
  883. ),
  884. 'page_hits' => array(
  885. 'header' => array(
  886. 'value' => $txt['spider_stats_page_hits'],
  887. ),
  888. 'data' => array(
  889. 'db' => 'page_hits',
  890. ),
  891. 'sort' => array(
  892. 'default' => 'ss.page_hits',
  893. 'reverse' => 'ss.page_hits DESC',
  894. ),
  895. ),
  896. ),
  897. 'form' => array(
  898. 'href' => $scripturl . '?action=admin;area=sengines;sa=stats',
  899. 'name' => 'spider_stat_list',
  900. ),
  901. 'additional_rows' => array(
  902. array(
  903. 'position' => 'below_table_data',
  904. 'value' => $date_select,
  905. 'style' => 'text-align: right;',
  906. ),
  907. ),
  908. );
  909. createToken('admin-ss');
  910. require_once($sourcedir . '/Subs-List.php');
  911. createList($listOptions);
  912. $context['sub_template'] = 'show_spider_stats';
  913. $context['default_list'] = 'spider_stat_list';
  914. }
  915. /**
  916. * Callback function for createList()
  917. * Get a list of spider stats from the log_spider table
  918. *
  919. * @param type $start
  920. * @param type $items_per_page
  921. * @param type $sort
  922. * @return array
  923. */
  924. function list_getSpiderStats($start, $items_per_page, $sort)
  925. {
  926. global $smcFunc;
  927. $request = $smcFunc['db_query']('', '
  928. SELECT ss.id_spider, ss.stat_date, ss.page_hits, s.spider_name
  929. FROM {db_prefix}log_spider_stats AS ss
  930. INNER JOIN {db_prefix}spiders AS s ON (s.id_spider = ss.id_spider)
  931. ORDER BY ' . $sort . '
  932. LIMIT ' . $start . ', ' . $items_per_page,
  933. array(
  934. )
  935. );
  936. $spider_stats = array();
  937. while ($row = $smcFunc['db_fetch_assoc']($request))
  938. $spider_stats[] = $row;
  939. $smcFunc['db_free_result']($request);
  940. return $spider_stats;
  941. }
  942. /**
  943. * Callback function for createList()
  944. * Get the number of spider stat rows from the log spicer stats table
  945. *
  946. * @return int
  947. */
  948. function list_getNumSpiderStats()
  949. {
  950. global $smcFunc;
  951. $request = $smcFunc['db_query']('', '
  952. SELECT COUNT(*) AS num_stats
  953. FROM {db_prefix}log_spider_stats',
  954. array(
  955. )
  956. );
  957. list ($numStats) = $smcFunc['db_fetch_row']($request);
  958. $smcFunc['db_free_result']($request);
  959. return $numStats;
  960. }
  961. /**
  962. * Recache spider names?
  963. */
  964. function recacheSpiderNames()
  965. {
  966. global $smcFunc;
  967. $request = $smcFunc['db_query']('', '
  968. SELECT id_spider, spider_name
  969. FROM {db_prefix}spiders',
  970. array(
  971. )
  972. );
  973. $spiders = array();
  974. while ($row = $smcFunc['db_fetch_assoc']($request))
  975. $spiders[$row['id_spider']] = $row['spider_name'];
  976. $smcFunc['db_free_result']($request);
  977. updateSettings(array('spider_name_cache' => serialize($spiders)));
  978. }
  979. ?>