Example #1
0
 function rm($name = '')
 {
     $clear = false;
     if ($name) {
         $this->cur_query = "cache->rm('{$name}')";
         $this->debug('start');
         $filename = $this->dir . clean_filename($this->prefix . $name) . '.php';
         if (file_exists($filename)) {
             $clear = (bool) unlink($filename);
         }
         $this->debug('stop');
         $this->cur_query = null;
         $this->num_queries++;
     } else {
         if (is_dir($this->dir)) {
             if ($dh = opendir($this->dir)) {
                 while (($file = readdir($dh)) !== false) {
                     if ($file != "." && $file != "..") {
                         $filename = $this->dir . $file;
                         unlink($filename);
                         $clear = true;
                     }
                 }
                 closedir($dh);
             }
         }
     }
     return $clear;
 }
Example #2
0
 public function print_grades()
 {
     global $CFG;
     $export_tracking = $this->track_exports();
     $strgrades = get_string('grades');
     switch ($this->separator) {
         case 'comma':
             $separator = ",";
             break;
         case 'tab':
         default:
             $separator = "\t";
     }
     /// Print header to force download
     if (strpos($CFG->wwwroot, 'https://') === 0) {
         //https sites - watch out for IE! KB812935 and KB316431
         @header('Cache-Control: max-age=10');
         @header('Expires: ' . gmdate('D, d M Y H:i:s', 0) . ' GMT');
         @header('Pragma: ');
     } else {
         //normal http - prevent caching at all cost
         @header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
         @header('Expires: ' . gmdate('D, d M Y H:i:s', 0) . ' GMT');
         @header('Pragma: no-cache');
     }
     header("Content-Type: application/download\n");
     $downloadfilename = clean_filename("{$this->course->shortname} {$strgrades}");
     header("Content-Disposition: attachment; filename=\"{$downloadfilename}.txt\"");
     /// Print names of all the fields
     echo get_string("firstname") . $separator . get_string("lastname") . $separator . get_string("idnumber") . $separator . get_string("institution") . $separator . get_string("department") . $separator . get_string("email");
     foreach ($this->columns as $grade_item) {
         echo $separator . $this->format_column_name($grade_item);
         /// add a feedback column
         if ($this->export_feedback) {
             echo $separator . $this->format_column_name($grade_item, true);
         }
     }
     echo "\n";
     /// Print all the lines of data.
     $geub = new grade_export_update_buffer();
     $gui = new graded_users_iterator($this->course, $this->columns, $this->groupid);
     $gui->init();
     while ($userdata = $gui->next_user()) {
         $user = $userdata->user;
         echo $user->firstname . $separator . $user->lastname . $separator . $user->idnumber . $separator . $user->institution . $separator . $user->department . $separator . $user->email;
         foreach ($userdata->grades as $itemid => $grade) {
             if ($export_tracking) {
                 $status = $geub->track($grade);
             }
             echo $separator . $this->format_grade($grade);
             if ($this->export_feedback) {
                 echo $separator . $this->format_feedback($userdata->feedbacks[$itemid]);
             }
         }
         echo "\n";
     }
     $gui->close();
     $geub->close();
     exit;
 }
Example #3
0
 public function print_grades()
 {
     global $CFG;
     $export_tracking = $this->track_exports();
     $strgrades = get_string('grades');
     $profilefields = grade_helper::get_user_profile_fields($this->course->id, $this->usercustomfields);
     $shortname = format_string($this->course->shortname, true, array('context' => context_course::instance($this->course->id)));
     $downloadfilename = clean_filename("{$shortname} {$strgrades}");
     $csvexport = new csv_export_writer($this->separator);
     $csvexport->set_filename($downloadfilename);
     // Print names of all the fields
     $exporttitle = array();
     foreach ($profilefields as $field) {
         $exporttitle[] = $field->fullname;
     }
     if (!$this->onlyactive) {
         $exporttitle[] = get_string("suspended");
     }
     // Add a feedback column.
     foreach ($this->columns as $grade_item) {
         $exporttitle[] = $this->format_column_name($grade_item);
         if ($this->export_feedback) {
             $exporttitle[] = $this->format_column_name($grade_item, true);
         }
     }
     $csvexport->add_data($exporttitle);
     // Print all the lines of data.
     $geub = new grade_export_update_buffer();
     $gui = new graded_users_iterator($this->course, $this->columns, $this->groupid);
     $gui->require_active_enrolment($this->onlyactive);
     $gui->allow_user_custom_fields($this->usercustomfields);
     $gui->init();
     while ($userdata = $gui->next_user()) {
         $exportdata = array();
         $user = $userdata->user;
         foreach ($profilefields as $field) {
             $fieldvalue = grade_helper::get_user_field_value($user, $field);
             $exportdata[] = $fieldvalue;
         }
         if (!$this->onlyactive) {
             $issuspended = $user->suspendedenrolment ? get_string('yes') : '';
             $exportdata[] = $issuspended;
         }
         foreach ($userdata->grades as $itemid => $grade) {
             if ($export_tracking) {
                 $status = $geub->track($grade);
             }
             $exportdata[] = $this->format_grade($grade);
             if ($this->export_feedback) {
                 $exportdata[] = $this->format_feedback($userdata->feedbacks[$itemid]);
             }
         }
         $csvexport->add_data($exportdata);
     }
     $gui->close();
     $geub->close();
     $csvexport->download_file();
     exit;
 }
Example #4
0
function msg_die($msg)
{
    if (DBG_LOG) {
        dbg_log(' ', '!die-' . clean_filename($msg));
    }
    $output = bencode(array('min interval' => (int) 1800, 'failure reason' => (string) $msg, 'warning message' => (string) $msg));
    die($output);
}
 /**
  * Processes the message (sends by email).
  * @param object $eventdata the event data submitted by the message sender plus $eventdata->savedmessageid
  */
 function send_message($eventdata)
 {
     global $CFG;
     // Ignore $CFG->noemailever here because we want to test this code,
     // the message sending fails later in email_to_user().
     // skip any messaging suspended and deleted users
     if ($eventdata->userto->auth === 'nologin' or $eventdata->userto->suspended or $eventdata->userto->deleted) {
         return true;
     }
     //the user the email is going to
     $recipient = null;
     //check if the recipient has a different email address specified in their messaging preferences Vs their user profile
     $emailmessagingpreference = get_user_preferences('message_processor_email_email', null, $eventdata->userto);
     $emailmessagingpreference = clean_param($emailmessagingpreference, PARAM_EMAIL);
     // If the recipient has set an email address in their preferences use that instead of the one in their profile
     // but only if overriding the notification email address is allowed
     if (!empty($emailmessagingpreference) && !empty($CFG->messagingallowemailoverride)) {
         //clone to avoid altering the actual user object
         $recipient = clone $eventdata->userto;
         $recipient->email = $emailmessagingpreference;
     } else {
         $recipient = $eventdata->userto;
     }
     // Check if we have attachments to send.
     $attachment = '';
     $attachname = '';
     if (!empty($CFG->allowattachments) && !empty($eventdata->attachment)) {
         if (empty($eventdata->attachname)) {
             // Attachment needs a file name.
             debugging('Attachments should have a file name. No attachments have been sent.', DEBUG_DEVELOPER);
         } else {
             if (!$eventdata->attachment instanceof stored_file) {
                 // Attachment should be of a type stored_file.
                 debugging('Attachments should be of type stored_file. No attachments have been sent.', DEBUG_DEVELOPER);
             } else {
                 // Copy attachment file to a temporary directory and get the file path.
                 $attachment = $eventdata->attachment->copy_content_to_temp();
                 // Get attachment file name.
                 $attachname = clean_filename($eventdata->attachname);
             }
         }
     }
     // Configure mail replies - this is used for incoming mail replies.
     $replyto = '';
     $replytoname = '';
     if (isset($eventdata->replyto)) {
         $replyto = $eventdata->replyto;
         if (isset($eventdata->replytoname)) {
             $replytoname = $eventdata->replytoname;
         }
     }
     $result = email_to_user($recipient, $eventdata->userfrom, $eventdata->subject, $eventdata->fullmessage, $eventdata->fullmessagehtml, $attachment, $attachname, true, $replyto, $replytoname);
     // Remove an attachment file if any.
     if (!empty($attachment) && file_exists($attachment)) {
         unlink($attachment);
     }
     return $result;
 }
