Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
tree: ce5940cc94
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

file 1576 lines (1375 sloc) 68.012 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575
<?php

// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.

/**
* Library of workshop module functions needed by Moodle core and other subsystems
*
* All the functions neeeded by Moodle core, gradebook, file subsystem etc
* are placed here.
*
* @package mod
* @subpackage workshop
* @copyright 2009 David Mudrak <david.mudrak@gmail.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/

defined('MOODLE_INTERNAL') || die();

require_once($CFG->dirroot . '/calendar/lib.php');

////////////////////////////////////////////////////////////////////////////////
// Moodle core API //
////////////////////////////////////////////////////////////////////////////////

/**
* Returns the information if the module supports a feature
*
* @see plugin_supports() in lib/moodlelib.php
* @param string $feature FEATURE_xx constant for requested feature
* @return mixed true if the feature is supported, null if unknown
*/
function workshop_supports($feature) {
    switch($feature) {
        case FEATURE_GRADE_HAS_GRADE: return true;
        case FEATURE_GROUPS: return true;
        case FEATURE_GROUPINGS: return true;
        case FEATURE_GROUPMEMBERSONLY: return true;
        case FEATURE_MOD_INTRO: return true;
        case FEATURE_BACKUP_MOODLE2: return true;
        case FEATURE_COMPLETION_TRACKS_VIEWS:
            return true;
        case FEATURE_SHOW_DESCRIPTION: return true;
        default: return null;
    }
}

/**
* Saves a new instance of the workshop into the database
*
* Given an object containing all the necessary data,
* (defined by the form in mod_form.php) this function
* will save a new instance and return the id number
* of the new instance.
*
* @param stdClass $workshop An object from the form in mod_form.php
* @return int The id of the newly inserted workshop record
*/
function workshop_add_instance(stdclass $workshop) {
    global $CFG, $DB;
    require_once(dirname(__FILE__) . '/locallib.php');

    $workshop->phase = workshop::PHASE_SETUP;
    $workshop->timecreated = time();
    $workshop->timemodified = $workshop->timecreated;
    $workshop->useexamples = (int)!empty($workshop->useexamples);
    $workshop->usepeerassessment = (int)!empty($workshop->usepeerassessment);
    $workshop->useselfassessment = (int)!empty($workshop->useselfassessment);
    $workshop->latesubmissions = (int)!empty($workshop->latesubmissions);
    $workshop->phaseswitchassessment = (int)!empty($workshop->phaseswitchassessment);
    $workshop->evaluation = 'best';

    // insert the new record so we get the id
    $workshop->id = $DB->insert_record('workshop', $workshop);

    // we need to use context now, so we need to make sure all needed info is already in db
    $cmid = $workshop->coursemodule;
    $DB->set_field('course_modules', 'instance', $workshop->id, array('id' => $cmid));
    $context = get_context_instance(CONTEXT_MODULE, $cmid);

    // process the custom wysiwyg editors
    if ($draftitemid = $workshop->instructauthorseditor['itemid']) {
        $workshop->instructauthors = file_save_draft_area_files($draftitemid, $context->id, 'mod_workshop', 'instructauthors',
                0, workshop::instruction_editors_options($context), $workshop->instructauthorseditor['text']);
        $workshop->instructauthorsformat = $workshop->instructauthorseditor['format'];
    }

    if ($draftitemid = $workshop->instructreviewerseditor['itemid']) {
        $workshop->instructreviewers = file_save_draft_area_files($draftitemid, $context->id, 'mod_workshop', 'instructreviewers',
                0, workshop::instruction_editors_options($context), $workshop->instructreviewerseditor['text']);
        $workshop->instructreviewersformat = $workshop->instructreviewerseditor['format'];
    }

    // re-save the record with the replaced URLs in editor fields
    $DB->update_record('workshop', $workshop);

    // create gradebook items
    workshop_grade_item_update($workshop);
    workshop_grade_item_category_update($workshop);

    // create calendar events
    workshop_calendar_update($workshop, $workshop->coursemodule);

    return $workshop->id;
}

/**
* Given an object containing all the necessary data,
* (defined by the form in mod_form.php) this function
* will update an existing instance with new data.
*
* @param stdClass $workshop An object from the form in mod_form.php
* @return bool success
*/
function workshop_update_instance(stdclass $workshop) {
    global $CFG, $DB;
    require_once(dirname(__FILE__) . '/locallib.php');

    $workshop->timemodified = time();
    $workshop->id = $workshop->instance;
    $workshop->useexamples = (int)!empty($workshop->useexamples);
    $workshop->usepeerassessment = (int)!empty($workshop->usepeerassessment);
    $workshop->useselfassessment = (int)!empty($workshop->useselfassessment);
    $workshop->latesubmissions = (int)!empty($workshop->latesubmissions);
    $workshop->phaseswitchassessment = (int)!empty($workshop->phaseswitchassessment);
    $workshop->evaluation = 'best';

    // todo - if the grading strategy is being changed, we must replace all aggregated peer grades with nulls
    // todo - if maximum grades are being changed, we should probably recalculate or invalidate them

    $DB->update_record('workshop', $workshop);
    $context = get_context_instance(CONTEXT_MODULE, $workshop->coursemodule);

    // process the custom wysiwyg editors
    if ($draftitemid = $workshop->instructauthorseditor['itemid']) {
        $workshop->instructauthors = file_save_draft_area_files($draftitemid, $context->id, 'mod_workshop', 'instructauthors',
                0, workshop::instruction_editors_options($context), $workshop->instructauthorseditor['text']);
        $workshop->instructauthorsformat = $workshop->instructauthorseditor['format'];
    }

    if ($draftitemid = $workshop->instructreviewerseditor['itemid']) {
        $workshop->instructreviewers = file_save_draft_area_files($draftitemid, $context->id, 'mod_workshop', 'instructreviewers',
                0, workshop::instruction_editors_options($context), $workshop->instructreviewerseditor['text']);
        $workshop->instructreviewersformat = $workshop->instructreviewerseditor['format'];
    }

    // re-save the record with the replaced URLs in editor fields
    $DB->update_record('workshop', $workshop);

    // update gradebook items
    workshop_grade_item_update($workshop);
    workshop_grade_item_category_update($workshop);

    // update calendar events
    workshop_calendar_update($workshop, $workshop->coursemodule);

    return true;
}

