<?php
// Generates a page of sites that have not been accessed in 6 months based on mdl_log along with statistics
// - Elvedin Trnjanin

require_once("config.php");
print 
"<html>";
print 
"<body>";

print 
"<br /> <br />";
$numofrows get_record_sql("select count(*) as count from {$CFG->prefix}log");
$starttime time();
$courses get_records_sql("select course, datediff(curdate(),from_unixtime(max(time))) as inactivity from {$CFG->prefix}log where course<>0 group by course order by inactivity desc;"); // this neat trick is from some admin plugin, sorry forgot the name
// the query returns inactivity in days

$coursecount 0// or use count($courses)
$inactivecoursecount 0;

foreach (
$courses as $course) {
        @
ini_set("max_execution_time","1000"); // might take a while if moodle is really active: about 8 million records took 12 seconds to parse and 8 seconds to sort
        
if ($course->inactivity 182) { // 182 days ~ 6 months
                
$coursecount++;
                continue;
        }
        echo 
"Course $course->course has been inactive for $course->inactivity days <br />";
        
$coursecount++; $inactivecoursecount++;
        echo 
"<a href=\"$CFG->wwwroot/course/view.php?id=$course->course\">$CFG->wwwroot/course/view.php?id=$course->course</a> <br />";
        
$instructors get_records_sql("select userid from {$CFG->prefix}role_assignments where roleid=3 and contextid=(select id from {$CFG->prefix}context where contextlevel=50 and instanceid=$course->course)"); // using the course id, get the userid from mdl_context to be used in mdl_role+assignments, roleid 3 is instructor
        
foreach ($instructors as $instructor) {
                
$userdetails get_records_sql("select firstname, lastname, email from {$CFG->prefix}user where id=$instructor->userid");
                foreach (
$userdetails as $userdetail) { // a course might have multiple instructors
                
echo "Instructor: $userdetail->lastname, $userdetail->firstname E-mail: $userdetail->email <br /> ";
                }
        }
        echo 
"<br />";
}
$totaltime time() - $starttime;

echo 
"<br />";
echo 
"<br /> $inactivecoursecount courses inactive out of $coursecount courses total<br />";
echo 
"Parsing through $numofrows->count log records took $totaltime seconds";
print 
"</body>";
print 
"</html>";
?>