/**
 * Obtains a recordset containing information about all scheduled PHP
 * report jobs for a particular report (to be used only from the scheduling UI since
 * this depends on the current user)
 *
 * @param   string     $report_shortname  Shortname of the report whose jobs we are looking up
 * @param   string     $fields            String containing the comma-separated list of fiedls
 *                                        to select, or NULL to use the default fields
 *
 * @return  recordset                     A recordset referring to the related records
 */
function block_php_report_get_report_jobs_recordset($report_shortname, $fields = NULL)
{
    global $CFG, $USER;
    //need this concatenation to connect ELIS and PHP scheduling info
    $concat = block_php_report_get_taskname_from_column('schedule.id');
    if ($fields === NULL) {
        //default set of database fields to select
        $fields = "user.firstname,\n                   user.lastname,\n                   task.lastruntime,\n                   task.nextruntime,\n                   schedule.config,\n                   schedule.id AS scheduleid";
    }
    //main query, involving ELIS and PHP schedling info
    $sql = "SELECT {$fields}\n            FROM\n            {$CFG->prefix}elis_scheduled_tasks task\n            JOIN {$CFG->prefix}php_report_schedule schedule\n              ON task.taskname = {$concat}\n            JOIN {$CFG->prefix}user user\n              ON schedule.userid = user.id\n            WHERE schedule.report = '{$report_shortname}'";
    if (!has_capability('block/php_report:manageschedules', get_context_instance(CONTEXT_SYSTEM))) {
        //user does not have the necessary capability for viewing all scheduled instances,
        //so limit to their own
        $sql .= ' AND user.id = ' . $USER->id;
    }
    return get_recordset_sql($sql);
}
/**
 * Removes orphaned PHP report schedule records (i.e. PHP report schedule records
 * that have no associated ELIS scheduled task)
 */
function php_report_schedule_delete_unmatching_records()
{
    global $CFG;
    //need this concatenation to connect ELIS and PHP scheduling info
    $concat = block_php_report_get_taskname_from_column('php_sched.id');
    //query to find the appropriate PHP report task ids
    $sql = "SELECT php_sched.id as id\n            FROM {$CFG->prefix}php_report_schedule php_sched\n            LEFT JOIN {$CFG->prefix}elis_scheduled_tasks elis_sched\n                   ON (elis_sched.taskname={$concat})\n                WHERE elis_sched.taskname IS NULL";
    //iterate and delete
    $rs = get_recordset_sql($sql);
    while ($res = rs_fetch_next_record($rs)) {
        delete_records('php_report_schedule', 'id', $res->id);
    }
}