/**
* Given an ID of an instance of this module,
* this function will permanently delete the instance
* and any data that depends on it.
*
* @param int $id Id of the module instance
* @return boolean Success/Failure
*/
function workshop_delete_instance($id) {
    global $CFG, $DB;
    require_once($CFG->libdir.'/gradelib.php');

    if (! $workshop = $DB->get_record('workshop', array('id' => $id))) {
        return false;
    }

    // delete all associated aggregations
    $DB->delete_records('workshop_aggregations', array('workshopid' => $workshop->id));

    // get the list of ids of all submissions
    $submissions = $DB->get_records('workshop_submissions', array('workshopid' => $workshop->id), '', 'id');

    // get the list of all allocated assessments
    $assessments = $DB->get_records_list('workshop_assessments', 'submissionid', array_keys($submissions), '', 'id');

    // delete the associated records from the workshop core tables
    $DB->delete_records_list('workshop_grades', 'assessmentid', array_keys($assessments));
    $DB->delete_records_list('workshop_assessments', 'id', array_keys($assessments));
    $DB->delete_records_list('workshop_submissions', 'id', array_keys($submissions));

    // call the static clean-up methods of all available subplugins
    $strategies = get_plugin_list('workshopform');
    foreach ($strategies as $strategy => $path) {
        require_once($path.'/lib.php');
        $classname = 'workshop_'.$strategy.'_strategy';
        call_user_func($classname.'::delete_instance', $workshop->id);
    }

    $allocators = get_plugin_list('workshopallocation');
    foreach ($allocators as $allocator => $path) {
        require_once($path.'/lib.php');
        $classname = 'workshop_'.$allocator.'_allocator';
        call_user_func($classname.'::delete_instance', $workshop->id);
    }

    $evaluators = get_plugin_list('workshopeval');
    foreach ($evaluators as $evaluator => $path) {
        require_once($path.'/lib.php');
        $classname = 'workshop_'.$evaluator.'_evaluation';
        call_user_func($classname.'::delete_instance', $workshop->id);
    }

    // delete the calendar events
    $events = $DB->get_records('event', array('modulename' => 'workshop', 'instance' => $workshop->id));
    foreach ($events as $event) {
        $event = calendar_event::load($event);
        $event->delete();
    }

    // finally remove the workshop record itself
    $DB->delete_records('workshop', array('id' => $workshop->id));

    // gradebook cleanup
    grade_update('mod/workshop', $workshop->course, 'mod', 'workshop', $workshop->id, 0, null, array('deleted' => true));
    grade_update('mod/workshop', $workshop->course, 'mod', 'workshop', $workshop->id, 1, null, array('deleted' => true));

    return true;
}

/**
* Return a small object with summary information about what a
* user has done with a given particular instance of this module
* Used for user activity reports.
* $return->time = the time they did it
* $return->info = a short text description
*
* @return stdclass|null
*/
function workshop_user_outline($course, $user, $mod, $workshop) {
    global $CFG, $DB;
    require_once($CFG->libdir.'/gradelib.php');

    $grades = grade_get_grades($course->id, 'mod', 'workshop', $workshop->id, $user->id);

    $submissiongrade = null;
    $assessmentgrade = null;

    $info = '';
    $time = 0;

    if (!empty($grades->items[0]->grades)) {
        $submissiongrade = reset($grades->items[0]->grades);
        $info .= get_string('submissiongrade', 'workshop') . ': ' . $submissiongrade->str_long_grade . html_writer::empty_tag('br');
        $time = max($time, $submissiongrade->dategraded);
    }
    if (!empty($grades->items[1]->grades)) {
        $assessmentgrade = reset($grades->items[1]->grades);
        $info .= get_string('gradinggrade', 'workshop') . ': ' . $assessmentgrade->str_long_grade;
        $time = max($time, $assessmentgrade->dategraded);
    }

    if (!empty($info) and !empty($time)) {
        $return = new stdclass();
        $return->time = $time;
        $return->info = $info;
        return $return;
    }

    return null;
}

/**
* Print a detailed representation of what a user has done with
* a given particular instance of this module, for user activity reports.
*
* @return string HTML
*/
function workshop_user_complete($course, $user, $mod, $workshop) {
    global $CFG, $DB, $OUTPUT;
    require_once(dirname(__FILE__).'/locallib.php');
    require_once($CFG->libdir.'/gradelib.php');

    $workshop = new workshop($workshop, $mod, $course);
    $grades = grade_get_grades($course->id, 'mod', 'workshop', $workshop->id, $user->id);

    if (!empty($grades->items[0]->grades)) {
        $submissiongrade = reset($grades->items[0]->grades);
        $info = get_string('submissiongrade', 'workshop') . ': ' . $submissiongrade->str_long_grade;
        echo html_writer::tag('li', $info, array('class'=>'submissiongrade'));
    }
    if (!empty($grades->items[1]->grades)) {
        $assessmentgrade = reset($grades->items[1]->grades);
        $info = get_string('gradinggrade', 'workshop') . ': ' . $assessmentgrade->str_long_grade;
        echo html_writer::tag('li', $info, array('class'=>'gradinggrade'));
    }

    if (has_capability('mod/workshop:viewallsubmissions', $workshop->context)) {
        $canviewsubmission = true;
        if (groups_get_activity_groupmode($workshop->cm) == SEPARATEGROUPS) {
            // user must have accessallgroups or share at least one group with the submission author
            if (!has_capability('moodle/site:accessallgroups', $workshop->context)) {
                $usersgroups = groups_get_activity_allowed_groups($workshop->cm);
                $authorsgroups = groups_get_all_groups($workshop->course->id, $user->id, $workshop->cm->groupingid, 'g.id');
                $sharedgroups = array_intersect_key($usersgroups, $authorsgroups);
                if (empty($sharedgroups)) {
                    $canviewsubmission = false;
                }
            }
        }
        if ($canviewsubmission and $submission = $workshop->get_submission_by_author($user->id)) {
            $title = format_string($submission->title);
            $url = $workshop->submission_url($submission->id);
            $link = html_writer::link($url, $title);
            $info = get_string('submission', 'workshop').': '.$link;
            echo html_writer::tag('li', $info, array('class'=>'submission'));
        }
    }

    if (has_capability('mod/workshop:viewallassessments', $workshop->context)) {
        if ($assessments = $workshop->get_assessments_by_reviewer($user->id)) {
            foreach ($assessments as $assessment) {
                $a = new stdclass();
                $a->submissionurl = $workshop->submission_url($assessment->submissionid)->out();
                $a->assessmenturl = $workshop->assess_url($assessment->id)->out();
                $a->submissiontitle = s($assessment->submissiontitle);
                echo html_writer::tag('li', get_string('assessmentofsubmission', 'workshop', $a));
            }
        }
    }
}