Example #6
0
function error_exit($msg = '')
{
    if (DBG_LOG) {
        dbg_log(' ', '!err-' . clean_filename($msg));
    }
    silent_exit();
    echo bencode(array('failure reason' => str_compact($msg)));
    tracker_exit();
}
Example #7
0
 function report_download_csv($fields, $data, $reportname = 'reportincsv')
 {
     $filename = clean_filename($reportname);
     $csvexport = new csv_export_writer();
     $csvexport->set_filename($filename);
     $csvexport->add_data($fields);
     foreach ($data as $eachrow) {
         $csvexport->add_data($eachrow);
     }
     $csvexport->download_file();
 }
Example #8
0
function user_download_csv($fields) {
    global $CFG;
    require_once($CFG->libdir . '/csvlib.class.php');
    $filename = clean_filename(get_string('course', 'local_cobaltcourses'));
    $csvexport = new csv_export_writer();
    $csvexport->set_filename($filename);
    $csvexport->add_data($fields);
    $userprofiledata = array();
    $csvexport->add_data($userprofiledata);
    $csvexport->download_file();
    die;
}
Example #9
0
function user_download_csv($fields) {
    global $CFG;
    require_once($CFG->libdir . '/csvlib.class.php');
    $filename = clean_filename('Departments');
    $csvexport = new csv_export_writer();
    $csvexport->set_filename($filename);
    $csvexport->add_data($fields);
    $userprofiledata = array();
    $csvexport->add_data($userprofiledata);
    $csvexport->download_file();
    die;
}
Example #10
0
function user_download_csv($fields) {
    global $CFG;
    require_once($CFG->libdir . '/csvlib.class.php');
    $filename = clean_filename('Users sample');
    $csvexport = new csv_export_writer();
    $csvexport->set_filename($filename);
    $csvexport->add_data($fields);
    $userprofiledata = array('lp_shortname','testuser');
    $csvexport->add_data($userprofiledata);
    $csvexport->download_file();
    die;
}
Example #11
0
function user_download_xls($fields) {

    global $CFG, $DB;
    require_once("$CFG->libdir/excellib.class.php");
    $filename = clean_filename(get_string('course', 'local_cobaltcourses') . '.xls');
    $workbook = new MoodleExcelWorkbook('-');
    $workbook->send($filename);
    $worksheet = array();
    $worksheet[0] = $workbook->add_worksheet('');
    $col = 0;
    foreach ($fields as $fieldname) {
        $worksheet[0]->write(0, $col, $fieldname);
        $col++;
    }


    $hierarchy = new hierarchy();
    $schoollist = $hierarchy->get_assignedschools();
    if (is_siteadmin()) {
        $schoollist = $hierarchy->get_school_items();
    }

    $sheetrow = 1;
    foreach ($schoollist as $school) {
        $courses = $DB->get_records('local_cobaltcourses', array('schoolid' => $school->id));
        foreach ($courses as $course) {
            $post = new stdclass();

            $post->fullname = $course->fullname;
            $post->shortname = $course->shortname;
            $departmentname = $DB->get_field('local_department', 'fullname', array('id' => $course->departmentid));
            $post->courselibraryname = $departmentname;
            $schoolname = $DB->get_field('local_school', 'fullname', array('id' => $course->schoolid));
            $post->organizationname = $schoolname;
            $post->summary = $course->summary;
            $post->coursetype = ($course->coursetype == 0) ? 'General' : 'Elective';
            $post->credithours = $course->credithours;
            $post->coursecost = $course->coursecost;
            $col = 0;
            foreach ($fields as $fieldname) {
                $worksheet[0]->write($sheetrow, $col, $post->$fieldname);
                $col++;
            }
            $sheetrow++;
        }
    }

    $workbook->close();
    die;
}
Example #12
0
function local_mail_downloadall($message) {
    $attachments = local_mail_attachments($message);
    if (count($attachments) > 1) {
        foreach ($attachments as $attach) {
            $filename = clean_filename($attach->get_filename());
            $filesforzipping[$filename] = $attach;
        }
        $filename = clean_filename(fullname($message->sender()) . '-' .
                                   $message->subject() . '.zip');
        if ($zipfile = pack_files($filesforzipping)) {
            send_temp_file($zipfile, $filename);
        }
    }
}
function moodle_binary_get_path($id, $meta, $course, $wiki, $userid, $groupid)
{
    global $CFG;
    $entry = wiki_get_entry($wiki, $course, $userid, $groupid);
    if (!$entry) {
        print_error('cannotgetentry', 'wiki');
    }
    $dir = make_upload_directory("{$course->id}/{$CFG->moddata}/wiki/{$wiki->id}/{$entry->id}/" . $meta["section"]);
    if (substr($id, 0, strlen(EWIKI_IDF_INTERNAL)) != EWIKI_IDF_INTERNAL) {
        print_error('cannotstartwith', 'wiki', '', EWIKI_IDF_INTERNAL . substr($id, 0, strlen(EWIKI_IDF_INTERNAL)));
    }
    $id = substr($id, strlen(EWIKI_IDF_INTERNAL));
    $id = clean_filename($id);
    return "{$dir}/{$id}";
}
Example #14
0
 function store($title, $var)
 {
     $this->cur_query = "cache->set('{$title}')";
     $this->debug('start');
     $this->data[$title] = $var;
     $filename = $this->dir . clean_filename($this->prefix . $title) . '.php';
     $filecache = "<?php\n";
     $filecache .= "if (!defined('FT_ROOT')) die(basename(__FILE__));\n";
     $filecache .= '$filecache = ' . var_export($var, true) . ";\n";
     $filecache .= '?>';
     $this->debug('stop');
     $this->cur_query = null;
     $this->num_queries++;
     return (bool) file_write($filecache, $filename, false, true, true);
 }
Example #15
0
function user_download_xls($fields) {

    global $CFG, $DB;
    require_once("$CFG->libdir/excellib.class.php");
    $filename = clean_filename(get_string('department', 'local_departments') . '.xls');
    $workbook = new MoodleExcelWorkbook('-');
    $workbook->send($filename);
    $worksheet = array();
    $worksheet[0] = $workbook->add_worksheet('');
    $col = 0;
    foreach ($fields as $fieldname) {
        $worksheet[0]->write(0, $col, $fieldname);
        $col++;
    }

    $hierarchy = new hierarchy();
    /*   Bug report #260 
     * Edited by hemalatha c arun <*****@*****.**>
     * resolved- If loggedin user is admin, downloading all the department   
     */
    if (is_siteadmin()) {
        $sql = "SELECT distinct(s.id),s.* FROM {local_school} s ORDER BY s.sortorder";
        $schoollist = $DB->get_records_sql($sql);
    } else
        $schoollist = $hierarchy->get_assignedschools();

    $sheetrow = 1;
    foreach ($schoollist as $school) {
        $departments = $DB->get_records('local_department', array('schoolid' => $school->id));
        foreach ($departments as $department) {
            $post = new stdclass();
            $post->shortname = $department->shortname;
            $post->fullname = $department->fullname;
            $schoolname = $DB->get_field('local_school', 'fullname', array('id' => $department->schoolid));
            $post->schoolname = $schoolname;
            $post->summary = $department->description;
            $col = 0;
            foreach ($fields as $fieldname) {
                $worksheet[0]->write($sheetrow, $col, $post->$fieldname);
                $col++;
            }
            $sheetrow++;
        }
    }
    $workbook->close();
    die;
}
Example #16
0
 /**
  * Make the directory for the file and open the file pointer
  *
  * @param string $name The preferred file name (no extension)
  * @param string $dir The directory to store the file in (temp by default)
  * @return void
  */
 public function init($name, $dir = NULL)
 {
     global $CFG;
     require_once $CFG->libdir . '/filelib.php';
     if (is_null($dir)) {
         $dir = $CFG->dataroot . '/temp';
     }
     check_dir_exists($dir, true, true);
     // Generate file path
     $name = clean_filename($name);
     $name = trim($name, '_');
     $this->file = "{$dir}/{$name}." . $this->get_extension();
     // Make sure it doesn't exist
     $this->cleanup();
     // Open for writing
     $this->fp = fopen($this->file, 'w');
 }
