I am trying to make a webservice in moodle that can be called externally. The webservice makes an entry in the database table mdl_quiz. But the quiz does not show up on the front-end.
Here is my code of the externallib file:
global $CFG, $DB;
$params = self::validate_parameters(
self::create_quiz_parameters(),
['quiz' => $quiz]
);
foreach ($params['quiz'] as $quiz) {
$courseid = $quiz['courseid'];
$quizname = $quiz['quizname'];
$intro = $quiz['intro'];
$attempts = $quiz['attempts'];
$timeopen = $quiz['timeopen'];
$timeclose = $quiz['timeclose'];
$quiz = new stdClass();
$quiz->course = $courseid;
$quiz->name = $quizname;
$quiz->timeopen = $timeopen;
$quiz->timeclose = $timeclose;
$quiz->attempts = $attempts;
$quiz->intro = $intro;
$rqa = $DB->insert_record('quiz', $quiz);
if (isset($rqa)) {
$moduleid = $DB->get_field('modules', 'id', ['name' => 'quiz'], MUST_EXIST);
$instanceid = 50;
$sectionid = 1;
$newcm = new stdClass();
$newcm->course = $courseid;
$newcm->module = $moduleid;
$newcm->section = $sectionid;
$newcm->added = time();
$newcm->instance = $instanceid;
$newcm->visible = 1;
$newcm->groupmode = 0;
$newcm->groupingid = 0;
$newcm->groupmembersonly = 0;
$newcm->showdescription = 0;
$cmid = $DB->insert_record('course_modules', $newcm);
}
}
You should use add_moduleinfo() instead of inserting records manually. This will do most of the work for you.
For an example see Create Moodle activities programmatically
Related
I am unable to enter multiple data, it enter only single data. I have tried using for loop and then entering data, using 3 user and 2 task, there is an error previously offset.
public function add($postData)
{
// dd($postData);
$c = count($postData['user_name']);
$t = count($postData['task_name']);
for ($i = 0; $i < $c; $i++) {
$user_name = $postData['user_name'][$i];
$user_email = $postData['user_email'][$i];
$data['insert']['user_name'] = $user_name;
$data['insert']['user_email'] = $user_email;
}
for ($j = 0; $j < $t; $j++) {
$task_name = $postData['task_name'][$j];
$data['insert']['task_name'] = $task_name;
}
$data['insert']['name'] = $postData['name'];
$data['insert']['description'] = $postData['description'];
$data['insert']['customer_name'] = $postData['customer_name'];
$data['insert']['billing_method'] = $postData['billing_method'];
$data['insert']['dt_created'] = DT;
$data['table'] = PROJECT;
$result = $this->insertRecord($data);
if ($result == true) {
$response['status'] = 'success';
$response['message'] = 'Project created';
} else {
$response['status'] = 'danger';
$response['message'] = DEFAULT_MESSAGE;
}
return $response;
}
As Per lack of question details attached, I am supposing that you want to insert multiple task entry with project name, description etc.
Here is updated code:
<?php
// dd($postData);
$username = $postData['username'];
$user_email = $postData['user_email'];
$task_name = $postData['task_name'];
foreach ($username as $key => $value) {
$data['insert']['name'] = $postData['name'];
$data['insert']['description'] = $postData['description'];
$data['insert']['customer_name'] = $postData['customer_name'];
$data['insert']['billing_method'] = $postData['billing_method'];
$data['insert']['username'] = $value;
$data['insert']['user_email'] = $user_email[$key];
$data['insert']['task_name'] = $task_name[$key];
$data['insert']['dt_created'] = DT;
$data['table'] = PROJECT;
$result = $this->insertRecord($data);
}
I currently have a site that uploads a CSV and displays it in a preview table as a form that can be edited (if any CSV values are wrong).
It works great, but I need to insert this into a database table with any edits that are made within the form. I have an array that puts the uploaded CSV into this form, but now I think I need to create a new CSV from this form and submit THAT CSV into the database. I've seen some tutorials but I'm unclear on how to do it from this table/form.
Here is the code for the existing preview form:
if(isset($_POST['preview']))
{
ini_set('auto_detect_line_endings', true);
$file = $_FILES["file"]["tmp_name"];
$handle = fopen($file, "r");
$maxPreviewRows = PHP_INT_MAX; // this will be ~2 billion on 32-bit system, or ~9 quintillion on 64-bit system
$hasHeaderRow = true;
?><form><?
echo '<table>';
/*WE WILL NEED TO QA CONDITIONS AND HIGHLIGHT IN RED HERE. ALSO NEED BORDER STYLINGS*/
if ($hasHeaderRow) {
$headerRow = fgetcsv($handle);
echo '<thead><tr>';
foreach($headerRow as $value) {
echo "<th>$value</th>";
}
echo '</tr></thead>';
}
echo '<tbody>';
$rowCount = 0;
while ($row = fgetcsv($handle)) {
echo '<tr>';
foreach($row as $value) {
echo "<td>$value</td>";
}
echo '</tr>';
if (++$rowCount > $maxPreviewRows) {
break;
}
}
echo '</tbody></table>';
}
?></form>
Since this doesn't have values for each field in the form, I'm unsure of the best way to create a CSV from this and insert it into my staging table.
UPDATE - the below code is my first attempt at using my CSV upload array
if(isset($_POST['submit']))
{
$file = $_FILES["file"]["tmp_name"];
$handle = fopen($file, "r");
$filesop = fgetcsv($handle, 0, ",");
while (($filesop = fgetcsv($handle)) !== FALSE) {
$coldata = array();
$coldata["orderNumber"] = $filesop[0];
$coldata["workOrderPacket"] = $filesop[1];
$coldata["workOrderNum"] = $filesop[2];
$coldata["lowSideMIUNumArriv"] = $filesop[3];
$coldata["lowSideMIUNumDepart"] = $filesop[4];
$coldata["highSideMIUNumArriv"] = $filesop[5];
$coldata["highSideMIUNumDepart"] = $filesop[6];
$coldata["accountNum"] = $filesop[7];
$coldata["filler1"] = $filesop[8];
$coldata["address"] = $filesop[9];
$coldata["filler2"] = $filesop[10];
$coldata["date"] = $filesop[11];
$coldata["utility"] = $filesop[12];
$coldata["serialNumber"] = $filesop[13];
$coldata["serviceName"] = $filesop[14];
$coldata["locationNotes"] = $filesop[15];
$coldata["locationComments"] = $filesop[16];
$coldata["filler3"] = $filesop[17];
$coldata["WaterValveArriv"] = $filesop[18];
$coldata["WaterValveDepart"] = $filesop[19];
$coldata["meterSize"] = $filesop[20];
$coldata["meterType"] = $filesop[21];
$coldata["manufacturer"] = $filesop[22];
$coldata["registration"] = $filesop[23];
$coldata["technician"] = $filesop[24];
$coldata["linePressurePSI"] = $filesop[25];
$coldata["filler4"] = $filesop[26];
$coldata["filler5"] = $filesop[27];
$coldata["lowSideRrBefore"] = $filesop[28];
$coldata["highSideRrBefore"] = $filesop[29];
$coldata["lowSideRrAfter"] = $filesop[30];
$coldata["highSideRrAfter"] = $filesop[31];
$coldata["vgOxygen"] = $filesop[32];
$coldata["vgCombustGas"] = $filesop[33];
$coldata["vgCarbonMon"] = $filesop[34];
$coldata["vgHydroSulf"] = $filesop[35];
$coldata["test1TestRateGPM"] = $filesop[36];
$coldata["test1MeterVol"] = $filesop[37];
$coldata["test1TesterVol"] = $filesop[38];
$coldata["test1Accuracy"] = $filesop[39];
$coldata["test1CorrectAcc"] = $filesop[40];
$coldata["test2TestRateGPM"] = $filesop[41];
$coldata["test2MeterVol"] = $filesop[42];
$coldata["test2TesterVol"] = $filesop[43];
$coldata["test2Accuracy"] = $filesop[44];
$coldata["test2CorrectAcc"] = $filesop[45];
$coldata["test3TestRateGPM"] = $filesop[46];
$coldata["test3MeterVol"] = $filesop[47];
$coldata["test3TesterVol"] = $filesop[48];
$coldata["test3Accuracy"] = $filesop[49];
$coldata["test3CorrectAcc"] = $filesop[50];
$coldata["test4TestRateGPM"] = $filesop[51];
$coldata["test4MeterVol"] = $filesop[52];
$coldata["test4TesterVol"] = $filesop[53];
$coldata["test4Accuracy"] = $filesop[54];
$coldata["test4CorrectAcc"] = $filesop[55];
$coldata["test5TestRateGPM"] = $filesop[56];
$coldata["test5MeterVol"] = $filesop[57];
$coldata["test5TesterVol"] = $filesop[58];
$coldata["test5Accuracy"] = $filesop[59];
$coldata["test5CorrectAcc"] = $filesop[60];
$coldata["test6TestRateGPM"] = $filesop[61];
$coldata["test6MeterVol"] = $filesop[62];
$coldata["test6TesterVol"] = $filesop[63];
$coldata["test6Accuracy"] = $filesop[64];
$coldata["test6CorrectAcc"] = $filesop[65];
$coldata["test7TestRateGPM"] = $filesop[66];
$coldata["test7MeterVol"] = $filesop[67];
$coldata["test7TesterVol"] = $filesop[68];
$coldata["test7Accuracy"] = $filesop[69];
$coldata["test7CorrectAcc"] = $filesop[70];
$coldata["test8TestRateGPM"] = $filesop[71];
$coldata["test8MeterVol"] = $filesop[72];
$coldata["test8TesterVol"] = $filesop[73];
$coldata["test8Accuracy"] = $filesop[74];
$coldata["test8CorrectAcc"] = $filesop[75];
$coldata["inletValveLoc"] = $filesop[76];
$coldata["inletValveSize"] = $filesop[77];
$coldata["InletValveType"] = $filesop[78];
$coldata["inletValveCond"] = $filesop[79];
$coldata["outletValveLoc"] = $filesop[80];
$coldata["outletValveSize"] = $filesop[81];
$coldata["outletValveType"] = $filesop[82];
$coldata["outletValveCond"] = $filesop[83];
$coldata["bypassValveLoc"] = $filesop[84];
$coldata["bypassValveSize"] = $filesop[85];
$coldata["bypassValveType"] = $filesop[86];
$coldata["bypassValveCond"] = $filesop[87];
$coldata["vaultLength"] = $filesop[88];
$coldata["vaultWidth"] = $filesop[89];
$coldata["vaultHeight"] = $filesop[90];
$coldata["meterLocation"] = $filesop[91];
$coldata["testPort"] = $filesop[92];
$coldata["testPortInstalled"] = $filesop[93];
$coldata["testPortSize"] = $filesop[94];
$coldata["picture"] = $filesop[95];
$coldata["timeTested"] = $filesop[96];
$coldata["comments"] = $filesop[97];
$coldata["testResults"] = $filesop[98];
$coldata["retest"] = $filesop[99];
$coldata["test1TestRateGPM2"] = $filesop[100];
$coldata["test1MeterVol2"] = $filesop[101];
$coldata["test1TesterVol2"] = $filesop[102];
$coldata["test1Accuracy2"] = $filesop[103];
$coldata["test1CorrectAcc2"] = $filesop[104];
$coldata["test2TestRateGPM2"] = $filesop[105];
$coldata["test2MeterVol2"] = $filesop[106];
$coldata["test2TesterVol2"] = $filesop[107];
$coldata["test2Accuracy2"] = $filesop[108];
$coldata["test2CorrectAcc2"] = $filesop[109];
$coldata["test3TestRateGPM2"] = $filesop[110];
$coldata["test3MeterVol2"] = $filesop[111];
$coldata["test3TesterVol2"] = $filesop[112];
$coldata["test3Accuracy2"] = $filesop[113];
$coldata["test3CorrectAcc2"] = $filesop[114];
$coldata["test4TestRateGPM2"] = $filesop[115];
$coldata["test4MeterVol2"] = $filesop[116];
$coldata["test4TesterVol2"] = $filesop[117];
$coldata["test4Accuracy2"] = $filesop[118];
$coldata["test4CorrectAcc2"] = $filesop[119];
$coldata["test5TestRateGPM2"] = $filesop[120];
$coldata["test5MeterVol2"] = $filesop[121];
$coldata["test5TesterVol2"] = $filesop[122];
$coldata["test5Accuracy2"] = $filesop[123];
$coldata["test5CorrectAcc2"] = $filesop[124];
$coldata["test6TestRateGPM2"] = $filesop[125];
$coldata["test6MeterVol2"] = $filesop[126];
$coldata["test6TesterVol2"] = $filesop[127];
$coldata["test6Accuracy2"] = $filesop[128];
$coldata["test6CorrectAcc2"] = $filesop[129];
$coldata["test7TestRateGPM2"] = $filesop[130];
$coldata["test7MeterVol2"] = $filesop[131];
$coldata["test7TesterVol2"] = $filesop[132];
$coldata["test7Accuracy2"] = $filesop[133];
$coldata["test7CorrectAcc2"] = $filesop[134];
$coldata["test8TestRateGPM2"] = $filesop[135];
$coldata["test8MeterVol2"] = $filesop[136];
$coldata["test8TesterVol2"] = $filesop[137];
$coldata["test8Accuracy2"] = $filesop[138];
$coldata["test8CorrectAcc2"] = $filesop[139];
$coldata["filler6"] = $filesop[140];
$coldata["filler7"] = $filesop[141];
$coldata["filler8"] = $filesop[142];
$coldata["filler9"] = $filesop[143];
$coldata["filler10"] = $filesop[144];
$coldata["filler11"] = $filesop[145];
$coldata["filler12"] = $filesop[146];
$coldata["serviceAddCorrect"] = $filesop[147];
$coldata["serviceLoccCorrect"] = $filesop[148];
$coldata["meterNumberCorrect"] = $filesop[149];
$coldata["lowRegisterCorrect"] = $filesop[150];
$coldata["lowRegisterType"] = $filesop[151];
$coldata["lowRegisterSize"] = $filesop[152];
$coldata["highRegisterCorrect"] = $filesop[153];
$coldata["highRegisterSize"] = $filesop[154];
$coldata["highRegisterType"] = $filesop[155];
$coldata["meterLidType"] = $filesop[156];
$coldata["meterLidMaterial"] = $filesop[157];
$coldata["lidFit"] = $filesop[158];
$coldata["lidCondition"] = $filesop[159];
$coldata["antennaeMountCor"] = $filesop[160];
$coldata["antennaePosition"] = $filesop[161];
$coldata["registerCondition"] = $filesop[162];
$coldata["MIUwire"] = $filesop[163];
$coldata["registerPinArriv"] = $filesop[164];
$coldata["registerPinDepart"] = $filesop[165];
$coldata["vaultType"] = $filesop[166];
$coldata["vaultSafe"] = $filesop[167];
$coldata["vaultLadder"] = $filesop[168];
$coldata["workOrderType"] = $filesop[169];
$coldata["workOrderLocation"] = $filesop[170];
$coldata["completeMeter"] = $filesop[171];
$coldata["ume"] = $filesop[172];
$coldata["discChamber"] = $filesop[173];
$coldata["turbineChamber"] = $filesop[174];
$coldata["automaticValve"] = $filesop[175];
$coldata["strainer"] = $filesop[176];
$coldata["lowRegister"] = $filesop[177];
$coldata["highRegister"] = $filesop[178];
$coldata["miu"] = $filesop[179];
$coldata["antennae"] = $filesop[180];
$coldata["calibrationVane"] = $filesop[181];
$coldata["meterLeakRepaired"] = $filesop[182];
$coldata["workOrderType2"] = $filesop[183];
$coldata["strainerPresent"] = $filesop[184];
$coldata["apparentLeak"] = $filesop[185];
$coldata["leakLocation"] = $filesop[186];
$coldata["leakType"] = $filesop[187];
$coldata["locateBypassValve"] = $filesop[188];
$coldata["locateInletValve"] = $filesop[189];
$coldata["locateOutletValve"] = $filesop[190];
$coldata["PreformShutdown"] = $filesop[191];
$coldata["turnOnWater"] = $filesop[192];
$coldata["repairLid"] = $filesop[193];
$coldata["repairVault"] = $filesop[194];
$coldata["repairLadder"] = $filesop[195];
$coldata["repairLeak"] = $filesop[196];
$coldata["repairBypassValve"] = $filesop[197];
$coldata["repairInletValve"] = $filesop[198];
$coldata["repairOutletValve"] = $filesop[199];
$coldata["latitude"] = $filesop[200];
$coldata["longitude"] = $filesop[201];
$coldata["onsiteSurveyTestCost"] = $filesop[202];
$coldata["onsiteSurveyTestRepairCost"] = $filesop[203];
$coldata["offsiteSurveyTestCost"] = $filesop[204];
$coldata["offsiteSurveyTestRepairCost"] = $filesop[205];
$coldata["onsiteTestOnlyCost"] = $filesop[206];
$coldata["onsiteTestRepairOnlyCost"] = $filesop[207];
$coldata["onsiteRepairOnly"] = $filesop[208];
$coldata["testPort2"] = $filesop[209];
$coldata["repairCompleteMeterReplacement"] = $filesop[210];
$coldata["repairCompleteMeterReplacementLaborCost"] = $filesop[211];
$coldata["umeCost"] = $filesop[212];
$coldata["umeLaborCost"] = $filesop[213];
$coldata["rotatingLowSideDiskChamber"] = $filesop[214];
$coldata["rotatingLowSideDiskChamberLaborCost"] = $filesop[215];
$coldata["turbineChamberCost"] = $filesop[216];
$coldata["turbineChamberLaborCost"] = $filesop[217];
$coldata["automaticValveCost"] = $filesop[218];
$coldata["automaticValveLaborCost"] = $filesop[219];
$coldata["strainerCost"] = $filesop[220];
$coldata["strainerLaborCost"] = $filesop[221];
$coldata["lowRegisterCost"] = $filesop[222];
$coldata["lowRegisterLaborCost"] = $filesop[223];
$coldata["highRegisterCost"] = $filesop[224];
$coldata["highRegisterLaborCost"] = $filesop[225];
$coldata["miuCost"] = $filesop[226];
$coldata["miuLaborCost"] = $filesop[227];
$coldata["totalCost"] = $filesop[228];
I want to show data from database: for every id_grup has many lapangan(court)
$groups_resource = Groups::all();
$groups = [];
foreach($groups_resource as $group)
{
$g = new Groups();
$g->id_group = "Group_".$group['id_group'];
$g->name = $group['nama'];
$g->expanded = true;
$g->eventHeight = 25;
$g->children = array();
$groups[] = $g;
$lapangan_resource = Lapangan::with('groups')->orderBy('nama')->get();
foreach($lapangan_resource as $lapangan)
{
$l = new Lapangan();
$l->id_lapangan = $lapangan['id_lapangan'];
$l->name = $lapangan['nama_lapangan'];
$g->children[] = $l;
}
}
return json_encode($groups);
output for above code
[{"id_group":"Group_1","name":"Lapangan Badminton","expanded":true,"eventHeight":25,"children":[]},{"id_group":"Group_2","name":"Lapangan Tenis","expanded":true,"eventHeight":25,"children":[]}]
There is no value for children which might be like this.
[{"id":"group_1","name":"Indoor","expanded":true,"eventHeight":25,"children":[
{"id":"1","name":"Court 1"},
{"id":"2","name":"Court 2"},
{"id":"3","name":"Court 3"},
{"id":"4","name":"Court 4"}]},"id":"group_2","name":"Outdoor","expanded":true,"eventHeight":25,"children":[
{"id":"11","name":"Court 5"},
{"id":"12","name":"Court 6"},
{"id":"13","name":"Court 7"},
{"id":"14","name":"Court 8"}]}]
You are using wrong array braces. You shouldn't first initialize the children property of a group instead of that you can do it like this:
foreach($groups_resource as $group)
{
$g = new Groups();
$g->id_group = "Group_".$group['id_group'];
$g->name = $group['nama'];
$g->expanded = true;
$g->eventHeight = 25;
$l_arr = [];
$lapangan_resource = Lapangan::with('groups')->orderBy('nama')->get();
foreach($lapangan_resource as $lapangan)
{
$l = new Lapangan();
$l->id_lapangan = $lapangan['id_lapangan'];
$l->name = $lapangan['nama_lapangan'];
$l_arr[] = $l;
}
$g->children = $l_arr;
$groups[] = $g;
}
return json_encode($groups);
Hope this helps!
I have one problem with my php code. I create the campaign and create audiences tag (remarketing => website visitors => code) from PHP.
The problem is when I try include audience to campaign. Code whose I'm using:
github example
My code view like this:
$campaignService = $user->GetService('CampaignService', ADWORDS_VERSION);
$adGroupId = $group_id;
$operations = array();
$campaign = new Campaign();
$campaign->id = $google_data['google_id'];
$campaign->advertisingChannelType = 'DISPLAY';
$networkSetting = new NetworkSetting();
$networkSetting->targetGoogleSearch = false;
$networkSetting->targetSearchNetwork = false;
$networkSetting->targetContentNetwork = true;
$campaign->networkSetting = $networkSetting;
$operation = new CampaignOperation();
$operation->operand = $campaign;
$operation->operator = 'SET';
$operations[] = $operation;
$result = $campaignService->mutate($operations);
$return_array['id'] = $result->value[0]->id;
$userListService = $user->GetService('AdwordsUserListService', ADWORDS_VERSION);
$conversionTrackerService =
$user->GetService('ConversionTrackerService', ADWORDS_VERSION);
$conversionType = new UserListConversionType();
$conversionType->name = $name . uniqid();
$userList = new BasicUserList();
$userList->name = $name . uniqid();
$userList->conversionTypes = array($conversionType);
$userList->status = 'OPEN';
$userList->membershipLifeSpan = $day;
$operation = new UserListOperation();
$operation->operand = $userList;
$operation->operator = 'ADD';
$operations = array($operation);
$result = $userListService->mutate($operations);
$userList = $result->value[0];
$static_user_id = $userList->id;
// print_r($userList->id);
// exit;
sleep(1);
$selector = new Selector();
$selector->fields = array('Id');
$selector->predicates[] =
new Predicate('Id', 'IN', array($userList->conversionTypes[0]->id));
$page = $conversionTrackerService->get($selector);
$conversionTracker = $page->entries[0];
$tag = $conversionTracker->snippet;
$audience_id = $userList->conversionTypes[0]->id;
$campaignId = $return_array['id'];
$adGroupService = $user->GetService('AdGroupService', ADWORDS_VERSION);
$operations = array();
$adGroup = new AdGroup();
$adGroup->id = $google_data['google_group_id'];
$adGroup->campaignId = $campaignId;
$targetingSetting = new TargetingSetting();
$targetingSetting->details[] = new TargetingSettingDetail('PLACEMENT', false);
$adGroup->settings[] = $targetingSetting;
$operation = new AdGroupOperation();
$operation->operand = $adGroup;
$operation->operator = 'SET';
$operations[] = $operation;
$result = $adGroupService->mutate($operations);
$return_array['id_group'] = $result->value[0]->id;
$adGroupId = $return_array['id_group'];
$adGroupCriterionService = $user->GetService('AdGroupCriterionService', ADWORDS_VERSION);
$criterionUserList = new CriterionUserList();
$criterionUserList->id = $static_user_id;
$criterionUserList->type = "USER_LIST";
$operations = array();
$adGroupCriterion = new BiddableAdGroupCriterion();
$adGroupCriterion->adGroupId = $adGroupId;
$adGroupCriterion->criterion = $criterionUserList;
$adGroupCriteria[] = $adGroupCriterion;
$operation = new AdGroupCriterionOperation();
$operation->operand = $adGroupCriterion;
$operation->operator = 'SET';
$operations[] = $operation;
$result = $adGroupCriterionService->mutate($operations);
$return_array['remarketing_email'] = $result->value[0]->criterion->id;
And when I running this code, I've got output:
An error has occurred:215 [EntityNotFound.INVALID_ID # operations[0].operand.criterion.id; trigger:'CriterionId{id=414978678}']
I need to upload files and folders into a course in moodle from a zip file, I have been searching and I found how to upload files. I try to upload, and the files are uploaded correctly into the database and in the file repository, but this files are not showed in the course when I enter to the course.
The code below is what I trying
$packer = get_file_packer('application/zip');
$files = $packer->extract_to_pathname($archivo_zip, $carpeta_unzip );
foreach($files as $path => $status){
$fs = get_file_storage();
$context = context_course::instance($courseid);
$filename = basename($path);
$path_directory = "/" . str_replace($filename, "", $path);
$author = $DB->get_record('user', array('id'=>$userid ), '*', MUST_EXIST);
$file_record = new stdClass;
$file_record->component = 'mod_folder'; //mod_resource
$file_record->contextid = $context->id;
$file_record->userid = $userid ;
$file_record->filearea = 'content'; //draft, attachment
$file_record->filename = $filename;
$file_record->filepath = $path_directory;
$file_record->itemid = 0;
$file_record->author = fullname($author);
$file_record->license = $CFG->sitedefaultlicense;
$file_record->source = $filename;
//$file_record->timecreated = time();
//$file_record->timemodified = time();
$existingfile = $fs->file_exists($file_record->contextid, $file_record->component, $file_record->filearea,
$file_record->itemid, $file_record->filepath, $file_record->filename);
if ($existingfile) {
//throw new file_exception('filenameexist');
} else {
$stored_file = $fs->create_file_from_pathname($file_record, $path_upload);
}
}
I try to upload the files manually through the website and I've noticed that the folders ara created in another table called mdl_folder or in the table called mdl_file, but i don't know how do that and the best way to create and relate folders with files programatically for then displayed in the website well.
So if anyone knows how to do it or have any examples or documentation that may be useful, it would be helpful.
Thanks in advance.
I found a solution that works for me, I don't know if it is the most appropriate or not, if someone can take a look and tell me if it is correct or not, or what changes could make would be grateful.
The solution i found is:
Create or get it back the folder who will contain the files
Upload the files
Code:
$packer = get_file_packer('application/zip');
$files = $packer->extract_to_pathname($archivo_zip, $carpeta_unzip );
foreach($files as $path => $status){
$fs = get_file_storage();
$folder = get_folder($courseid, 'Upload Test');
$filename = basename($path);
$path_directory = "/" . str_replace($filename, "", $path);
$author = $DB->get_record('user', array('id'=>$userid ), '*', MUST_EXIST);
$file_record = new stdClass;
$file_record->component = 'mod_folder'; //mod_resource
$file_record->contextid = $folder->id;
$file_record->userid = $userid ;
$file_record->filearea = 'content'; //draft, attachment
$file_record->filename = $filename;
$file_record->filepath = $path_directory;
$file_record->itemid = 0;
$file_record->author = fullname($author);
$file_record->license = $CFG->sitedefaultlicense;
$file_record->source = $filename;
//$file_record->timecreated = time();
//$file_record->timemodified = time();
$existingfile = $fs->file_exists($file_record->contextid, $file_record->component, $file_record->filearea,
$file_record->itemid, $file_record->filepath, $file_record->filename);
if ($existingfile) {
//throw new file_exception('filenameexist');
} else {
$stored_file = $fs->create_file_from_pathname($file_record, $path_upload);
}
}
And the function to create or get it back the folder is:
function get_folder($courseid, $resource_name) {
global $DB, $CFG;
//Comprobamos si la carpeta ya existe ya existe
$sql = "SELECT cm.id as cmid FROM {course_modules} cm, {folder} res
WHERE res.name = '" . $resource_name . "'
AND cm.course = " . $courseid . "
AND cm.instance = res.id";
if (! $coursemodule = $DB->get_record_sql($sql)) {
require_once($CFG->dirroot.'/course/lib.php');
echo "\tCreate new folder\n";
$course = $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST);
// get module id
$module = $DB->get_record('modules', array('name' => 'folder'), '*', MUST_EXIST);
// get course section
/*course_create_sections_if_missing($course->id, 0);
$modinfo = get_fast_modinfo($course->id);
$cw = $modinfo->get_section_info(0);
echo "section id: " . $cw->id;*/
$sectionid = $DB->get_record('course_sections', array('course' => $course->id, 'name' => 'Recursos'), '*', MUST_EXIST);
$folder_data = new stdClass();
$folder_data->course = $course->id;
$folder_data->name = $resource_name;
$folder_data->intro = '<p>'.$resource_name.'</p>';
$folder_data->introformat = 1;
$folder_data->revision = 1;
$folder_data->timemodified = time();
$folder_data->display = 0;
$folder_data->showexpanded = 1;
$folder_data->showdownloadfolder = 1;
$folder_id = $DB->insert_record('folder', $folder_data);
echo "folder id: " . $folder_id;
// add course module
$cm = new stdClass();
$cm->course = $courseid;
$cm->module = $module->id; // should be retrieved from mdl_modules
$cm->instance = $folder_id; // from mdl_resource
$cm->section = $sectionid->id; // from mdl_course_sections
$cm->visible = 1;
$cm->visibleold = 1;
$cm->showavailability = 1;
$cm->added = time();
$cmid = $DB->insert_record('course_modules', $cm);
// add module to course section so it'll be visible
if ($DB->record_exists('course_sections', array('course' => $courseid, 'section' => 1))) {
$sectionid = $DB->get_record('course_sections', array('course' => $courseid, 'section' => 1));
// if sequence is not empty, add another course_module id
if (!empty($sectionid->sequence)) {
$sequence = $sectionid->sequence . ',' . $cmid;
} else {
// if sequence is empty, add course_module id
$sequence = $cmid;
}
$course_section = new stdClass();
$course_section->id = $sectionid->id;
$course_section->course = $courseid;
$course_section->section = 1;
$course_section->sequence = $sequence;
$csid = $DB->update_record('course_sections', $course_section);
} else {
$sequence = $cmid;
$course_section = new stdClass();
$course_section->course = $courseid;
$course_section->section = 1;
$course_section->sequence = $sequence;
$csid = $DB->insert_record('course_sections', $course_section);
}
rebuild_course_cache($courseid, true);
// get context again, this time with all resources present
$context = get_folder($courseid, $resource_name);
return $context;
} else {
$context = context_module::instance($coursemodule->cmid);
return $context;
}
} // get_folder