/**
* Given a course and a time, this module should find recent activity
* that has occurred in workshop activities and print it out.
* Return true if there was output, or false is there was none.
*
* @param stdClass $course
* @param bool $viewfullnames
* @param int $timestart
* @return boolean
*/
function workshop_print_recent_activity($course, $viewfullnames, $timestart) {
    global $CFG, $USER, $DB, $OUTPUT;

    $sql = "SELECT s.id AS submissionid, s.title AS submissiontitle, s.timemodified AS submissionmodified,
author.id AS authorid, author.lastname AS authorlastname, author.firstname AS authorfirstname,
a.id AS assessmentid, a.timemodified AS assessmentmodified,
reviewer.id AS reviewerid, reviewer.lastname AS reviewerlastname, reviewer.firstname AS reviewerfirstname,
cm.id AS cmid
FROM {workshop} w
INNER JOIN {course_modules} cm ON cm.instance = w.id
INNER JOIN {modules} md ON md.id = cm.module
INNER JOIN {workshop_submissions} s ON s.workshopid = w.id
INNER JOIN {user} author ON s.authorid = author.id
LEFT JOIN {workshop_assessments} a ON a.submissionid = s.id
LEFT JOIN {user} reviewer ON a.reviewerid = reviewer.id
WHERE cm.course = ?
AND md.name = 'workshop'
AND s.example = 0
AND (s.timemodified > ? OR a.timemodified > ?)";

    $rs = $DB->get_recordset_sql($sql, array($course->id, $timestart, $timestart));

    $modinfo = get_fast_modinfo($course); // reference needed because we might load the groups

    $submissions = array(); // recent submissions indexed by submission id
    $assessments = array(); // recent assessments indexed by assessment id
    $users = array();

    foreach ($rs as $activity) {
        if (!array_key_exists($activity->cmid, $modinfo->cms)) {
            // this should not happen but just in case
            continue;
        }

        $cm = $modinfo->cms[$activity->cmid];
        if (!$cm->uservisible) {
            continue;
        }

        if ($viewfullnames) {
            // remember all user names we can use later
            if (empty($users[$activity->authorid])) {
                $u = new stdclass();
                $u->lastname = $activity->authorlastname;
                $u->firstname = $activity->authorfirstname;
                $users[$activity->authorid] = $u;
            }
            if ($activity->reviewerid and empty($users[$activity->reviewerid])) {
                $u = new stdclass();
                $u->lastname = $activity->reviewerlastname;
                $u->firstname = $activity->reviewerfirstname;
                $users[$activity->reviewerid] = $u;
            }
        }

        $context = get_context_instance(CONTEXT_MODULE, $cm->id);
        $groupmode = groups_get_activity_groupmode($cm, $course);

        if ($activity->submissionmodified > $timestart and empty($submissions[$activity->submissionid])) {
            $s = new stdclass();
            $s->title = $activity->submissiontitle;
            $s->authorid = $activity->authorid;
            $s->timemodified = $activity->submissionmodified;
            $s->cmid = $activity->cmid;
            if (has_capability('mod/workshop:viewauthornames', $context)) {
                $s->authornamevisible = true;
            } else {
                $s->authornamevisible = false;
            }

            // the following do-while wrapper allows to break from deeply nested if-statements
            do {
                if ($s->authorid === $USER->id) {
                    // own submissions always visible
                    $submissions[$activity->submissionid] = $s;
                    break;
                }

                if (has_capability('mod/workshop:viewallsubmissions', $context)) {
                    if ($groupmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context)) {
                        if (isguestuser()) {
                            // shortcut - guest user does not belong into any group
                            break;
                        }

                        if (is_null($modinfo->groups)) {
                            $modinfo->groups = groups_get_user_groups($course->id); // load all my groups and cache it in modinfo
                        }

                        // this might be slow - show only submissions by users who share group with me in this cm
                        if (empty($modinfo->groups[$cm->id])) {
                            break;
                        }
                        $authorsgroups = groups_get_all_groups($course->id, $s->authorid, $cm->groupingid);
                        if (is_array($authorsgroups)) {
                            $authorsgroups = array_keys($authorsgroups);
                            $intersect = array_intersect($authorsgroups, $modinfo->groups[$cm->id]);
                            if (empty($intersect)) {
                                break;
                            } else {
                                // can see all submissions and shares a group with the author
                                $submissions[$activity->submissionid] = $s;
                                break;
                            }
                        }

                    } else {
                        // can see all submissions from all groups
                        $submissions[$activity->submissionid] = $s;
                    }
                }
            } while (0);
        }

        if ($activity->assessmentmodified > $timestart and empty($assessments[$activity->assessmentid])) {
            $a = new stdclass();
            $a->submissionid = $activity->submissionid;
            $a->submissiontitle = $activity->submissiontitle;
            $a->reviewerid = $activity->reviewerid;
            $a->timemodified = $activity->assessmentmodified;
            $a->cmid = $activity->cmid;
            if (has_capability('mod/workshop:viewreviewernames', $context)) {
                $a->reviewernamevisible = true;
            } else {
                $a->reviewernamevisible = false;
            }

            // the following do-while wrapper allows to break from deeply nested if-statements
            do {
                if ($a->reviewerid === $USER->id) {
                    // own assessments always visible
                    $assessments[$activity->assessmentid] = $a;
                    break;
                }

                if (has_capability('mod/workshop:viewallassessments', $context)) {
                    if ($groupmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context)) {
                        if (isguestuser()) {
                            // shortcut - guest user does not belong into any group
                            break;
                        }

                        if (is_null($modinfo->groups)) {
                            $modinfo->groups = groups_get_user_groups($course->id); // load all my groups and cache it in modinfo
                        }

                        // this might be slow - show only submissions by users who share group with me in this cm
                        if (empty($modinfo->groups[$cm->id])) {
                            break;
                        }
                        $reviewersgroups = groups_get_all_groups($course->id, $a->reviewerid, $cm->groupingid);
                        if (is_array($reviewersgroups)) {
                            $reviewersgroups = array_keys($reviewersgroups);
                            $intersect = array_intersect($reviewersgroups, $modinfo->groups[$cm->id]);
                            if (empty($intersect)) {
                                break;
                            } else {
                                // can see all assessments and shares a group with the reviewer
                                $assessments[$activity->assessmentid] = $a;
                                break;
                            }
                        }

                    } else {
                        // can see all assessments from all groups
                        $assessments[$activity->assessmentid] = $a;
                    }
                }
            } while (0);
        }
    }
    $rs->close();

    $shown = false;

    if (!empty($submissions)) {
        $shown = true;
        echo $OUTPUT->heading(get_string('recentsubmissions', 'workshop'), 3);
        foreach ($submissions as $id => $submission) {
            $link = new moodle_url('/mod/workshop/submission.php', array('id'=>$id, 'cmid'=>$submission->cmid));
            if ($viewfullnames and $submission->authornamevisible) {
                $author = $users[$submission->authorid];
            } else {
                $author = null;
            }
            print_recent_activity_note($submission->timemodified, $author, $submission->title, $link->out(), false, $viewfullnames);
        }
    }

    if (!empty($assessments)) {
        $shown = true;
        echo $OUTPUT->heading(get_string('recentassessments', 'workshop'), 3);
        foreach ($assessments as $id => $assessment) {
            $link = new moodle_url('/mod/workshop/assessment.php', array('asid' => $id));
            if ($viewfullnames and $assessment->reviewernamevisible) {
                $reviewer = $users[$assessment->reviewerid];
            } else {
                $reviewer = null;
            }
            print_recent_activity_note($assessment->timemodified, $reviewer, $assessment->submissiontitle, $link->out(), false, $viewfullnames);
        }
    }

    if ($shown) {
        return true;
    }

    return false;
}