Example #17
0
function user_download_xls($fields) {
    $hier = new hierarchy();
    $schools = $hier->get_assignedschools();

    global $CFG, $DB;
    require_once("$CFG->libdir/excellib.class.php");
    $filename = clean_filename('Users.xls');
    $workbook = new MoodleExcelWorkbook('-');
    $workbook->send($filename);
    $worksheet = array();
    $worksheet[0] = $workbook->add_worksheet('');
    $col = 0;
    foreach ($fields as $fieldname) {
        $worksheet[0]->write(0, $col, $fieldname);
        $col++;
    }

    $sheetrow = 1;
    $myuser = users::getInstance();

    $users = $DB->get_records_sql("SELECT u.id, u.username, u.email, u.firstname, u.lastname, u.city, u.country,
                                            u.lastaccess, u.confirmed, u.mnethostid, u.suspended FROM {user} u, {local_users} lu
                                            WHERE lu.userid = u.id ");

    foreach ($users as $user) {
        $rid = $myuser->get_rolename($user->id);
        $post = new stdclass();
        $post->firstname = $user->firstname;
        $post->lastname = $user->lastname;
        $post->email = $user->email;

        $post->schoolname = $myuser->get_schoolnames($user);
        $post->roleid = $myuser->get_rolename($user->id);
        $col = 0;
        foreach ($fields as $fieldname) {
            $worksheet[0]->write($sheetrow, $col, $post->$fieldname);
            $col++;
        }
        $sheetrow++;
    }

    $workbook->close();
    die;
}
/**
* Create default export filename
*
* @return string   default export filename
* @param object $course
* @param object $referentiel
* @param string $info
*/
function referentiel_default_export_filename($course, $referentiel, $info = "")
{
    //Take off some characters in the filename !!
    $takeoff = array(" ", ":", "/", "\\", "|");
    $core_text = new core_text();
    $export_word = str_replace($takeoff, "_", $core_text::strtolower(get_string("exportfilename", "referentiel")));
    //If non-translated, use "export"
    if (substr($export_word, 0, 1) == "[") {
        $export_word = "export";
    }
    //Calculate the date format string
    $export_date_format = str_replace(" ", "_", get_string("exportnameformat", "referentiel"));
    //If non-translated, use "%Y%m%d-%H%M"
    if (substr($export_date_format, 0, 1) == "[") {
        $export_date_format = "%Y%m%d-%H%M";
    }
    //Calculate the shortname
    $export_shortname = clean_filename($course->shortname);
    if (empty($export_shortname) or $export_shortname == '_') {
        $export_shortname = $course->id;
    }
    //Calculate the instance name
    $export_instancename = clean_filename(trim($referentiel->name));
    //Calculate the final export filename
    //The export word
    $export_name = $export_word . "-";
    //The shortname
    $export_name .= referentiel_purge_accents($export_shortname) . "-";
    //The instance name
    $export_name .= referentiel_purge_accents($export_instancename) . "-";
    if ($info) {
        $export_name .= referentiel_purge_accents(clean_filename($info)) . "-";
    }
    // DEBUG
    //echo "<br />DEBUG :: import_export_l_b.php :: 99 <br />$export_name<br />$export_date_format\n";
    //The date format
    // $export_name .= date("Ymd_Hgs");
    $export_name .= userdate(time(), $export_date_format, 99, false);
    //The extension - no extension, supplied by format
    // $export_name .= ".txt";
    //echo "<br />APRES FORMATAGE / $export_name\n";
    //exit;
    return $export_name;
}
Example #19
0
/** Configurable Reports
 * A Moodle block for creating customizable reports
 * @package blocks
 * @author: Juan leyva <http://www.twitter.com/jleyvadelgado>
 * @date: 2009
 */
function export_report($report) {
    global $DB, $CFG;
    require_once($CFG->dirroot . '/lib/excellib.class.php');

    $table = $report->table;
    $matrix = array();
    $filename = 'report_' . (time()) . '.xls';

    if (!empty($table->head)) {
        $countcols = count($table->head);
        $keys = array_keys($table->head);
        $lastkey = end($keys);
        foreach ($table->head as $key => $heading) {
            $matrix[0][$key] = str_replace("\n", ' ', htmlspecialchars_decode(strip_tags(nl2br($heading))));
        }
    }

    if (!empty($table->data)) {
        foreach ($table->data as $rkey => $row) {
            foreach ($row as $key => $item) {
                $matrix[$rkey + 1][$key] = str_replace("\n", ' ', htmlspecialchars_decode(strip_tags(nl2br($item))));
            }
        }
    }

    $downloadfilename = clean_filename($filename);
    /// Creating a workbook
    $workbook = new MoodleExcelWorkbook("-");
    /// Sending HTTP headers
    $workbook->send($downloadfilename);
    /// Adding the worksheet
    $myxls = $workbook->add_worksheet($filename);

    foreach ($matrix as $ri => $col) {
        foreach ($col as $ci => $cv) {
            $myxls->write_string($ri, $ci, $cv);
        }
    }

    $workbook->close();
    exit;
}
Example #20
0
function user_download_xls($fields) {
    global $CFG, $DB;
    require_once("$CFG->libdir/excellib.class.php");
    $filename = clean_filename(get_string('program', 'local_programs') . '.xls');
    $workbook = new MoodleExcelWorkbook('-');
    $workbook->send($filename);
    $worksheet = array();
    $worksheet[0] = $workbook->add_worksheet('');
    $col = 0;
    foreach ($fields as $fieldname) {
        $worksheet[0]->write(0, $col, $fieldname);
        $col++;
    }

    $hierarchy = new hierarchy();
    $schoollist = $hierarchy->get_assignedschools();
    $sheetrow = 1;
    foreach ($schoollist as $school) {
        $programs = $DB->get_records('local_program', array('schoolid' => $school->id));
        foreach ($programs as $program) {
            $post = new stdclass();
            $post->shortname = $program->shortname;
            $post->fullname = $program->fullname;
            $departmentname = $DB->get_field('local_department', 'fullname', array('id' => $program->departmentid));
            $post->departmentname = $departmentname;
            $schoolname = $DB->get_field('local_school', 'fullname', array('id' => $program->schoolid));
            $post->schoolname = $schoolname;
            $post->summary = $program->description;
            $post->type = ($program->type == 0) ? 'UnderGraduate' : 'PostGraduate';
            $post->duration = $program->duration;
            $col = 0;
            foreach ($fields as $fieldname) {
                $worksheet[0]->write($sheetrow, $col, $post->$fieldname);
                $col++;
            }
            $sheetrow++;
        }
    }
    $workbook->close();
    die;
}
Example #21
0
function send_file_to_browser($attachment, $upload_dir)
{
    global $bb_cfg, $lang, $userdata;
    $filename = $upload_dir == '' ? $attachment['physical_filename'] : $upload_dir . '/' . $attachment['physical_filename'];
    $gotit = false;
    if (@(!file_exists(@amod_realpath($filename)))) {
        bb_die($lang['ERROR_NO_ATTACHMENT'] . "<br /><br />" . $filename . "<br /><br />" . $lang['TOR_NOT_FOUND']);
    } else {
        $gotit = true;
    }
    // Correct the mime type - we force application/octet-stream for all files, except images
    // Please do not change this, it is a security precaution
    if (!strstr($attachment['mimetype'], 'image')) {
        $attachment['mimetype'] = 'application/octet-stream';
    }
    //bt
    if (!(isset($_GET['original']) && !IS_USER)) {
        include INC_DIR . 'functions_torrent.php';
        send_torrent_with_passkey($filename);
    }
    // Now the tricky part... let's dance
    header('Pragma: public');
    $real_filename = clean_filename(basename($attachment['real_filename']));
    $mimetype = $attachment['mimetype'] . ';';
    $charset = "charset={$bb_cfg['lang'][$userdata['user_lang']]['encoding']};";
    // Send out the Headers
    header("Content-Type: {$mimetype} {$charset} name=\"{$real_filename}\"");
    header("Content-Disposition: inline; filename=\"{$real_filename}\"");
    unset($real_filename);
    // Now send the File Contents to the Browser
    if ($gotit) {
        $size = @filesize($filename);
        if ($size) {
            header("Content-length: {$size}");
        }
        readfile($filename);
    } else {
        bb_die($lang['ERROR_NO_ATTACHMENT'] . "<br /><br />" . $filename . "<br /><br />" . $lang['TOR_NOT_FOUND']);
    }
    exit;
}
Example #22
0
/**
* Create default export filename
*
* @return string   default export filename
* @param object $course
* @param object $referentiel
* @param string $info
*/
function referentiel_default_print_filename($course, $referentiel, $info = "")
{
    //Take off some characters in the filename !!
    $takeoff = array(" ", ":", "/", "\\", "|");
    $core_text = new core_text();
    $export_word = str_replace($takeoff, "_", $core_text::strtolower(get_string("exportfilename", "referentiel")));
    //If non-translated, use "export"
    if (substr($export_word, 0, 1) == "[") {
        $export_word = "export";
    }
    //Calculate the date format string
    $export_date_format = str_replace(" ", "_", get_string("exportnameformat", "referentiel"));
    //If non-translated, use "%Y%m%d-%H%M"
    if (substr($export_date_format, 0, 1) == "[") {
        $export_date_format = "%%Y%%m%%d-%%H%%M";
    }
    //Calculate the shortname
    $export_shortname = clean_filename($course->shortname);
    if (empty($export_shortname) or $export_shortname == '_') {
        $export_shortname = $course->id;
    }
    //Calculate the instance name
    $export_instancename = clean_filename($referentiel->name);
    //Calculate the final export filename
    //The export word
    $export_name = 'print_' . $export_word . "-";
    //The shortname
    $export_name .= $core_text::strtolower($export_shortname) . "-";
    //The instance name
    $export_name .= $core_text::strtolower($export_instancename) . "-";
    if ($info) {
        $export_name .= $core_text::strtolower($info) . "-";
    }
    //The date format
    $export_name .= userdate(time(), $export_date_format, 99, false);
    //The extension - no extension, supplied by format
    // $export_name .= ".txt";
    return $export_name;
}
 /**
  * To be implemented by child classes
  */
 public function print_grades()
 {
     global $CFG;
     require_once $CFG->dirroot . '/lib/excellib.class.php';
     $export_tracking = $this->track_exports();
     $strgrades = get_string('grades');
     // Calculate file name
     $shortname = format_string($this->course->shortname, true, array('context' => context_course::instance($this->course->id)));
     $downloadfilename = clean_filename("{$shortname} {$strgrades}.xls");
     // Creating a workbook
     $workbook = new MoodleExcelWorkbook("-");
     // Sending HTTP headers
     $workbook->send($downloadfilename);
     // Adding the worksheet
     $myxls = $workbook->add_worksheet($strgrades);
     // Print names of all the fields
     $profilefields = grade_helper::get_user_profile_fields($this->course->id, $this->usercustomfields);
     foreach ($profilefields as $id => $field) {
         $myxls->write_string(0, $id, $field->fullname);
     }
     $pos = count($profilefields);
     if (!$this->onlyactive) {
         $myxls->write_string(0, $pos++, get_string("suspended"));
     }
     foreach ($this->columns as $grade_item) {
         $myxls->write_string(0, $pos++, $this->format_column_name($grade_item));
         // Add a column_feedback column
         if ($this->export_feedback) {
             $myxls->write_string(0, $pos++, $this->format_column_name($grade_item, true));
         }
     }
     // Print all the lines of data.
     $i = 0;
     $geub = new grade_export_update_buffer();
     $gui = new graded_users_iterator($this->course, $this->columns, $this->groupid);
     $gui->require_active_enrolment($this->onlyactive);
     $gui->allow_user_custom_fields($this->usercustomfields);
     $gui->init();
     while ($userdata = $gui->next_user()) {
         $i++;
         $user = $userdata->user;
         foreach ($profilefields as $id => $field) {
             $fieldvalue = grade_helper::get_user_field_value($user, $field);
             $myxls->write_string($i, $id, $fieldvalue);
         }
         $j = count($profilefields);
         if (!$this->onlyactive) {
             $issuspended = $user->suspendedenrolment ? get_string('yes') : '';
             $myxls->write_string($i, $j++, $issuspended);
         }
         foreach ($userdata->grades as $itemid => $grade) {
             if ($export_tracking) {
                 $status = $geub->track($grade);
             }
             $gradestr = $this->format_grade($grade);
             if (is_numeric($gradestr)) {
                 $myxls->write_number($i, $j++, $gradestr);
             } else {
                 $myxls->write_string($i, $j++, $gradestr);
             }
             // writing feedback if requested
             if ($this->export_feedback) {
                 $myxls->write_string($i, $j++, $this->format_feedback($userdata->feedbacks[$itemid]));
             }
         }
     }
     $gui->close();
     $geub->close();
     /// Close the workbook
     $workbook->close();
     exit;
 }
Example #24
0
    }
}
// Rename any files with changed name
if (isset($_POST['renamefile'])) {
    foreach ($_POST['renamefile'] as $namethis => $newname) {
        if ($_POST['actionfile'][$namethis] != $newname . $_POST['renameext'][$namethis]) {
            $namethisfilefrom = $tinybrowser['docroot'] . $editpath . $_POST['actionfile'][$namethis];
            $namethisfileto = $tinybrowser['docroot'] . $editpath . clean_filename($newname . $_POST['renameext'][$namethis]);
            if (file_exists($namethisfilefrom) && rename($namethisfilefrom, $namethisfileto)) {
                $renameqty++;
            } else {
                $errorqty++;
            }
            if ($typenow == 'image') {
                $namethisthumbfrom = $tinybrowser['docroot'] . $editpath . "_thumbs/_" . $_POST['actionfile'][$namethis];
                $namethisthumbto = $tinybrowser['docroot'] . $editpath . "_thumbs/_" . clean_filename($newname . $_POST['renameext'][$namethis]);
                if (file_exists($namethisthumbfrom)) {
                    rename($namethisthumbfrom, $namethisthumbto);
                }
            }
        }
    }
}
// Resize any files with new size
if (isset($_POST['resizefile'])) {
    foreach ($_POST['resizefile'] as $sizethis => $newsize) {
        $newsize = intval($newsize);
        if ($newsize) {
            // detect silly sizes
            if ($newsize > $tinybrowser['thumbsize']) {
                // do image resize
Example #25
0
// Apache log integration. In apache conf file one can use ${MOODULEUSER}n in
// LogFormat to get the current logged in username in moodle.
if ($USER && function_exists('apache_note') && !empty($CFG->apacheloguser) && isset($USER->username)) {
    $apachelog_userid = $USER->id;
    $apachelog_username = clean_filename($USER->username);
    $apachelog_name = '';
    if (isset($USER->firstname)) {
        // We can assume both will be set
        // - even if to empty.
        $apachelog_name = clean_filename($USER->firstname . " " . $USER->lastname);
    }
    if (session_is_loggedinas()) {
        $realuser = session_get_realuser();
        $apachelog_username = clean_filename($realuser->username . " as " . $apachelog_username);
        $apachelog_name = clean_filename($realuser->firstname . " " . $realuser->lastname . " as " . $apachelog_name);
        $apachelog_userid = clean_filename($realuser->id . " as " . $apachelog_userid);
    }
    switch ($CFG->apacheloguser) {
        case 3:
            $logname = $apachelog_username;
            break;
        case 2:
            $logname = $apachelog_name;
            break;
        case 1:
        default:
            $logname = $apachelog_userid;
            break;
    }
    apache_note('MOODLEUSER', $logname);
}
Example #26
0
 /**
  * @todo Document this function
  */
 public function prepare_package()
 {
     $content = '';
     $lasttime = 0;
     $sessiongap = 5 * 60;
     // 5 minutes silence means a new session
     foreach ($this->messages as $message) {
         // We are walking FORWARDS through messages
         $m = clone $message;
         // grrrrrr - this causes the sha1 to change as chat_format_message changes what it's passed.
         $formatmessage = chat_format_message($m, null, $this->user);
         if (!isset($formatmessage->html)) {
             continue;
         }
         if (empty($lasttime) || $message->timestamp - $lasttime > $sessiongap) {
             $content .= '<hr />';
             $content .= userdate($message->timestamp);
         }
         $content .= $formatmessage->html;
         $lasttime = $message->timestamp;
     }
     $content = preg_replace('/\\<img[^>]*\\>/', '', $content);
     $this->exporter->write_new_file($content, clean_filename($this->cm->name . '-session.html'), false);
 }
Example #27
0
 /**
  * Gets all entries out of $_FILES and stores them locally in $files and then
  * checks each one against {@link get_max_upload_file_size()} and calls {@link cleanfilename()}
  * and scans them for viruses etc.
  * @uses $CFG
  * @uses $_FILES
  * @return boolean
  */
 function preprocess_files()
 {
     global $CFG, $OUTPUT;
     foreach ($_FILES as $name => $file) {
         $this->status = true;
         // only set it to true here so that we can check if this function has been called.
         if (empty($this->inputname) || $name == $this->inputname) {
             // if we have input name, only process if it matches.
             $file['originalname'] = $file['name'];
             // do this first for the log.
             $this->files[$name] = $file;
             // put it in first so we can get uploadlog out in print_upload_log.
             $this->files[$name]['uploadlog'] = '';
             // initialize error log
             $this->status = $this->validate_file($this->files[$name]);
             // default to only allowing empty on multiple uploads.
             if (!$this->status && ($this->files[$name]['error'] == 0 || $this->files[$name]['error'] == 4) && ($this->config->allownull || empty($this->inputname))) {
                 // this shouldn't cause everything to stop.. modules should be responsible for knowing which if any are compulsory.
                 continue;
             }
             if ($this->status && !empty($CFG->runclamonupload)) {
                 $this->status = clam_scan_moodle_file($this->files[$name], $this->course);
             }
             if (!$this->status) {
                 if (!$this->config->recoverifmultiple && count($this->files) > 1) {
                     $a = new stdClass();
                     $a->name = $this->files[$name]['originalname'];
                     $a->problem = $this->files[$name]['uploadlog'];
                     if (!$this->config->silent) {
                         echo $OUTPUT->notification(get_string('uploadfailednotrecovering', 'moodle', $a));
                     } else {
                         $this->notify .= '<br />' . get_string('uploadfailednotrecovering', 'moodle', $a);
                     }
                     $this->status = false;
                     return false;
                 } else {
                     if (count($this->files) == 1) {
                         if (!$this->config->silent and !$this->config->allownull) {
                             echo $OUTPUT->notification($this->files[$name]['uploadlog']);
                         } else {
                             $this->notify .= '<br />' . $this->files[$name]['uploadlog'];
                         }
                         $this->status = false;
                         return false;
                     }
                 }
             } else {
                 $newname = clean_filename($this->files[$name]['name']);
                 if ($newname != $this->files[$name]['name']) {
                     $a = new stdClass();
                     $a->oldname = $this->files[$name]['name'];
                     $a->newname = $newname;
                     $this->files[$name]['uploadlog'] .= get_string('uploadrenamedchars', 'moodle', $a);
                 }
                 $this->files[$name]['name'] = $newname;
                 $this->files[$name]['clear'] = true;
                 // ok to save.
                 $this->config->somethingtosave = true;
             }
         }
     }
     if (!is_array($_FILES) || count($_FILES) == 0) {
         return $this->config->allownull;
     }
     $this->status = true;
     return true;
     // if we've got this far it means that we're recovering so we want status to be ok.
 }
function ewiki_page_wiki_dump_send($exportbinaries = 0, $exportformats = 0, $withvirtualpages = 0, $exportdestinations = 0)
{
    global $ewiki_config, $wiki, $ewiki_plugins, $wiki_entry, $course, $CFG, $ewiki_t, $userid, $groupid;
    $filestozip = array();
    #-- disable protected email
    if (is_array($ewiki_plugins["link_url"])) {
        foreach ($ewiki_plugins["link_url"] as $key => $linkplugin) {
            if ($linkplugin == "ewiki_email_protect_link") {
                unset($ewiki_plugins["link_url"][$key]);
            }
        }
    }
    /// HTML-Export
    if ($exportformats == 1) {
        #-- if exportformats is html
        $HTML_TEMPLATE = '<html>
      <head>' . $ewiki_t["c"]["EWIKIDUMPCSS"] . '
      <title>$title</title>
      </head>
      <body bgcolor="#ffffff";>
      <div id="PageText">
      <h2>$title</h2>
      $content
      </div>
      </body>
      </html>';
        #-- reconfigure ewiki_format() to generate offline pages and files
        $html_ext = ".html";
        $ewiki_config["script"] = "%s{$html_ext}";
        $ewiki_config["script_binary"] = "%s";
    }
    // Export Virtual pages special
    $a_virtual = array_keys($ewiki_plugins["page"]);
    #-- get all pages / binary files
    $a_validpages = ewiki_valid_pages(1, $withvirtualpages);
    $a_pagelist = ewiki_sitemap_create($wiki_entry->pagename, $a_validpages, 100, 1);
    # Add linked binary files to pagelist
    foreach ($a_pagelist as $key => $value) {
        if (is_array($a_validpages[$value]["refs"])) {
            foreach ($a_validpages[$value]["refs"] as $refs) {
                if ($a_validpages[$refs]["type"] == "image" || $a_validpages[$refs]["type"] == "file") {
                    $a_pagelist[] = $refs;
                }
            }
        }
    }
    # Adjust links to binary files
    foreach ($a_pagelist as $key => $value) {
        if ($a_validpages[$value]["type"] == "image") {
            $a_images[] = urlencode($value);
            $a_rimages[] = urlencode(preg_replace(EWIKI_DUMP_FILENAME_REGEX, "", $value));
            unset($a_validpages[$value]);
        }
        if ($a_validpages[$value]["type"] == "file") {
            $a_images[] = urlencode($value);
            $a_rimages[] = clean_filename(substr($value, strlen(EWIKI_IDF_INTERNAL)));
            $a_images[] = $value;
            $a_rimages[] = clean_filename(substr($value, strlen(EWIKI_IDF_INTERNAL)));
            unset($a_validpages[$value]);
        }
    }
    # Remove binaries from a_validpages and add to a_pagelist
    foreach ($a_validpages as $key => $value) {
        if ($a_validpages[$key]["type"] == "image" || $a_validpages[$key]["type"] == "file") {
            $a_pagelist[] = $key;
            unset($a_validpages[$key]);
        }
    }
    #print "<pre>"; print_r($a_validpages); print "</pre>";
    #print "<hr /><pre>"; print_r($a_pagelist); print "</pre>";
    $a_sitemap = ewiki_sitemap_create($wiki_entry->pagename, $a_validpages, 99, 0);
    if ($a_pagelist) {
        #-- create new zip file
        #if($arctype == "ZIP"){
        #  $archivename=EWIKI_WIKIDUMP_ARCNAME."$rootid.zip";
        #  $archive = new ewiki_virtual_zip();
        #} elseif ($arctype == "TAR") {
        #  $archivename=EWIKI_WIKIDUMP_ARCNAME."$rootid.tar";
        #  $archive = new ewiki_virtual_tarball();
        #} else {
        #  die();
        #}
        /// Create/Set Directory
        $wname = clean_filename(strip_tags(format_string($wiki->name, true)));
        if ($exportdestinations) {
            if (wiki_is_teacher($wiki)) {
                $exportdir = $CFG->dataroot . "/" . $course->id . "/" . $exportdestinations;
            } else {
                add_to_log($course->id, "wiki", "hack", "", format_string($wiki->name, true) . ": Tried to export a wiki as non-teacher into {$exportdestinations}.");
                error("You are not a teacher !");
            }
        } else {
            $exportbasedir = tempnam("/tmp", "WIKIEXPORT");
            @unlink($exportbasedir);
            @mkdir($exportbasedir);
            /// maybe we need to check the name here...?
            $exportdir = $exportbasedir . "/" . $wname;
            @mkdir($exportdir);
            if (!is_dir($exportdir)) {
                error("Cannot create temporary directory {$exportdir} !");
            }
        }
        $a_pagelist = array_unique($a_pagelist);
        #-- convert all pages
        foreach ($a_pagelist as $pagename) {
            if (!in_array($pagename, $a_virtual)) {
                $id = $pagename;
                #-- not a virtual page
                $row = ewiki_database("GET", array("id" => $pagename));
                $content = "";
            } elseif ($withvirtualpages) {
                $id = $pagename;
                #-- is a virtual page
                $pf = $ewiki_plugins["page"][$id];
                $content = $pf($id, $content, "view");
                if ($exportformats == 1) {
                    $content = str_replace('$content', $content, str_replace('$title', $id, $HTML_TEMPLATE));
                }
                $fn = urlencode($id);
                $fn = preg_replace(EWIKI_DUMP_FILENAME_REGEX, "", $fn);
                $fn = $fn . $html_ext;
            } else {
                continue;
            }
            if (empty($content)) {
                switch ($row["flags"] & EWIKI_DB_F_TYPE) {
                    // Text Page
                    case EWIKI_DB_F_TEXT:
                        #print "<pre>"; print_r($row[content]); print "\n-------------</pre>";
                        if ($exportformats == 1) {
                            /// HTML-Export
                            $content = ewiki_format($row["content"]);
                        } else {
                            $content = $row["content"];
                        }
                        # Binary files link adjustment when html
                        if ($exportformats == 1) {
                            $content = str_replace($a_images, $a_rimages, $content);
                        }
                        $fn = preg_replace(EWIKI_DUMP_FILENAME_REGEX, "", urlencode($id));
                        $fn = $fn . $html_ext;
                        if ($exportformats == 1) {
                            /// HTML-Export
                            $content = str_replace('$content', $content, str_replace('$title', $id, $HTML_TEMPLATE));
                        }
                        break;
                    case EWIKI_DB_F_BINARY:
                        #print "Binary: $row[id]<br />";
                        if (($row["meta"]["class"] == "image" || $row["meta"]["class"] == "file") && $exportbinaries) {
                            # Copy files to the appropriate directory
                            $fn = moodle_binary_get_path($id, $row["meta"], $course, $wiki, $userid, $groupid);
                            $destfn = clean_filename(substr($id, strlen(EWIKI_IDF_INTERNAL)));
                            $dest = "{$exportdir}/" . $destfn;
                            if (!copy($fn, $dest)) {
                                notify("Cannot copy {$fn} to {$dest}.");
                            }
                            #$fn = urlencode(preg_replace(EWIKI_DUMP_FILENAME_REGEX, "", $id));
                            #$content = &$row["content"];
                            $filestozip[] = $exportdir . "/" . $destfn;
                            continue 2;
                        } else {
                            #-- php considers switch statements as loops so continue 2 is needed to
                            #-- hit the end of the for loop
                            continue 2;
                        }
                        break;
                    default:
                        # don't want it
                        continue 2;
                }
            }
            # Do not translate links when wiki already in pure html - mode
            if ($wiki->htmlmode != 2) {
                $content = preg_replace_callback('/(<a href=")(.*?)(\\.html">)/', create_function('$matches', 'return($matches[1].preg_replace(EWIKI_DUMP_FILENAME_REGEX,"",$matches[2]).$matches[3]);'), $content);
            }
            #-- add file
            // Let's make sure the file exists and is writable first.
            if (!($handle = fopen($exportdir . "/" . $fn, 'w'))) {
                error("Cannot open file ({$exportdir}/{$fn})");
            }
            // Write $content to our opened file.
            if (fwrite($handle, $content) === FALSE) {
                error("Cannot write to file ({$exportdir}/{$fn})");
            }
            fclose($handle);
            $filestozip[] = $exportdir . "/" . $fn;
            #$archive->add($content, $fn, array(
            #  "mtime" => $row["lastmodified"],
            #  "uname" => "ewiki",
            #  "mode" => 0664 | (($row["flags"]&EWIKI_DB_F_WRITEABLE)?0002:0000),
            #  ), $complevel);
        }
        #-- create index page
        /// HTML-Export
        if ($exportformats == 1) {
            $timer = array();
            $level = -1;
            $fordump = 1;
            $str_formatted = "<ul>\n<li><a href=\"" . $wiki_entry->pagename . $html_ext . "\">" . $wiki_entry->pagename . "</a></li>";
            $fin_level = format_sitemap($a_sitemap, $wiki_entry->pagename, $str_formatted, $level, $timer, $fordump);
            $str_formatted .= "</ul>" . str_pad("", $fin_level * 6, "</ul>\n");
            $str_formatted = preg_replace_callback('/(<a href=")(.*?)(\\.html">)/', create_function('$matches', 'return($matches[1].preg_replace(EWIKI_DUMP_FILENAME_REGEX,"",$matches[2]).$matches[3]);'), $str_formatted);
            $str_formatted = str_replace('$content', $str_formatted, str_replace('$title', get_string("index", "wiki"), $HTML_TEMPLATE));
            #-- add file
            // Let's make sure the file exists and is writable first.
            $indexname = "index" . $html_ext;
            if (!($handle = fopen($exportdir . "/" . $indexname, 'w'))) {
                error("Cannot open file ({$exportdir}/{$indexname})");
            }
            // Write $somecontent to our opened file.
            if (fwrite($handle, $str_formatted) === FALSE) {
                error("Cannot write to file ({$exportdir}/{$indexname})");
            }
            fclose($handle);
            $filestozip[] = $exportdir . "/" . $indexname;
            #-- add index page
            #    $archive->add($str_formatted, "Index_$rootid".$html_ext, array(
            #      "mtime" => $row["lastmodified"],
            #      "uname" => "ewiki",
            #      "mode" => 0664 | (($row["flags"]&EWIKI_DB_F_WRITEABLE)?0002:0000),
            #      ), $complevel);
        }
        if (!$exportdestinations) {
            $archivename = $wname . ".zip";
            zip_files($filestozip, "{$exportbasedir}/{$archivename}");
            #-- Headers
            Header("Content-type: application/zip");
            Header("Content-disposition: attachment; filename=\"{$archivename}\"");
            Header("Cache-control: private");
            Header("Original-Filename: {$archivename}");
            Header("X-Content-Type: application/zip");
            Header("Content-Location: {$archivename}");
            if (!@readfile("{$exportbasedir}/{$archivename}")) {
                error("Cannot read {$exportbasedir}/{$archivename}");
            }
            if (!deldir($exportbasedir)) {
                error("Cannot delete {$exportbasedir}");
            }
            #exit();
            return false;
        } else {
            return get_string("exportsuccessful", "wiki") . "<br />";
        }
    }
}
Example #29
0
                $myxls->write_string($row, 3, $ug2);
                if (isset($option_text)) {
                    $myxls->write_string($row, 4, format_string($option_text, true));
                }
                $row++;
            }
        }
        $pos = 4;
    }
    /// Close the workbook
    $workbook->close();
    exit;
}
// print text file
if ($download == "txt" && has_capability('mod/choice:downloadresponses', $context)) {
    $filename = clean_filename("{$course->shortname} " . strip_tags(format_string($choice->name, true))) . '.txt';
    header("Content-Type: application/download\n");
    header("Content-Disposition: attachment; filename=\"{$filename}\"");
    header("Expires: 0");
    header("Cache-Control: must-revalidate,post-check=0,pre-check=0");
    header("Pragma: public");
    /// Print names of all the fields
    echo get_string("lastname") . "\t" . get_string("firstname") . "\t" . get_string("idnumber") . "\t";
    echo get_string("group") . "\t";
    echo get_string("choice", "choice") . "\n";
    /// generate the data for the body of the spreadsheet
    $i = 0;
    if ($users) {
        foreach ($users as $option => $userid) {
            $option_text = choice_get_option_text($choice, $option);
            foreach ($userid as $user) {
Example #30
0
 function display($quiz, $cm, $course)
 {
     /// This function just displays the report
     global $CFG, $SESSION, $db, $QTYPES;
     $strnoquiz = get_string('noquiz', 'quiz');
     $strnoattempts = get_string('noattempts', 'quiz');
     /// Only print headers if not asked to download data
     $download = optional_param('download', NULL);
     if (!$download) {
         $this->print_header_and_tabs($cm, $course, $quiz, $reportmode = "analysis");
     }
     /// Construct the table for this particular report
     if (!$quiz->questions) {
         print_heading($strnoattempts);
         return true;
     }
     /// Check to see if groups are being used in this quiz
     if ($groupmode = groupmode($course, $cm)) {
         // Groups are being used
         if (!$download) {
             $currentgroup = setup_and_print_groups($course, $groupmode, "report.php?id={$cm->id}&amp;mode=analysis");
         } else {
             $currentgroup = get_and_set_current_group($course, $groupmode);
         }
     } else {
         $currentgroup = get_and_set_current_group($course, $groupmode);
     }
     // set Table and Analysis stats options
     if (!isset($SESSION->quiz_analysis_table)) {
         $SESSION->quiz_analysis_table = array('attemptselection' => 0, 'lowmarklimit' => 0, 'pagesize' => 10);
     }
     foreach ($SESSION->quiz_analysis_table as $option => $value) {
         $urlparam = optional_param($option, NULL);
         if ($urlparam === NULL) {
             ${$option} = $value;
         } else {
             ${$option} = $SESSION->quiz_analysis_table[$option] = $urlparam;
         }
     }
     $scorelimit = $quiz->sumgrades * $lowmarklimit / 100;
     // ULPGC ecastro DEBUG this is here to allow for different SQL to select attempts
     switch ($attemptselection) {
         case QUIZ_ALLATTEMPTS:
             $limit = '';
             $group = '';
             break;
         case QUIZ_HIGHESTATTEMPT:
             $limit = ', max(qa.sumgrades) ';
             $group = ' GROUP BY qa.userid ';
             break;
         case QUIZ_FIRSTATTEMPT:
             $limit = ', min(qa.timemodified) ';
             $group = ' GROUP BY qa.userid ';
             break;
         case QUIZ_LASTATTEMPT:
             $limit = ', max(qa.timemodified) ';
             $group = ' GROUP BY qa.userid ';
             break;
     }
     if ($attemptselection != QUIZ_ALLATTEMPTS) {
         $sql = 'SELECT qa.userid ' . $limit . 'FROM ' . $CFG->prefix . 'user u LEFT JOIN ' . $CFG->prefix . 'quiz_attempts qa ON u.id = qa.userid ' . 'WHERE qa.quiz = ' . $quiz->id . ' AND qa.preview = 0 ' . $group;
         $usermax = get_records_sql_menu($sql);
     }
     $groupmembers = '';
     $groupwhere = '';
     //Add this to the SQL to show only group users
     if ($currentgroup) {
         $groupmembers = ', ' . groups_members_from_sql();
         $groupwhere = ' AND ' . groups_members_where_sql($currentgroup, 'u.id');
     }
     $sql = 'SELECT  qa.* FROM ' . $CFG->prefix . 'quiz_attempts qa, ' . $CFG->prefix . 'user u ' . $groupmembers . 'WHERE u.id = qa.userid AND qa.quiz = ' . $quiz->id . ' AND qa.preview = 0 AND ( qa.sumgrades >= ' . $scorelimit . ' ) ' . $groupwhere;
     // ^^^^^^ es posible seleccionar aqu TODOS los quizzes, como quiere Jussi,
     // pero habra que llevar la cuenta ed cada quiz para restaura las preguntas (quizquestions, states)
     /// Fetch the attempts
     $attempts = get_records_sql($sql);
     if (empty($attempts)) {
         print_heading(get_string('nothingtodisplay'));
         $this->print_options_form($quiz, $cm, $attemptselection, $lowmarklimit, $pagesize);
         return true;
     }
     /// Here we rewiew all attempts and record data to construct the table
     $questions = array();
     $statstable = array();
     $questionarray = array();
     foreach ($attempts as $attempt) {
         $questionarray[] = quiz_questions_in_quiz($attempt->layout);
     }
     $questionlist = quiz_questions_in_quiz(implode(",", $questionarray));
     $questionarray = array_unique(explode(",", $questionlist));
     $questionlist = implode(",", $questionarray);
     unset($questionarray);
     foreach ($attempts as $attempt) {
         switch ($attemptselection) {
             case QUIZ_ALLATTEMPTS:
                 $userscore = 0;
                 // can be anything, not used
                 break;
             case QUIZ_HIGHESTATTEMPT:
                 $userscore = $attempt->sumgrades;
                 break;
             case QUIZ_FIRSTATTEMPT:
                 $userscore = $attempt->timemodified;
                 break;
             case QUIZ_LASTATTEMPT:
                 $userscore = $attempt->timemodified;
                 break;
         }
         if ($attemptselection == QUIZ_ALLATTEMPTS || $userscore == $usermax[$attempt->userid]) {
             $sql = "SELECT q.*, i.grade AS maxgrade, i.id AS instance" . "  FROM {$CFG->prefix}question q," . "       {$CFG->prefix}quiz_question_instances i" . " WHERE i.quiz = '{$quiz->id}' AND q.id = i.question" . "   AND q.id IN ({$questionlist})";
             if (!($quizquestions = get_records_sql($sql))) {
                 error('No questions found');
             }
             // Load the question type specific information
             if (!get_question_options($quizquestions)) {
                 error('Could not load question options');
             }
             // Restore the question sessions to their most recent states
             // creating new sessions where required
             if (!($states = get_question_states($quizquestions, $quiz, $attempt))) {
                 error('Could not restore question sessions');
             }
             $numbers = explode(',', $questionlist);
             $statsrow = array();
             foreach ($numbers as $i) {
                 if (!isset($quizquestions[$i]) or !isset($states[$i])) {
                     continue;
                 }
                 $qtype = $quizquestions[$i]->qtype == 'random' ? $states[$i]->options->question->qtype : $quizquestions[$i]->qtype;
                 $q = get_question_responses($quizquestions[$i], $states[$i]);
                 if (empty($q)) {
                     continue;
                 }
                 $qid = $q->id;
                 if (!isset($questions[$qid])) {
                     $questions[$qid]['id'] = $qid;
                     $questions[$qid]['qname'] = $quizquestions[$i]->name;
                     foreach ($q->responses as $answer => $r) {
                         $r->count = 0;
                         $questions[$qid]['responses'][$answer] = $r->answer;
                         $questions[$qid]['rcounts'][$answer] = 0;
                         $questions[$qid]['credits'][$answer] = $r->credit;
                         $statsrow[$qid] = 0;
                     }
                 }
                 $responses = get_question_actual_response($quizquestions[$i], $states[$i]);
                 foreach ($responses as $resp) {
                     if ($resp) {
                         if ($key = array_search($resp, $questions[$qid]['responses'])) {
                             $questions[$qid]['rcounts'][$key]++;
                         } else {
                             $test = new stdClass();
                             $test->responses = $QTYPES[$quizquestions[$i]->qtype]->get_correct_responses($quizquestions[$i], $states[$i]);
                             if ($key = $QTYPES[$quizquestions[$i]->qtype]->check_response($quizquestions[$i], $states[$i], $test)) {
                                 $questions[$qid]['rcounts'][$key]++;
                             } else {
                                 $questions[$qid]['responses'][] = $resp;
                                 $questions[$qid]['rcounts'][] = 1;
                                 $questions[$qid]['credits'][] = 0;
                             }
                         }
                     }
                 }
                 $statsrow[$qid] = get_question_fraction_grade($quizquestions[$i], $states[$i]);
             }
             $attemptscores[$attempt->id] = $attempt->sumgrades;
             $statstable[$attempt->id] = $statsrow;
         }
     }
     // Statistics Data table built
     unset($attempts);
     unset($quizquestions);
     unset($states);
     // now calculate statistics and set the values in the $questions array
     $top = max($attemptscores);
     $bottom = min($attemptscores);
     $gap = ($top - $bottom) / 3;
     $top -= $gap;
     $bottom += $gap;
     foreach ($questions as $qid => $q) {
         $questions[$qid] = $this->report_question_stats($q, $attemptscores, $statstable, $top, $bottom);
     }
     unset($attemptscores);
     unset($statstable);
     /// Now check if asked download of data
     if ($download = optional_param('download', NULL)) {
         $filename = clean_filename("{$course->shortname} " . format_string($quiz->name, true));
         switch ($download) {
             case "Excel":
                 $this->Export_Excel($questions, $filename);
                 break;
             case "ODS":
                 $this->Export_ODS($questions, $filename);
                 break;
             case "CSV":
                 $this->Export_CSV($questions, $filename);
                 break;
         }
     }
     /// Construct the table for this particular report
     $tablecolumns = array('id', 'qname', 'responses', 'credits', 'rcounts', 'rpercent', 'facility', 'qsd', 'disc_index', 'disc_coeff');
     $tableheaders = array(get_string('qidtitle', 'quiz_analysis'), get_string('qtexttitle', 'quiz_analysis'), get_string('responsestitle', 'quiz_analysis'), get_string('rfractiontitle', 'quiz_analysis'), get_string('rcounttitle', 'quiz_analysis'), get_string('rpercenttitle', 'quiz_analysis'), get_string('facilitytitle', 'quiz_analysis'), get_string('stddevtitle', 'quiz_analysis'), get_string('dicsindextitle', 'quiz_analysis'), get_string('disccoefftitle', 'quiz_analysis'));
     $table = new flexible_table('mod-quiz-report-itemanalysis');
     $table->define_columns($tablecolumns);
     $table->define_headers($tableheaders);
     $table->define_baseurl($CFG->wwwroot . '/mod/quiz/report.php?q=' . $quiz->id . '&amp;mode=analysis');
     $table->sortable(true);
     $table->no_sorting('rpercent');
     $table->collapsible(true);
     $table->initialbars(false);
     $table->column_class('id', 'numcol');
     $table->column_class('credits', 'numcol');
     $table->column_class('rcounts', 'numcol');
     $table->column_class('rpercent', 'numcol');
     $table->column_class('facility', 'numcol');
     $table->column_class('qsd', 'numcol');
     $table->column_class('disc_index', 'numcol');
     $table->column_class('disc_coeff', 'numcol');
     $table->column_suppress('id');
     $table->column_suppress('qname');
     $table->column_suppress('facility');
     $table->column_suppress('qsd');
     $table->column_suppress('disc_index');
     $table->column_suppress('disc_coeff');
     $table->set_attribute('cellspacing', '0');
     $table->set_attribute('id', 'itemanalysis');
     $table->set_attribute('class', 'generaltable generalbox');
     // Start working -- this is necessary as soon as the niceties are over
     $table->setup();
     $tablesort = $table->get_sql_sort();
     $sorts = explode(",", trim($tablesort));
     if ($tablesort and is_array($sorts)) {
         $sortindex = array();
         $sortorder = array();
         foreach ($sorts as $sort) {
             $data = explode(" ", trim($sort));
             $sortindex[] = trim($data[0]);
             $s = trim($data[1]);
             if ($s == "ASC") {
                 $sortorder[] = SORT_ASC;
             } else {
                 $sortorder[] = SORT_DESC;
             }
         }
         if (count($sortindex) > 0) {
             $sortindex[] = "id";
             $sortorder[] = SORT_ASC;
             foreach ($questions as $qid => $row) {
                 $index1[$qid] = $row[$sortindex[0]];
                 $index2[$qid] = $row[$sortindex[1]];
             }
             array_multisort($index1, $sortorder[0], $index2, $sortorder[1], $questions);
         }
     }
     $format_options = new stdClass();
     $format_options->para = false;
     $format_options->noclean = true;
     $format_options->newlines = false;
     // Now it is time to page the data, simply slice the keys in the array
     if (!isset($pagesize) || (int) $pagesize < 1) {
         $pagesize = 10;
     }
     $table->pagesize($pagesize, count($questions));
     $start = $table->get_page_start();
     $pagequestions = array_slice(array_keys($questions), $start, $pagesize);
     foreach ($pagequestions as $qnum) {
         $q = $questions[$qnum];
         $qid = $q['id'];
         $question = get_record('question', 'id', $qid);
         if (has_capability('moodle/question:manage', get_context_instance(CONTEXT_COURSE, $course->id))) {
             $qnumber = " (" . link_to_popup_window('/question/question.php?id=' . $qid, '&amp;cmid=' . $cm->id . 'editquestion', $qid, 450, 550, get_string('edit'), 'none', true) . ") ";
         } else {
             $qnumber = $qid;
         }
         $qname = '<div class="qname">' . format_text($question->name . " :  ", $question->questiontextformat, $format_options, $quiz->course) . '</div>';
         $qicon = print_question_icon($question, true);
         $qreview = quiz_question_preview_button($quiz, $question);
         $qtext = format_text($question->questiontext, $question->questiontextformat, $format_options, $quiz->course);
         $qquestion = $qname . "\n" . $qtext . "\n";
         $responses = array();
         foreach ($q['responses'] as $aid => $resp) {
             $response = new stdClass();
             if ($q['credits'][$aid] <= 0) {
                 $qclass = 'uncorrect';
             } elseif ($q['credits'][$aid] == 1) {
                 $qclass = 'correct';
             } else {
                 $qclass = 'partialcorrect';
             }
             $response->credit = '<span class="' . $qclass . '">(' . format_float($q['credits'][$aid], 2) . ') </span>';
             $response->text = '<span class="' . $qclass . '">' . format_text($resp, FORMAT_MOODLE, $format_options, $quiz->course) . ' </span>';
             $count = $q['rcounts'][$aid] . '/' . $q['count'];
             $response->rcount = $count;
             $response->rpercent = '(' . format_float($q['rcounts'][$aid] / $q['count'] * 100, 0) . '%)';
             $responses[] = $response;
         }
         $facility = format_float($q['facility'] * 100, 0) . "%";
         $qsd = format_float($q['qsd'], 3);
         $di = format_float($q['disc_index'], 2);
         $dc = format_float($q['disc_coeff'], 2);
         $response = array_shift($responses);
         $table->add_data(array($qnumber . "\n<br />" . $qicon . "\n " . $qreview, $qquestion, $response->text, $response->credit, $response->rcount, $response->rpercent, $facility, $qsd, $di, $dc));
         foreach ($responses as $response) {
             $table->add_data(array('', '', $response->text, $response->credit, $response->rcount, $response->rpercent, '', '', '', ''));
         }
     }
     print_heading_with_help(get_string("analysistitle", "quiz_analysis"), "itemanalysis", "quiz");
     echo '<div id="tablecontainer">';
     $table->print_html();
     echo '</div>';
     $this->print_options_form($quiz, $cm, $attemptselection, $lowmarklimit, $pagesize);
     return true;
 }