PageRenderTime 56ms CodeModel.GetById 26ms RepoModel.GetById 0ms app.codeStats 0ms

/admin/tool/log/store/legacy/classes/log/store.php

https://github.com/marxjohnson/moodle
PHP | 362 lines | 217 code | 46 blank | 99 comment | 29 complexity | 189c77c64ce7ac3fa983eb1e48c0aea4 MD5 | raw file
  1. <?php
  2. // This file is part of Moodle - http://moodle.org/
  3. //
  4. // Moodle is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // Moodle is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU General Public License
  15. // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
  16. /**
  17. * Legacy log reader.
  18. *
  19. * @package logstore_legacy
  20. * @copyright 2013 Petr Skoda {@link http://skodak.org}
  21. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  22. */
  23. namespace logstore_legacy\log;
  24. defined('MOODLE_INTERNAL') || die();
  25. class store implements \tool_log\log\store, \core\log\sql_reader {
  26. use \tool_log\helper\store,
  27. \tool_log\helper\reader;
  28. public function __construct(\tool_log\log\manager $manager) {
  29. $this->helper_setup($manager);
  30. }
  31. /** @var array list of db fields which needs to be replaced for legacy log query */
  32. protected static $standardtolegacyfields = array(
  33. 'timecreated' => 'time',
  34. 'courseid' => 'course',
  35. 'contextinstanceid' => 'cmid',
  36. 'origin' => 'ip',
  37. 'anonymous' => 0,
  38. );
  39. /** @var string Regex to replace the crud params */
  40. const CRUD_REGEX = "/(crud).*?(<>|=|!=).*?'(.*?)'/s";
  41. /**
  42. * This method contains mapping required for Moodle core to make legacy store compatible with other sql_reader based
  43. * queries.
  44. *
  45. * @param string $selectwhere Select statment
  46. * @param array $params params for the sql
  47. * @param string $sort sort fields
  48. *
  49. * @return array returns an array containing the sql predicate, an array of params and sorting parameter.
  50. */
  51. protected static function replace_sql_legacy($selectwhere, array $params, $sort = '') {
  52. // Following mapping is done to make can_delete_course() compatible with legacy store.
  53. if ($selectwhere == "userid = :userid AND courseid = :courseid AND eventname = :eventname AND timecreated > :since" and
  54. empty($sort)) {
  55. $replace = "module = 'course' AND action = 'new' AND userid = :userid AND url = :url AND time > :since";
  56. $params += array('url' => "view.php?id={$params['courseid']}");
  57. return array($replace, $params, $sort);
  58. }
  59. // Replace db field names to make it compatible with legacy log.
  60. foreach (self::$standardtolegacyfields as $from => $to) {
  61. $selectwhere = str_replace($from, $to, $selectwhere);
  62. if (!empty($sort)) {
  63. $sort = str_replace($from, $to, $sort);
  64. }
  65. if (isset($params[$from])) {
  66. $params[$to] = $params[$from];
  67. unset($params[$from]);
  68. }
  69. }
  70. // Replace crud fields.
  71. $selectwhere = preg_replace_callback("/(crud).*?(<>|=|!=).*?'(.*?)'/s", 'self::replace_crud', $selectwhere);
  72. return array($selectwhere, $params, $sort);
  73. }
  74. public function get_events_select($selectwhere, array $params, $sort, $limitfrom, $limitnum) {
  75. global $DB;
  76. $sort = self::tweak_sort_by_id($sort);
  77. // Replace the query with hardcoded mappings required for core.
  78. list($selectwhere, $params, $sort) = self::replace_sql_legacy($selectwhere, $params, $sort);
  79. $records = array();
  80. try {
  81. // A custom report + on the fly SQL rewriting = a possible exception.
  82. $records = $DB->get_recordset_select('log', $selectwhere, $params, $sort, '*', $limitfrom, $limitnum);
  83. } catch (\moodle_exception $ex) {
  84. debugging("error converting legacy event data " . $ex->getMessage() . $ex->debuginfo, DEBUG_DEVELOPER);
  85. return array();
  86. }
  87. $events = array();
  88. foreach ($records as $data) {
  89. $events[$data->id] = $this->get_log_event($data);
  90. }
  91. $records->close();
  92. return $events;
  93. }
  94. /**
  95. * Fetch records using given criteria returning a Traversable object.
  96. *
  97. * Note that the traversable object contains a moodle_recordset, so
  98. * remember that is important that you call close() once you finish
  99. * using it.
  100. *
  101. * @param string $selectwhere
  102. * @param array $params
  103. * @param string $sort
  104. * @param int $limitfrom
  105. * @param int $limitnum
  106. * @return \Traversable|\core\event\base[]
  107. */
  108. public function get_events_select_iterator($selectwhere, array $params, $sort, $limitfrom, $limitnum) {
  109. global $DB;
  110. $sort = self::tweak_sort_by_id($sort);
  111. // Replace the query with hardcoded mappings required for core.
  112. list($selectwhere, $params, $sort) = self::replace_sql_legacy($selectwhere, $params, $sort);
  113. try {
  114. $recordset = $DB->get_recordset_select('log', $selectwhere, $params, $sort, '*', $limitfrom, $limitnum);
  115. } catch (\moodle_exception $ex) {
  116. debugging("error converting legacy event data " . $ex->getMessage() . $ex->debuginfo, DEBUG_DEVELOPER);
  117. return new \EmptyIterator;
  118. }
  119. return new \core\dml\recordset_walk($recordset, array($this, 'get_log_event'));
  120. }
  121. /**
  122. * Returns an event from the log data.
  123. *
  124. * @param stdClass $data Log data
  125. * @return \core\event\base
  126. */
  127. public function get_log_event($data) {
  128. return \logstore_legacy\event\legacy_logged::restore_legacy($data);
  129. }
  130. public function get_events_select_count($selectwhere, array $params) {
  131. global $DB;
  132. // Replace the query with hardcoded mappings required for core.
  133. list($selectwhere, $params) = self::replace_sql_legacy($selectwhere, $params);
  134. try {
  135. return $DB->count_records_select('log', $selectwhere, $params);
  136. } catch (\moodle_exception $ex) {
  137. debugging("error converting legacy event data " . $ex->getMessage() . $ex->debuginfo, DEBUG_DEVELOPER);
  138. return 0;
  139. }
  140. }
  141. /**
  142. * Are the new events appearing in the reader?
  143. *
  144. * @return bool true means new log events are being added, false means no new data will be added
  145. */
  146. public function is_logging() {
  147. return (bool)$this->get_config('loglegacy', true);
  148. }
  149. public function dispose() {
  150. }
  151. /**
  152. * Legacy add_to_log() code.
  153. *
  154. * @param int $courseid The course id
  155. * @param string $module The module name e.g. forum, journal, resource, course, user etc
  156. * @param string $action 'view', 'update', 'add' or 'delete', possibly followed by another word to clarify.
  157. * @param string $url The file and parameters used to see the results of the action
  158. * @param string $info Additional description information
  159. * @param int $cm The course_module->id if there is one
  160. * @param int|\stdClass $user If log regards $user other than $USER
  161. * @param string $ip Override the IP, should only be used for restore.
  162. * @param int $time Override the log time, should only be used for restore.
  163. */
  164. public function legacy_add_to_log($courseid, $module, $action, $url, $info, $cm, $user, $ip = null, $time = null) {
  165. // Note that this function intentionally does not follow the normal Moodle DB access idioms.
  166. // This is for a good reason: it is the most frequently used DB update function,
  167. // so it has been optimised for speed.
  168. global $DB, $CFG, $USER;
  169. if (!$this->is_logging()) {
  170. return;
  171. }
  172. if ($cm === '' || is_null($cm)) { // Postgres won't translate empty string to its default.
  173. $cm = 0;
  174. }
  175. if ($user) {
  176. $userid = $user;
  177. } else {
  178. if (\core\session\manager::is_loggedinas()) { // Don't log.
  179. return;
  180. }
  181. $userid = empty($USER->id) ? '0' : $USER->id;
  182. }
  183. if (isset($CFG->logguests) and !$CFG->logguests) {
  184. if (!$userid or isguestuser($userid)) {
  185. return;
  186. }
  187. }
  188. $remoteaddr = (is_null($ip)) ? getremoteaddr() : $ip;
  189. $timenow = (is_null($time)) ? time() : $time;
  190. if (!empty($url)) { // Could break doing html_entity_decode on an empty var.
  191. $url = html_entity_decode($url, ENT_QUOTES, 'UTF-8');
  192. } else {
  193. $url = '';
  194. }
  195. // Restrict length of log lines to the space actually available in the
  196. // database so that it doesn't cause a DB error. Log a warning so that
  197. // developers can avoid doing things which are likely to cause this on a
  198. // routine basis.
  199. if (\core_text::strlen($action) > 40) {
  200. $action = \core_text::substr($action, 0, 37) . '...';
  201. debugging('Warning: logged very long action', DEBUG_DEVELOPER);
  202. }
  203. if (!empty($info) && \core_text::strlen($info) > 255) {
  204. $info = \core_text::substr($info, 0, 252) . '...';
  205. debugging('Warning: logged very long info', DEBUG_DEVELOPER);
  206. }
  207. // If the 100 field size is changed, also need to alter print_log in course/lib.php.
  208. if (!empty($url) && \core_text::strlen($url) > 100) {
  209. $url = \core_text::substr($url, 0, 97) . '...';
  210. debugging('Warning: logged very long URL', DEBUG_DEVELOPER);
  211. }
  212. if (defined('MDL_PERFDB')) {
  213. global $PERF;
  214. $PERF->logwrites++;
  215. };
  216. $log = array('time' => $timenow, 'userid' => $userid, 'course' => $courseid, 'ip' => $remoteaddr,
  217. 'module' => $module, 'cmid' => $cm, 'action' => $action, 'url' => $url, 'info' => $info);
  218. try {
  219. $DB->insert_record_raw('log', $log, false);
  220. } catch (\dml_exception $e) {
  221. debugging('Error: Could not insert a new entry to the Moodle log. ' . $e->errorcode, DEBUG_ALL);
  222. // MDL-11893, alert $CFG->supportemail if insert into log failed.
  223. if ($CFG->supportemail and empty($CFG->noemailever)) {
  224. // Function email_to_user is not usable because email_to_user tries to write to the logs table,
  225. // and this will get caught in an infinite loop, if disk is full.
  226. $site = get_site();
  227. $subject = 'Insert into log failed at your moodle site ' . $site->fullname;
  228. $message = "Insert into log table failed at " . date('l dS \of F Y h:i:s A') .
  229. ".\n It is possible that your disk is full.\n\n";
  230. $message .= "The failed query parameters are:\n\n" . var_export($log, true);
  231. $lasttime = get_config('admin', 'lastloginserterrormail');
  232. if (empty($lasttime) || time() - $lasttime > 60 * 60 * 24) { // Limit to 1 email per day.
  233. // Using email directly rather than messaging as they may not be able to log in to access a message.
  234. mail($CFG->supportemail, $subject, $message);
  235. set_config('lastloginserterrormail', time(), 'admin');
  236. }
  237. }
  238. }
  239. }
  240. /**
  241. * Generate a replace string for crud related sql conditions. This function is called as callback to preg_replace_callback()
  242. * on the actual sql.
  243. *
  244. * @param array $match matched string for the passed pattern
  245. *
  246. * @return string The sql string to use instead of original
  247. */
  248. protected static function replace_crud($match) {
  249. $return = '';
  250. unset($match[0]); // The first entry is the whole string.
  251. foreach ($match as $m) {
  252. // We hard code LIKE here because we are not worried about case sensitivity and want this to be fast.
  253. switch ($m) {
  254. case 'crud' :
  255. $replace = 'action';
  256. break;
  257. case 'c' :
  258. switch ($match[2]) {
  259. case '=' :
  260. $replace = " LIKE '%add%'";
  261. break;
  262. case '!=' :
  263. case '<>' :
  264. $replace = " NOT LIKE '%add%'";
  265. break;
  266. default:
  267. $replace = '';
  268. }
  269. break;
  270. case 'r' :
  271. switch ($match[2]) {
  272. case '=' :
  273. $replace = " LIKE '%view%' OR action LIKE '%report%'";
  274. break;
  275. case '!=' :
  276. case '<>' :
  277. $replace = " NOT LIKE '%view%' AND action NOT LIKE '%report%'";
  278. break;
  279. default:
  280. $replace = '';
  281. }
  282. break;
  283. case 'u' :
  284. switch ($match[2]) {
  285. case '=' :
  286. $replace = " LIKE '%update%'";
  287. break;
  288. case '!=' :
  289. case '<>' :
  290. $replace = " NOT LIKE '%update%'";
  291. break;
  292. default:
  293. $replace = '';
  294. }
  295. break;
  296. case 'd' :
  297. switch ($match[2]) {
  298. case '=' :
  299. $replace = " LIKE '%delete%'";
  300. break;
  301. case '!=' :
  302. case '<>' :
  303. $replace = " NOT LIKE '%delete%'";
  304. break;
  305. default:
  306. $replace = '';
  307. }
  308. break;
  309. default :
  310. $replace = '';
  311. }
  312. $return .= $replace;
  313. }
  314. return $return;
  315. }
  316. }