/**
* Returns all activity in course workshops since a given time
*
* @param array $activities sequentially indexed array of objects
* @param int $index
* @param int $timestart
* @param int $courseid
* @param int $cmid
* @param int $userid defaults to 0
* @param int $groupid defaults to 0
* @return void adds items into $activities and increases $index
*/
function workshop_get_recent_mod_activity(&$activities, &$index, $timestart, $courseid, $cmid, $userid=0, $groupid=0) {
    global $CFG, $COURSE, $USER, $DB;

    if ($COURSE->id == $courseid) {
        $course = $COURSE;
    } else {
        $course = $DB->get_record('course', array('id'=>$courseid));
    }

    $modinfo = get_fast_modinfo($course);

    $cm = $modinfo->cms[$cmid];

    $params = array();
    if ($userid) {
        $userselect = "AND (author.id = :authorid OR reviewer.id = :reviewerid)";
        $params['authorid'] = $userid;
        $params['reviewerid'] = $userid;
    } else {
        $userselect = "";
    }

    if ($groupid) {
        $groupselect = "AND (authorgroupmembership.groupid = :authorgroupid OR reviewergroupmembership.groupid = :reviewergroupid)";
        $groupjoin = "LEFT JOIN {groups_members} authorgroupmembership ON authorgroupmembership.userid = author.id
LEFT JOIN {groups_members} reviewergroupmembership ON reviewergroupmembership.userid = reviewer.id";
        $params['authorgroupid'] = $groupid;
        $params['reviewergroupid'] = $groupid;
    } else {
        $groupselect = "";
        $groupjoin = "";
    }

    $params['cminstance'] = $cm->instance;
    $params['submissionmodified'] = $timestart;
    $params['assessmentmodified'] = $timestart;

    $sql = "SELECT s.id AS submissionid, s.title AS submissiontitle, s.timemodified AS submissionmodified,
author.id AS authorid, author.lastname AS authorlastname, author.firstname AS authorfirstname,
author.picture AS authorpicture, author.imagealt AS authorimagealt, author.email AS authoremail,
a.id AS assessmentid, a.timemodified AS assessmentmodified,
reviewer.id AS reviewerid, reviewer.lastname AS reviewerlastname, reviewer.firstname AS reviewerfirstname,
reviewer.picture AS reviewerpicture, reviewer.imagealt AS reviewerimagealt, reviewer.email AS revieweremail
FROM {workshop_submissions} s
INNER JOIN {workshop} w ON s.workshopid = w.id
INNER JOIN {user} author ON s.authorid = author.id
LEFT JOIN {workshop_assessments} a ON a.submissionid = s.id
LEFT JOIN {user} reviewer ON a.reviewerid = reviewer.id
$groupjoin
WHERE w.id = :cminstance
AND s.example = 0
$userselect $groupselect
AND (s.timemodified > :submissionmodified OR a.timemodified > :assessmentmodified)
ORDER BY s.timemodified ASC, a.timemodified ASC";

    $rs = $DB->get_recordset_sql($sql, $params);

    $groupmode = groups_get_activity_groupmode($cm, $course);
    $context = get_context_instance(CONTEXT_MODULE, $cm->id);
    $grader = has_capability('moodle/grade:viewall', $context);
    $accessallgroups = has_capability('moodle/site:accessallgroups', $context);
    $viewfullnames = has_capability('moodle/site:viewfullnames', $context);
    $viewauthors = has_capability('mod/workshop:viewauthornames', $context);
    $viewreviewers = has_capability('mod/workshop:viewreviewernames', $context);

    if (is_null($modinfo->groups)) {
        $modinfo->groups = groups_get_user_groups($course->id); // load all my groups and cache it in modinfo
    }

    $submissions = array(); // recent submissions indexed by submission id
    $assessments = array(); // recent assessments indexed by assessment id
    $users = array();

    foreach ($rs as $activity) {

        if ($viewfullnames) {
            // remember all user names we can use later
            if (empty($users[$activity->authorid])) {
                $u = new stdclass();
                $u->id = $activity->authorid;
                $u->lastname = $activity->authorlastname;
                $u->firstname = $activity->authorfirstname;
                $u->picture = $activity->authorpicture;
                $u->imagealt = $activity->authorimagealt;
                $u->email = $activity->authoremail;
                $users[$activity->authorid] = $u;
            }
            if ($activity->reviewerid and empty($users[$activity->reviewerid])) {
                $u = new stdclass();
                $u->id = $activity->reviewerid;
                $u->lastname = $activity->reviewerlastname;
                $u->firstname = $activity->reviewerfirstname;
                $u->picture = $activity->reviewerpicture;
                $u->imagealt = $activity->reviewerimagealt;
                $u->email = $activity->revieweremail;
                $users[$activity->reviewerid] = $u;
            }
        }

        if ($activity->submissionmodified > $timestart and empty($submissions[$activity->submissionid])) {
            $s = new stdclass();
            $s->id = $activity->submissionid;
            $s->title = $activity->submissiontitle;
            $s->authorid = $activity->authorid;
            $s->timemodified = $activity->submissionmodified;
            if (has_capability('mod/workshop:viewauthornames', $context)) {
                $s->authornamevisible = true;
            } else {
                $s->authornamevisible = false;
            }

            // the following do-while wrapper allows to break from deeply nested if-statements
            do {
                if ($s->authorid === $USER->id) {
                    // own submissions always visible
                    $submissions[$activity->submissionid] = $s;
                    break;
                }

                if (has_capability('mod/workshop:viewallsubmissions', $context)) {
                    if ($groupmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context)) {
                        if (isguestuser()) {
                            // shortcut - guest user does not belong into any group
                            break;
                        }

                        // this might be slow - show only submissions by users who share group with me in this cm
                        if (empty($modinfo->groups[$cm->id])) {
                            break;
                        }
                        $authorsgroups = groups_get_all_groups($course->id, $s->authorid, $cm->groupingid);
                        if (is_array($authorsgroups)) {
                            $authorsgroups = array_keys($authorsgroups);
                            $intersect = array_intersect($authorsgroups, $modinfo->groups[$cm->id]);
                            if (empty($intersect)) {
                                break;
                            } else {
                                // can see all submissions and shares a group with the author
                                $submissions[$activity->submissionid] = $s;
                                break;
                            }
                        }

                    } else {
                        // can see all submissions from all groups
                        $submissions[$activity->submissionid] = $s;
                    }
                }
            } while (0);
        }

        if ($activity->assessmentmodified > $timestart and empty($assessments[$activity->assessmentid])) {
            $a = new stdclass();
            $a->id = $activity->assessmentid;
            $a->submissionid = $activity->submissionid;
            $a->submissiontitle = $activity->submissiontitle;
            $a->reviewerid = $activity->reviewerid;
            $a->timemodified = $activity->assessmentmodified;
            if (has_capability('mod/workshop:viewreviewernames', $context)) {
                $a->reviewernamevisible = true;
            } else {
                $a->reviewernamevisible = false;
            }

            // the following do-while wrapper allows to break from deeply nested if-statements
            do {
                if ($a->reviewerid === $USER->id) {
                    // own assessments always visible
                    $assessments[$activity->assessmentid] = $a;
                    break;
                }

                if (has_capability('mod/workshop:viewallassessments', $context)) {
                    if ($groupmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context)) {
                        if (isguestuser()) {
                            // shortcut - guest user does not belong into any group
                            break;
                        }

                        // this might be slow - show only submissions by users who share group with me in this cm
                        if (empty($modinfo->groups[$cm->id])) {
                            break;
                        }
                        $reviewersgroups = groups_get_all_groups($course->id, $a->reviewerid, $cm->groupingid);
                        if (is_array($reviewersgroups)) {
                            $reviewersgroups = array_keys($reviewersgroups);
                            $intersect = array_intersect($reviewersgroups, $modinfo->groups[$cm->id]);
                            if (empty($intersect)) {
                                break;
                            } else {
                                // can see all assessments and shares a group with the reviewer
                                $assessments[$activity->assessmentid] = $a;
                                break;
                            }
                        }

                    } else {
                        // can see all assessments from all groups
                        $assessments[$activity->assessmentid] = $a;
                    }
                }
            } while (0);
        }
    }
    $rs->close();

    $workshopname = format_string($cm->name, true);

    if ($grader) {
        require_once($CFG->libdir.'/gradelib.php');
        $grades = grade_get_grades($courseid, 'mod', 'workshop', $cm->instance, array_keys($users));
    }

    foreach ($submissions as $submission) {
        $tmpactivity = new stdclass();
        $tmpactivity->type = 'workshop';
        $tmpactivity->cmid = $cm->id;
        $tmpactivity->name = $workshopname;
        $tmpactivity->sectionnum = $cm->sectionnum;
        $tmpactivity->timestamp = $submission->timemodified;
        $tmpactivity->subtype = 'submission';
        $tmpactivity->content = $submission;
        if ($grader) {
            $tmpactivity->grade = $grades->items[0]->grades[$submission->authorid]->str_long_grade;
        }
        if ($submission->authornamevisible and !empty($users[$submission->authorid])) {
            $tmpactivity->user = $users[$submission->authorid];
        }
        $activities[$index++] = $tmpactivity;
    }

    foreach ($assessments as $assessment) {
        $tmpactivity = new stdclass();
        $tmpactivity->type = 'workshop';
        $tmpactivity->cmid = $cm->id;
        $tmpactivity->name = $workshopname;
        $tmpactivity->sectionnum = $cm->sectionnum;
        $tmpactivity->timestamp = $assessment->timemodified;
        $tmpactivity->subtype = 'assessment';
        $tmpactivity->content = $assessment;
        if ($grader) {
            $tmpactivity->grade = $grades->items[1]->grades[$assessment->reviewerid]->str_long_grade;
        }
        if ($assessment->reviewernamevisible and !empty($users[$assessment->reviewerid])) {
            $tmpactivity->user = $users[$assessment->reviewerid];
        }
        $activities[$index++] = $tmpactivity;
    }
}

