ManageSearchEngines.php 28 KB

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