/**
* Print single activity item prepared by {@see workshop_get_recent_mod_activity()}
*/
function workshop_print_recent_mod_activity($activity, $courseid, $detail, $modnames, $viewfullnames) {
    global $CFG, $OUTPUT;

    if (!empty($activity->user)) {
        echo html_writer::tag('div', $OUTPUT->user_picture($activity->user, array('courseid'=>$courseid)),
                array('style' => 'float: left; padding: 7px;'));
    }

    if ($activity->subtype == 'submission') {
        echo html_writer::start_tag('div', array('class'=>'submission', 'style'=>'padding: 7px; float:left;'));

        if ($detail) {
            echo html_writer::start_tag('h4', array('class'=>'workshop'));
            $url = new moodle_url('/mod/workshop/view.php', array('id'=>$activity->cmid));
            $name = s($activity->name);
            echo html_writer::empty_tag('img', array('src'=>$OUTPUT->pix_url('icon', $activity->type), 'class'=>'icon', 'alt'=>$name));
            echo ' ' . $modnames[$activity->type];
            echo html_writer::link($url, $name, array('class'=>'name', 'style'=>'margin-left: 5px'));
            echo html_writer::end_tag('h4');
        }

        echo html_writer::start_tag('div', array('class'=>'title'));
        $url = new moodle_url('/mod/workshop/submission.php', array('cmid'=>$activity->cmid, 'id'=>$activity->content->id));
        $name = s($activity->content->title);
        echo html_writer::tag('strong', html_writer::link($url, $name));
        echo html_writer::end_tag('div');

        if (!empty($activity->user)) {
            echo html_writer::start_tag('div', array('class'=>'user'));
            $url = new moodle_url('/user/view.php', array('id'=>$activity->user->id, 'course'=>$courseid));
            $name = fullname($activity->user);
            $link = html_writer::link($url, $name);
            echo get_string('submissionby', 'workshop', $link);
            echo ' - '.userdate($activity->timestamp);
            echo html_writer::end_tag('div');
        } else {
            echo html_writer::start_tag('div', array('class'=>'anonymous'));
            echo get_string('submission', 'workshop');
            echo ' - '.userdate($activity->timestamp);
            echo html_writer::end_tag('div');
        }

        echo html_writer::end_tag('div');
    }

    if ($activity->subtype == 'assessment') {
        echo html_writer::start_tag('div', array('class'=>'assessment', 'style'=>'padding: 7px; float:left;'));

        if ($detail) {
            echo html_writer::start_tag('h4', array('class'=>'workshop'));
            $url = new moodle_url('/mod/workshop/view.php', array('id'=>$activity->cmid));
            $name = s($activity->name);
            echo html_writer::empty_tag('img', array('src'=>$OUTPUT->pix_url('icon', $activity->type), 'class'=>'icon', 'alt'=>$name));
            echo ' ' . $modnames[$activity->type];
            echo html_writer::link($url, $name, array('class'=>'name', 'style'=>'margin-left: 5px'));
            echo html_writer::end_tag('h4');
        }

        echo html_writer::start_tag('div', array('class'=>'title'));
        $url = new moodle_url('/mod/workshop/assessment.php', array('asid'=>$activity->content->id));
        $name = s($activity->content->submissiontitle);
        echo html_writer::tag('em', html_writer::link($url, $name));
        echo html_writer::end_tag('div');

        if (!empty($activity->user)) {
            echo html_writer::start_tag('div', array('class'=>'user'));
            $url = new moodle_url('/user/view.php', array('id'=>$activity->user->id, 'course'=>$courseid));
            $name = fullname($activity->user);
            $link = html_writer::link($url, $name);
            echo get_string('assessmentbyfullname', 'workshop', $link);
            echo ' - '.userdate($activity->timestamp);
            echo html_writer::end_tag('div');
        } else {
            echo html_writer::start_tag('div', array('class'=>'anonymous'));
            echo get_string('assessment', 'workshop');
            echo ' - '.userdate($activity->timestamp);
            echo html_writer::end_tag('div');
        }

        echo html_writer::end_tag('div');
    }

    echo html_writer::empty_tag('br', array('style'=>'clear:both'));
}

/**
* Regular jobs to execute via cron
*
* @return boolean true on success, false otherwise
*/
function workshop_cron() {
    global $CFG, $DB;

    $now = time();

    mtrace(' processing workshop subplugins ...');
    cron_execute_plugin_type('workshopallocation', 'workshop allocation methods');

    // now when the scheduled allocator had a chance to do its job, check if there
    // are some workshops to switch into the assessment phase
    $workshops = $DB->get_records_select("workshop",
        "phase = 20 AND phaseswitchassessment = 1 AND submissionend > 0 AND submissionend < ?", array($now));

    if (!empty($workshops)) {
        mtrace('Processing automatic assessment phase switch in '.count($workshops).' workshop(s) ... ', '');
        require_once($CFG->dirroot.'/mod/workshop/locallib.php');
        foreach ($workshops as $workshop) {
            $cm = get_coursemodule_from_instance('workshop', $workshop->id, $workshop->course, false, MUST_EXIST);
            $course = $DB->get_record('course', array('id' => $cm->course), '*', MUST_EXIST);
            $workshop = new workshop($workshop, $cm, $course);
            $workshop->switch_phase(workshop::PHASE_ASSESSMENT);
            $workshop->log('update switch phase', $workshop->view_url(), $workshop->phase);
            // disable the automatic switching now so that it is not executed again by accident
            // if the teacher changes the phase back to the submission one
            $DB->set_field('workshop', 'phaseswitchassessment', 0, array('id' => $workshop->id));

            // todo inform the teachers
        }
        mtrace('done');
    }

    return true;
}

/**
* Is a given scale used by the instance of workshop?
*
* The function asks all installed grading strategy subplugins. The workshop
* core itself does not use scales. Both grade for submission and grade for
* assessments do not use scales.
*
* @param int $workshopid id of workshop instance
* @param int $scaleid id of the scale to check
* @return bool
*/
function workshop_scale_used($workshopid, $scaleid) {
    global $CFG; // other files included from here

    $strategies = get_plugin_list('workshopform');
    foreach ($strategies as $strategy => $strategypath) {
        $strategylib = $strategypath . '/lib.php';
        if (is_readable($strategylib)) {
            require_once($strategylib);
        } else {
            throw new coding_exception('the grading forms subplugin must contain library ' . $strategylib);
        }
        $classname = 'workshop_' . $strategy . '_strategy';
        if (method_exists($classname, 'scale_used')) {
            if (call_user_func_array(array($classname, 'scale_used'), array($scaleid, $workshopid))) {
                // no need to include any other files - scale is used
                return true;
            }
        }
    }

    return false;
}

/**
* Is a given scale used by any instance of workshop?
*
* The function asks all installed grading strategy subplugins. The workshop
* core itself does not use scales. Both grade for submission and grade for
* assessments do not use scales.
*
* @param int $scaleid id of the scale to check
* @return bool
*/
function workshop_scale_used_anywhere($scaleid) {
    global $CFG; // other files included from here

    $strategies = get_plugin_list('workshopform');
    foreach ($strategies as $strategy => $strategypath) {
        $strategylib = $strategypath . '/lib.php';
        if (is_readable($strategylib)) {
            require_once($strategylib);
        } else {
            throw new coding_exception('the grading forms subplugin must contain library ' . $strategylib);
        }
        $classname = 'workshop_' . $strategy . '_strategy';
        if (method_exists($classname, 'scale_used')) {
            if (call_user_func(array($classname, 'scale_used'), $scaleid)) {
                // no need to include any other files - scale is used
                return true;
            }
        }
    }

    return false;
}

/**
* Returns all other caps used in the module
*
* @return array
*/
function workshop_get_extra_capabilities() {
    return array('moodle/site:accessallgroups');
}

////////////////////////////////////////////////////////////////////////////////
// Gradebook API //
////////////////////////////////////////////////////////////////////////////////

/**
* Creates or updates grade items for the give workshop instance
*
* Needed by grade_update_mod_grades() in lib/gradelib.php. Also used by
* {@link workshop_update_grades()}.
*
* @param stdClass $workshop instance object with extra cmidnumber property
* @param stdClass $submissiongrades data for the first grade item
* @param stdClass $assessmentgrades data for the second grade item
* @return void
*/
function workshop_grade_item_update(stdclass $workshop, $submissiongrades=null, $assessmentgrades=null) {
    global $CFG;
    require_once($CFG->libdir.'/gradelib.php');

    $a = new stdclass();
    $a->workshopname = clean_param($workshop->name, PARAM_NOTAGS);

    $item = array();
    $item['itemname'] = get_string('gradeitemsubmission', 'workshop', $a);
    $item['gradetype'] = GRADE_TYPE_VALUE;
    $item['grademax'] = $workshop->grade;
    $item['grademin'] = 0;
    grade_update('mod/workshop', $workshop->course, 'mod', 'workshop', $workshop->id, 0, $submissiongrades , $item);

    $item = array();
    $item['itemname'] = get_string('gradeitemassessment', 'workshop', $a);
    $item['gradetype'] = GRADE_TYPE_VALUE;
    $item['grademax'] = $workshop->gradinggrade;
    $item['grademin'] = 0;
    grade_update('mod/workshop', $workshop->course, 'mod', 'workshop', $workshop->id, 1, $assessmentgrades, $item);
}

/**
* Update workshop grades in the gradebook
*
* Needed by grade_update_mod_grades() in lib/gradelib.php
*
* @category grade
* @param stdClass $workshop instance object with extra cmidnumber and modname property
* @param int $userid update grade of specific user only, 0 means all participants
* @return void
*/
function workshop_update_grades(stdclass $workshop, $userid=0) {
    global $CFG, $DB;
    require_once($CFG->libdir.'/gradelib.php');

    $whereuser = $userid ? ' AND authorid = :userid' : '';
    $params = array('workshopid' => $workshop->id, 'userid' => $userid);
    $sql = 'SELECT authorid, grade, gradeover, gradeoverby, feedbackauthor, feedbackauthorformat, timemodified, timegraded
FROM {workshop_submissions}
WHERE workshopid = :workshopid AND example=0' . $whereuser;
    $records = $DB->get_records_sql($sql, $params);
    $submissiongrades = array();
    foreach ($records as $record) {
        $grade = new stdclass();
        $grade->userid = $record->authorid;
        if (!is_null($record->gradeover)) {
            $grade->rawgrade = grade_floatval($workshop->grade * $record->gradeover / 100);
            $grade->usermodified = $record->gradeoverby;
        } else {
            $grade->rawgrade = grade_floatval($workshop->grade * $record->grade / 100);
        }
        $grade->feedback = $record->feedbackauthor;
        $grade->feedbackformat = $record->feedbackauthorformat;
        $grade->datesubmitted = $record->timemodified;
        $grade->dategraded = $record->timegraded;
        $submissiongrades[$record->authorid] = $grade;
    }

    $whereuser = $userid ? ' AND userid = :userid' : '';
    $params = array('workshopid' => $workshop->id, 'userid' => $userid);
    $sql = 'SELECT userid, gradinggrade, timegraded
FROM {workshop_aggregations}
WHERE workshopid = :workshopid' . $whereuser;
    $records = $DB->get_records_sql($sql, $params);
    $assessmentgrades = array();
    foreach ($records as $record) {
        $grade = new stdclass();
        $grade->userid = $record->userid;
        $grade->rawgrade = grade_floatval($workshop->gradinggrade * $record->gradinggrade / 100);
        $grade->dategraded = $record->timegraded;
        $assessmentgrades[$record->userid] = $grade;
    }

    workshop_grade_item_update($workshop, $submissiongrades, $assessmentgrades);
}

/**
* Update the grade items categories if they are changed via mod_form.php
*
* We must do it manually here in the workshop module because modedit supports only
* single grade item while we use two.
*
* @param stdClass $workshop An object from the form in mod_form.php
*/
function workshop_grade_item_category_update($workshop) {

    $gradeitems = grade_item::fetch_all(array(
        'itemtype' => 'mod',
        'itemmodule' => 'workshop',
        'iteminstance' => $workshop->id,
        'courseid' => $workshop->course));

    if (!empty($gradeitems)) {
        foreach ($gradeitems as $gradeitem) {
            if ($gradeitem->itemnumber == 0) {
                if ($gradeitem->categoryid != $workshop->gradecategory) {
                    $gradeitem->set_parent($workshop->gradecategory);
                }
            } else if ($gradeitem->itemnumber == 1) {
                if ($gradeitem->categoryid != $workshop->gradinggradecategory) {
                    $gradeitem->set_parent($workshop->gradinggradecategory);
                }
            }
        }
    }
}

////////////////////////////////////////////////////////////////////////////////
// File API //
////////////////////////////////////////////////////////////////////////////////

/**
* Returns the lists of all browsable file areas within the given module context
*
* The file area workshop_intro for the activity introduction field is added automatically
* by {@link file_browser::get_file_info_context_module()}
*
* @package mod_workshop
* @category files
*
* @param stdClass $course
* @param stdClass $cm
* @param stdClass $context
* @return array of [(string)filearea] => (string)description
*/
function workshop_get_file_areas($course, $cm, $context) {
    $areas = array();
    $areas['instructauthors'] = get_string('areainstructauthors', 'workshop');
    $areas['instructreviewers'] = get_string('areainstructreviewers', 'workshop');
    $areas['submission_content'] = get_string('areasubmissioncontent', 'workshop');
    $areas['submission_attachment'] = get_string('areasubmissionattachment', 'workshop');

    return $areas;
}

/**
* Serves the files from the workshop file areas
*
* Apart from module intro (handled by pluginfile.php automatically), workshop files may be
* media inserted into submission content (like images) and submission attachments. For these two,
* the fileareas submission_content and submission_attachment are used.
* Besides that, areas instructauthors and instructreviewers contain the media
* embedded using the mod_form.php.
*
* @package mod_workshop
* @category files
*
* @param stdClass $course the course object
* @param stdClass $cm the course module object
* @param stdClass $context the workshop's context
* @param string $filearea the name of the file area
* @param array $args extra arguments (itemid, path)
* @param bool $forcedownload whether or not force download
* @param array $options additional options affecting the file serving
* @return bool false if the file not found, just send the file otherwise and do not return anything
*/
function workshop_pluginfile($course, $cm, $context, $filearea, array $args, $forcedownload, array $options=array()) {
    global $DB, $CFG, $USER;

    if ($context->contextlevel != CONTEXT_MODULE) {
        return false;
    }

    require_login($course, true, $cm);

    if ($filearea === 'instructauthors') {
        array_shift($args); // itemid is ignored here
        $relativepath = implode('/', $args);
        $fullpath = "/$context->id/mod_workshop/$filearea/0/$relativepath";

        $fs = get_file_storage();
        if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
            send_file_not_found();
        }

        $lifetime = isset($CFG->filelifetime) ? $CFG->filelifetime : 86400;

        // finally send the file
        send_stored_file($file, $lifetime, 0, $forcedownload, $options);
    }

    if ($filearea === 'instructreviewers') {
        array_shift($args); // itemid is ignored here
        $relativepath = implode('/', $args);
        $fullpath = "/$context->id/mod_workshop/$filearea/0/$relativepath";

        $fs = get_file_storage();
        if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
            send_file_not_found();
        }

        $lifetime = isset($CFG->filelifetime) ? $CFG->filelifetime : 86400;

        // finally send the file
        send_stored_file($file, $lifetime, 0, $forcedownload, $options);

    } else if ($filearea === 'submission_content' or $filearea === 'submission_attachment') {
        $itemid = (int)array_shift($args);
        if (!$workshop = $DB->get_record('workshop', array('id' => $cm->instance))) {
            return false;
        }
        if (!$submission = $DB->get_record('workshop_submissions', array('id' => $itemid, 'workshopid' => $workshop->id))) {
            return false;
        }

        // make sure the user is allowed to see the file
        if (empty($submission->example)) {
            if ($USER->id != $submission->authorid) {
                if ($submission->published == 1 and $workshop->phase == 50
                        and has_capability('mod/workshop:viewpublishedsubmissions', $context)) {
                    // Published submission, we can go (workshop does not take the group mode
                    // into account in this case yet).
                } else if (!$DB->record_exists('workshop_assessments', array('submissionid' => $submission->id, 'reviewerid' => $USER->id))) {
                    if (!has_capability('mod/workshop:viewallsubmissions', $context)) {
                        send_file_not_found();
                    } else {
                        $gmode = groups_get_activity_groupmode($cm, $course);
                        if ($gmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context)) {
                            // check there is at least one common group with both the $USER
                            // and the submission author
                            $sql = "SELECT 'x'
FROM {workshop_submissions} s
JOIN {user} a ON (a.id = s.authorid)
JOIN {groups_members} agm ON (a.id = agm.userid)
JOIN {user} u ON (u.id = ?)
JOIN {groups_members} ugm ON (u.id = ugm.userid)
WHERE s.example = 0 AND s.workshopid = ? AND s.id = ? AND agm.groupid = ugm.groupid";
                            $params = array($USER->id, $workshop->id, $submission->id);
                            if (!$DB->record_exists_sql($sql, $params)) {
                                send_file_not_found();
                            }
                        }
                    }
                }
            }
        }

        $fs = get_file_storage();
        $relativepath = implode('/', $args);
        $fullpath = "/$context->id/mod_workshop/$filearea/$itemid/$relativepath";
        if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
            return false;
        }
        // finally send the file
        // these files are uploaded by students - forcing download for security reasons
        send_stored_file($file, 0, 0, true, $options);
    }

    return false;
}

/**
* File browsing support for workshop file areas
*
* @package mod_workshop
* @category files
*
* @param file_browser $browser
* @param array $areas
* @param stdClass $course
* @param stdClass $cm
* @param stdClass $context
* @param string $filearea
* @param int $itemid
* @param string $filepath
* @param string $filename
* @return file_info instance or null if not found
*/
function workshop_get_file_info($browser, $areas, $course, $cm, $context, $filearea, $itemid, $filepath, $filename) {
    global $CFG, $DB, $USER;
    /** @var array internal cache for author names */
    static $submissionauthors = array();

    $fs = get_file_storage();

    if ($filearea === 'submission_content' or $filearea === 'submission_attachment') {

        if (!has_capability('mod/workshop:viewallsubmissions', $context)) {
            return null;
        }

        if (is_null($itemid)) {
            // no itemid (submissionid) passed, display the list of all submissions
            require_once($CFG->dirroot . '/mod/workshop/fileinfolib.php');
            return new workshop_file_info_submissions_container($browser, $course, $cm, $context, $areas, $filearea);
        }

        // make sure the user can see the particular submission in separate groups mode
        $gmode = groups_get_activity_groupmode($cm, $course);

        if ($gmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context)) {
            // check there is at least one common group with both the $USER
            // and the submission author (this is not expected to be a frequent
            // usecase so we can live with pretty ineffective one query per submission here...)
            $sql = "SELECT 'x'
FROM {workshop_submissions} s
JOIN {user} a ON (a.id = s.authorid)
JOIN {groups_members} agm ON (a.id = agm.userid)
JOIN {user} u ON (u.id = ?)
JOIN {groups_members} ugm ON (u.id = ugm.userid)
WHERE s.example = 0 AND s.workshopid = ? AND s.id = ? AND agm.groupid = ugm.groupid";
            $params = array($USER->id, $cm->instance, $itemid);
            if (!$DB->record_exists_sql($sql, $params)) {
                return null;
            }
        }

        // we are inside some particular submission container

        $filepath = is_null($filepath) ? '/' : $filepath;
        $filename = is_null($filename) ? '.' : $filename;

        if (!$storedfile = $fs->get_file($context->id, 'mod_workshop', $filearea, $itemid, $filepath, $filename)) {
            if ($filepath === '/' and $filename === '.') {
                $storedfile = new virtual_root_file($context->id, 'mod_workshop', $filearea, $itemid);
            } else {
                // not found
                return null;
            }
        }

        // Checks to see if the user can manage files or is the owner.
        // TODO MDL-33805 - Do not use userid here and move the capability check above.
        if (!has_capability('moodle/course:managefiles', $context) && $storedfile->get_userid() != $USER->id) {
            return null;
        }

        // let us display the author's name instead of itemid (submission id)

        if (isset($submissionauthors[$itemid])) {
            $topvisiblename = $submissionauthors[$itemid];

        } else {

            $sql = "SELECT s.id, u.lastname, u.firstname
FROM {workshop_submissions} s
JOIN {user} u ON (s.authorid = u.id)
WHERE s.example = 0 AND s.workshopid = ?";
            $params = array($cm->instance);
            $rs = $DB->get_recordset_sql($sql, $params);

            foreach ($rs as $submissionauthor) {
                $title = s(fullname($submissionauthor)); // this is generally not unique...
                $submissionauthors[$submissionauthor->id] = $title;
            }
            $rs->close();

            if (!isset($submissionauthors[$itemid])) {
                // should not happen
                return null;
            } else {
                $topvisiblename = $submissionauthors[$itemid];
            }
        }

        $urlbase = $CFG->wwwroot . '/pluginfile.php';
        // do not allow manual modification of any files!
        return new file_info_stored($browser, $context, $storedfile, $urlbase, $topvisiblename, true, true, false, false);
    }

    if ($filearea == 'instructauthors' or $filearea == 'instructreviewers') {
        // always only itemid 0

        $filepath = is_null($filepath) ? '/' : $filepath;
        $filename = is_null($filename) ? '.' : $filename;

        $urlbase = $CFG->wwwroot.'/pluginfile.php';
        if (!$storedfile = $fs->get_file($context->id, 'mod_workshop', $filearea, 0, $filepath, $filename)) {
            if ($filepath === '/' and $filename === '.') {
                $storedfile = new virtual_root_file($context->id, 'mod_workshop', $filearea, 0);
            } else {
                // not found
                return null;
            }
        }
        return new file_info_stored($browser, $context, $storedfile, $urlbase, $areas[$filearea], false, true, true, false);
    }
}

////////////////////////////////////////////////////////////////////////////////
// Navigation API //
////////////////////////////////////////////////////////////////////////////////

/**
* Extends the global navigation tree by adding workshop nodes if there is a relevant content
*
* This can be called by an AJAX request so do not rely on $PAGE as it might not be set up properly.
*
* @param navigation_node $navref An object representing the navigation tree node of the workshop module instance
* @param stdClass $course
* @param stdClass $module
* @param cm_info $cm
*/
function workshop_extend_navigation(navigation_node $navref, stdclass $course, stdclass $module, cm_info $cm) {
    global $CFG;

    if (has_capability('mod/workshop:submit', get_context_instance(CONTEXT_MODULE, $cm->id))) {
        $url = new moodle_url('/mod/workshop/submission.php', array('cmid' => $cm->id));
        $mysubmission = $navref->add(get_string('mysubmission', 'workshop'), $url);
        $mysubmission->mainnavonly = true;
    }
}

/**
* Extends the settings navigation with the Workshop settings

* This function is called when the context for the page is a workshop module. This is not called by AJAX
* so it is safe to rely on the $PAGE.
*
* @param settings_navigation $settingsnav {@link settings_navigation}
* @param navigation_node $workshopnode {@link navigation_node}
*/
function workshop_extend_settings_navigation(settings_navigation $settingsnav, navigation_node $workshopnode=null) {
    global $PAGE;

    //$workshopobject = $DB->get_record("workshop", array("id" => $PAGE->cm->instance));

    if (has_capability('mod/workshop:editdimensions', $PAGE->cm->context)) {
        $url = new moodle_url('/mod/workshop/editform.php', array('cmid' => $PAGE->cm->id));
        $workshopnode->add(get_string('editassessmentform', 'workshop'), $url, settings_navigation::TYPE_SETTING);
    }
    if (has_capability('mod/workshop:allocate', $PAGE->cm->context)) {
        $url = new moodle_url('/mod/workshop/allocation.php', array('cmid' => $PAGE->cm->id));
        $workshopnode->add(get_string('allocate', 'workshop'), $url, settings_navigation::TYPE_SETTING);
    }
}

/**
* Return a list of page types
* @param string $pagetype current page type
* @param stdClass $parentcontext Block's parent context
* @param stdClass $currentcontext Current context of block
*/
function workshop_page_type_list($pagetype, $parentcontext, $currentcontext) {
    $module_pagetype = array('mod-workshop-*'=>get_string('page-mod-workshop-x', 'workshop'));
    return $module_pagetype;
}

////////////////////////////////////////////////////////////////////////////////
// Calendar API //
////////////////////////////////////////////////////////////////////////////////

/**
* Updates the calendar events associated to the given workshop
*
* @param stdClass $workshop the workshop instance record
* @param int $cmid course module id
*/
function workshop_calendar_update(stdClass $workshop, $cmid) {
    global $DB;

    // get the currently registered events so that we can re-use their ids
    $currentevents = $DB->get_records('event', array('modulename' => 'workshop', 'instance' => $workshop->id));

    // the common properties for all events
    $base = new stdClass();
    $base->description = format_module_intro('workshop', $workshop, $cmid, false);
    $base->courseid = $workshop->course;
    $base->groupid = 0;
    $base->userid = 0;
    $base->modulename = 'workshop';
    $base->eventtype = 'pluginname';
    $base->instance = $workshop->id;
    $base->visible = instance_is_visible('workshop', $workshop);
    $base->timeduration = 0;

    if ($workshop->submissionstart) {
        $event = clone($base);
        $event->name = get_string('submissionstartevent', 'mod_workshop', $workshop->name);
        $event->timestart = $workshop->submissionstart;
        if ($reusedevent = array_shift($currentevents)) {
            $event->id = $reusedevent->id;
        } else {
            // should not be set but just in case
            unset($event->id);
        }
        // update() will reuse a db record if the id field is set
        $eventobj = new calendar_event($event);
        $eventobj->update($event, false);
    }

    if ($workshop->submissionend) {
        $event = clone($base);
        $event->name = get_string('submissionendevent', 'mod_workshop', $workshop->name);
        $event->timestart = $workshop->submissionend;
        if ($reusedevent = array_shift($currentevents)) {
            $event->id = $reusedevent->id;
        } else {
            // should not be set but just in case
            unset($event->id);
        }
        // update() will reuse a db record if the id field is set
        $eventobj = new calendar_event($event);
        $eventobj->update($event, false);
    }

    if ($workshop->assessmentstart) {
        $event = clone($base);
        $event->name = get_string('assessmentstartevent', 'mod_workshop', $workshop->name);
        $event->timestart = $workshop->assessmentstart;
        if ($reusedevent = array_shift($currentevents)) {
            $event->id = $reusedevent->id;
        } else {
            // should not be set but just in case
            unset($event->id);
        }
        // update() will reuse a db record if the id field is set
        $eventobj = new calendar_event($event);
        $eventobj->update($event, false);
    }

    if ($workshop->assessmentend) {
        $event = clone($base);
        $event->name = get_string('assessmentendevent', 'mod_workshop', $workshop->name);
        $event->timestart = $workshop->assessmentend;
        if ($reusedevent = array_shift($currentevents)) {
            $event->id = $reusedevent->id;
        } else {
            // should not be set but just in case
            unset($event->id);
        }
        // update() will reuse a db record if the id field is set
        $eventobj = new calendar_event($event);
        $eventobj->update($event, false);
    }

    // delete any leftover events
    foreach ($currentevents as $oldevent) {
        $oldevent = calendar_event::load($oldevent);
        $oldevent->delete();
    }
}
Something went wrong with that request. Please try again.