Hello,
The best option to control content of "my" section and prevent users from changing settings is:
- Add in config.php this line:
$CFG->forcedefaultmymoodle = true;
Best regards,
Iban Cardona.
Showing posts with label moodle. Show all posts
Showing posts with label moodle. Show all posts
Tuesday, 25 July 2017
Thursday, 13 July 2017
Moodle: Change course name in breadcrumb
Hello,
If you want to modify the text of the a course in the breadcrumb you can do this (tested in Moodle 3.2):
Add this function in your file lib.php of your local plugin:
function local_yourlocalplugin_extend_navigation(global_navigation $nav) {
global $COURSE, $CFG;
if (isset($COURSE->id) && $COURSE->id > 0) {
$coursenode = $nav->find($COURSE->id, navigation_node::TYPE_COURSE);
if ($coursenode) {
$coursenode->text .= ' My extra text';
}
}
}
Best regards!
If you want to modify the text of the a course in the breadcrumb you can do this (tested in Moodle 3.2):
Add this function in your file lib.php of your local plugin:
function local_yourlocalplugin_extend_navigation(global_navigation $nav) {
global $COURSE, $CFG;
if (isset($COURSE->id) && $COURSE->id > 0) {
$coursenode = $nav->find($COURSE->id, navigation_node::TYPE_COURSE);
if ($coursenode) {
$coursenode->text .= ' My extra text';
}
}
}
Best regards!
Monday, 15 May 2017
Moodle & PHPUnit: Capture events
Hello,
If you want to tests events in Moodle using PHPUnit, the best method is:
public function test_creationg_event() {
$this->resetAfterTest();
$event_sink = $this->redirectEvents();
$course = $this->getDataGenerator()->create_course();
$events = $event_sink->get_events();
$event_sink->close();
$event = $events[0];
$this->assertInstanceOf('\core\event\course_created', $event);
}
Best regards!
If you want to tests events in Moodle using PHPUnit, the best method is:
public function test_creationg_event() {
$this->resetAfterTest();
$event_sink = $this->redirectEvents();
$course = $this->getDataGenerator()->create_course();
$events = $event_sink->get_events();
$event_sink->close();
$event = $events[0];
$this->assertInstanceOf('\core\event\course_created', $event);
}
Best regards!
Tuesday, 25 April 2017
Moodle: Block settings not shown for students
Hello,
If you want to disable (not shown) settings block for students in Moodle, you can do it changing the renderer in your theme. This code is valid only for themes not based on Boost.
Add this function in the core_renderer class of your theme:
public function block(block_contents $bc, $region) {
global $DB;
$idblock = isset($bc->attributes['id']) ? $bc->attributes['id'] : '';
$arr_aux = explode('inst', $idblock);
if (isset($arr_aux[1])) {
$block_instance = $DB->get_record('block_instances', array('id' => $arr_aux[1]));
$context_course = context_course::instance($this->page->course->id);
if (isset($block_instance->blockname) && $block_instance->blockname == 'settings') {
if (!has_capability('moodle/grade:viewall', $context_course)) {
return '';
}
}
}
return parent::block($bc, $region);
}
Best regards,
Iban Cardona.
If you want to disable (not shown) settings block for students in Moodle, you can do it changing the renderer in your theme. This code is valid only for themes not based on Boost.
Add this function in the core_renderer class of your theme:
public function block(block_contents $bc, $region) {
global $DB;
$idblock = isset($bc->attributes['id']) ? $bc->attributes['id'] : '';
$arr_aux = explode('inst', $idblock);
if (isset($arr_aux[1])) {
$block_instance = $DB->get_record('block_instances', array('id' => $arr_aux[1]));
$context_course = context_course::instance($this->page->course->id);
if (isset($block_instance->blockname) && $block_instance->blockname == 'settings') {
if (!has_capability('moodle/grade:viewall', $context_course)) {
return '';
}
}
}
return parent::block($bc, $region);
}
Best regards,
Iban Cardona.
Wednesday, 22 February 2017
Moodle: moodle_form inside module: Edit or new?
Hello,
Sometimes inside a custom Moodle module we need to know if we are editing or creating a new module (activity or resource) instance... Here the solution:
function definition() {
global $CFG, $DB;
$mform =& $this->_form;
if (is_numeric($this->_instance) && $this->_instance && $mymodule = $DB->get_record("mymodule", array("id"=>$this->_instance))) {
$mform->addElement('header', 'general', 'Editing');
} else {
$mform->addElement('header', 'general', 'Creating');
}
...
Best regards,
Iban Cardona.
Sometimes inside a custom Moodle module we need to know if we are editing or creating a new module (activity or resource) instance... Here the solution:
function definition() {
global $CFG, $DB;
$mform =& $this->_form;
if (is_numeric($this->_instance) && $this->_instance && $mymodule = $DB->get_record("mymodule", array("id"=>$this->_instance))) {
$mform->addElement('header', 'general', 'Editing');
} else {
$mform->addElement('header', 'general', 'Creating');
}
...
Best regards,
Iban Cardona.
Saturday, 7 January 2017
Moodle: Download exact commit from git
Hello,
If you want to manage a source code from Moodle of a specific commit, you need to do:
Best regards!
If you want to manage a source code from Moodle of a specific commit, you need to do:
- Install git: https://git-scm.com/book/en/v2/Getting-Started-Installing-Git
- Find the commit to download in https://github.com/moodle/moodle . In my case I found this: https://github.com/moodle/moodle/commit/89117976b8afd75c588b8b3908f763aab2edfb6a#diff-5bbd3ccd25214f9956eea7e9f714bc08
- Download the Moodle code: git clone https://github.com/moodle/moodle.git my_moodle
- Copy the ID of the commit: 89117976b8afd75c588b8b3908f763aab2edfb6a
- Checkout the commit:
- cd my_moodle
- git checkout 89117976b8afd75c588b8b3908f763aab2edfb6a
Best regards!
Wednesday, 30 March 2016
Moodle: Get courses recursively
Hello,
How to get all courses of a category recursively?
<?php
global $CFG;
require_once($CFG->dirroot . '/lib/coursecatlib.php');
$categoryid = 1;
$allcourses = coursecat::get($categoryid)->get_courses(array('recursive' => true));
How to get all courses of a hidden category?
<?php
global $CFG;
require_once($CFG->dirroot . '/lib/coursecatlib.php');
$categoryid = 1;
$allcourses = coursecat::get($categoryid, MUST_EXIST, true)->get_courses(array('recursive' => true));
Best regards!
How to get all courses of a category recursively?
<?php
global $CFG;
require_once($CFG->dirroot . '/lib/coursecatlib.php');
$categoryid = 1;
$allcourses = coursecat::get($categoryid)->get_courses(array('recursive' => true));
How to get all courses of a hidden category?
<?php
global $CFG;
require_once($CFG->dirroot . '/lib/coursecatlib.php');
$categoryid = 1;
$allcourses = coursecat::get($categoryid, MUST_EXIST, true)->get_courses(array('recursive' => true));
Best regards!
Wednesday, 10 February 2016
Moodle: Create zip file with all course resources
Hello,
How to create a zip file with all resource modules of a course:
<?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/>.
require_once('../../config.php');
$id = required_param('id', PARAM_INT);
$course = get_course($id);
if (!$course) {
die();
}
$context = context_course::instance($course->id);
require_login($course);
$filename = 'contents.zip';
$new_names = array();
// Get files resources
$query_resources = "SELECT {resource}.*
FROM {resource}, {course_modules}, {modules}
WHERE {course_modules}.instance = {resource}.id
AND {modules}.id = {course_modules}.module
AND {modules}.name = 'resource'
AND {resource}.course = ?
AND {course_modules}.course = ?";
$resources = $DB->get_records_sql($query_resources, array($course->id, $course->id));
foreach ($resources as $resource) {
$cm = get_coursemodule_from_instance('resource', $resource->id, $resource->course, false, MUST_EXIST);
$context_resource = context_module::instance($cm->id);
$fs = get_file_storage();
$resource_files = $fs->get_area_files($context_resource->id, 'mod_resource', 'content', 0, 'sortorder DESC, id ASC', false);
if (count($resource_files) < 1) continue;
$resource_file = reset($resource_files);
unset($resource_files);
$contenthash = $resource_file->get_contenthash();
$l1 = $contenthash[0].$contenthash[1];
$l2 = $contenthash[2].$contenthash[3];
$filedir = ((isset($CFG->filedir))) ? $CFG->filedir : $CFG->dataroot.'/filedir';
$path = "$filedir/$l1/$l2/$contenthash";
$new_names['/'.$resource->name.'/'.$resource_file->get_filename()] = $path;
}
// End get files resources
// Create zip file
$packer = get_file_packer('application/zip');
$fs = get_file_storage();
$result = $packer->archive_to_storage($new_names, $context->id, 'local_zip', 'zip_files', 0, '/', $filename);
// End Create zip file
print_r($result);
Best regards,
Iban Cardona.
How to create a zip file with all resource modules of a course:
<?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/>.
require_once('../../config.php');
$id = required_param('id', PARAM_INT);
$course = get_course($id);
if (!$course) {
die();
}
$context = context_course::instance($course->id);
require_login($course);
$filename = 'contents.zip';
$new_names = array();
// Get files resources
$query_resources = "SELECT {resource}.*
FROM {resource}, {course_modules}, {modules}
WHERE {course_modules}.instance = {resource}.id
AND {modules}.id = {course_modules}.module
AND {modules}.name = 'resource'
AND {resource}.course = ?
AND {course_modules}.course = ?";
$resources = $DB->get_records_sql($query_resources, array($course->id, $course->id));
foreach ($resources as $resource) {
$cm = get_coursemodule_from_instance('resource', $resource->id, $resource->course, false, MUST_EXIST);
$context_resource = context_module::instance($cm->id);
$fs = get_file_storage();
$resource_files = $fs->get_area_files($context_resource->id, 'mod_resource', 'content', 0, 'sortorder DESC, id ASC', false);
if (count($resource_files) < 1) continue;
$resource_file = reset($resource_files);
unset($resource_files);
$contenthash = $resource_file->get_contenthash();
$l1 = $contenthash[0].$contenthash[1];
$l2 = $contenthash[2].$contenthash[3];
$filedir = ((isset($CFG->filedir))) ? $CFG->filedir : $CFG->dataroot.'/filedir';
$path = "$filedir/$l1/$l2/$contenthash";
$new_names['/'.$resource->name.'/'.$resource_file->get_filename()] = $path;
}
// End get files resources
// Create zip file
$packer = get_file_packer('application/zip');
$fs = get_file_storage();
$result = $packer->archive_to_storage($new_names, $context->id, 'local_zip', 'zip_files', 0, '/', $filename);
// End Create zip file
print_r($result);
Best regards,
Iban Cardona.
Tuesday, 2 February 2016
Moodle: Use config.php vars (CFG) loading minimum data
Hello,
Sometimes, in a custom moodle script or in your local plugin you need $CFG vars but you don't need all moodle features.
The best option is write:
<?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/>.
define('NO_DEBUG_DISPLAY', true);
define('ABORT_AFTER_CONFIG', true);
require_once('../../config.php');
...
With this code, you could, for example, execute echo $CFG->dbhost
Best regards,
Iban Cardona.
Sometimes, in a custom moodle script or in your local plugin you need $CFG vars but you don't need all moodle features.
The best option is write:
<?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/>.
define('NO_DEBUG_DISPLAY', true);
define('ABORT_AFTER_CONFIG', true);
require_once('../../config.php');
...
With this code, you could, for example, execute echo $CFG->dbhost
Best regards,
Iban Cardona.
Wednesday, 4 November 2015
Moodle: Avoid alert message when form changed and exit page
Hello,
Sometimes in a moodleform you want to move to another page by javascript and a message appears saying "Are you sure...?"
The solution:
In your javascript code, use before call window.location:
window.onbeforeunload = null;
Best regards!
UPDATE 09/3/2015
P.D: Another option is editing the form and in the definition function add:
public function definition() {
$mform =& $this->_form;
$mform->disable_form_change_checker();
Sometimes in a moodleform you want to move to another page by javascript and a message appears saying "Are you sure...?"
The solution:
In your javascript code, use before call window.location:
window.onbeforeunload = null;
Best regards!
UPDATE 09/3/2015
P.D: Another option is editing the form and in the definition function add:
public function definition() {
$mform =& $this->_form;
$mform->disable_form_change_checker();
Tuesday, 13 October 2015
Moodle: Change current session lang in your local plugins
Hi,
I'm creating some code in my moodle local plugins and webservices and I'd like to "force" use a specific language. The solution that I found is:
$SESSION->lang = 'ca';
Best regards,
Iban Cardona.
I'm creating some code in my moodle local plugins and webservices and I'd like to "force" use a specific language. The solution that I found is:
$SESSION->lang = 'ca';
Best regards,
Iban Cardona.
Wednesday, 17 June 2015
Essential: List of categories as a tree
Essential is a fancy moodle theme that has a lot of settings... One of them is use icons in categories or not. If you select in Category Icons -> Enable category icons : Yes, you will see categories as folders:
If you select "No", you will see categories as a tree:
Best regards,
Iban Cardona.
If you select "No", you will see categories as a tree:
Best regards,
Iban Cardona.
Monday, 23 March 2015
Use image repository in theme settings inside html editor
Hi,
I'm using Essential (version 2.7) theme in moodle. In settings section, I'd like to use html editor with the option to upload images. My solution:
In settings.php file:
global $CFG;
require_once($CFG->dirroot.'/local/icsbcn/lib/admin_setting_confightmleditor_icsbcn.class.php');
$setting = new admin_setting_confightmleditor_icsbcn($name, $title, $description, $default);
In admin_setting_confightmleditor_icsbcn.class.php file:
<?php
global $CFG;
require_once($CFG->libdir.'/adminlib.php');
require_once($CFG->libdir.'/filelib.php');
/**
* General text area with html editor.
*/
class admin_setting_confightmleditor_icsbcn extends admin_setting_configtext {
private $rows;
private $cols;
private $options;
/**
* @param string $name
* @param string $visiblename
* @param string $description
* @param mixed $defaultsetting string or array
* @param mixed $paramtype
*/
public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $cols='60', $rows='8') {
$this->rows = $rows;
$this->cols = $cols;
parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype);
editors_head_setup();
}
private function get_options() {
global $USER;
$ctx = context_user::instance($USER->id);
$default = array();
$default['noclean'] = false;
$default['context'] = $ctx;
$default['maxbytes'] = 0;
$default['maxfiles'] = -1;
$default['forcehttps'] = false;
$default['subdirs'] = false;
$default['changeformat'] = 0;
$default['areamaxbytes'] = FILE_AREA_MAX_BYTES_UNLIMITED;
$default['return_types'] = (FILE_INTERNAL | FILE_EXTERNAL);
return $default;
}
/**
* Returns an XHTML string for the editor
*
* @param string $data
* @param string $query
* @return string XHTML string for the editor
*/
public function output_html($data, $query='') {
global $USER;
$default = $this->get_defaultsetting();
$defaultinfo = $default;
if (!is_null($default) and $default !== '') {
$defaultinfo = "\n".$default;
}
$ctx = context_user::instance($USER->id);
$editor = editors_get_preferred_editor(FORMAT_HTML);
$options = $this->get_options();
$draftitemid = file_get_unused_draft_itemid();
$component = is_null($this->plugin) ? 'core' : $this->plugin;
$data = file_prepare_draft_area($draftitemid, $options['context']->id, $component, $this->get_full_name().'_draftitemid', $draftitemid, $options, $data);
$fpoptions = array();
$args = new stdClass();
// need these three to filter repositories list
$args->accepted_types = array('web_image');
$args->return_types = $options['return_types'];
$args->context = $ctx;
$args->env = 'filepicker';
// advimage plugin
$image_options = initialise_filepicker($args);
$image_options->context = $ctx;
$image_options->client_id = uniqid();
$image_options->maxbytes = $options['maxbytes'];
$image_options->areamaxbytes = $options['areamaxbytes'];
$image_options->env = 'editor';
$image_options->itemid = $draftitemid;
// moodlemedia plugin
$args->accepted_types = array('video', 'audio');
$media_options = initialise_filepicker($args);
$media_options->context = $ctx;
$media_options->client_id = uniqid();
$media_options->maxbytes = $options['maxbytes'];
$media_options->areamaxbytes = $options['areamaxbytes'];
$media_options->env = 'editor';
$media_options->itemid = $draftitemid;
// advlink plugin
$args->accepted_types = '*';
$link_options = initialise_filepicker($args);
$link_options->context = $ctx;
$link_options->client_id = uniqid();
$link_options->maxbytes = $options['maxbytes'];
$link_options->areamaxbytes = $options['areamaxbytes'];
$link_options->env = 'editor';
$link_options->itemid = $draftitemid;
$fpoptions['image'] = $image_options;
$fpoptions['media'] = $media_options;
$fpoptions['link'] = $link_options;
$editor->use_editor($this->get_id(), $options, $fpoptions);
return format_admin_setting($this, $this->visiblename,
'<div class="form-textarea"><textarea rows="'. $this->rows .'" cols="'. $this->cols .'" id="'. $this->get_id() .'" name="'. $this->get_full_name() .'" spellcheck="true">'. s($data) .'</textarea></div>
<input value="'.$draftitemid.'" name="'.$this->get_full_name().'_draftitemid" type="hidden" />',
$this->description, true, '', $defaultinfo, $query);
}
public function write_setting($data) {
global $CFG;
if ($this->paramtype === PARAM_INT and $data === '') {
// do not complain if '' used instead of 0
$data = 0;
}
// $data is a string
$validated = $this->validate($data);
if ($validated !== true) {
return $validated;
}
$options = $this->get_options();
$fs = get_file_storage();
$component = is_null($this->plugin) ? 'core' : $this->plugin;
$wwwroot = $CFG->wwwroot;
if ($options['forcehttps']) {
$wwwroot = str_replace('http://', 'https://', $wwwroot);
}
$draftitemid = $_REQUEST[$this->get_full_name().'_draftitemid'];
$draftfiles = $fs->get_area_files($options['context']->id, 'user', 'draft', $draftitemid, 'id');
foreach ($draftfiles as $file) {
if (!$file->is_directory()) {
$strToSearch = "$wwwroot/draftfile.php/".$options['context']->id."/user/draft/$draftitemid/".$file->get_filename();
if (stripos($data, $strToSearch) !== false) {
$file_record = array(
'contextid' => context_system::instance()->id,
'component' => $component,
'filearea' => 'icsbcnmarketingimages',
'itemid' => 0,
'timemodified' => time()
);
$newfile = $fs->create_file_from_storedfile($file_record, $file);
$url = moodle_url::make_pluginfile_url($newfile->get_contextid(), $newfile->get_component(), $newfile->get_filearea(), $newfile->get_itemid(), $newfile->get_filepath(), $newfile->get_filename());
$data = str_ireplace($strToSearch, $url, $data);
}
}
}
return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
}
}
In theme/icsbcn/lib.php:
I added these lines in function theme_icsbcn_pluginfile:
else if ($filearea === 'icsbcnmarketingimages') {
return $theme->setting_file_serve($filearea, $args, $forcedownload, $options);
}
Best regards!
Iban Cardona.
I'm using Essential (version 2.7) theme in moodle. In settings section, I'd like to use html editor with the option to upload images. My solution:
In settings.php file:
global $CFG;
require_once($CFG->dirroot.'/local/icsbcn/lib/admin_setting_confightmleditor_icsbcn.class.php');
$setting = new admin_setting_confightmleditor_icsbcn($name, $title, $description, $default);
In admin_setting_confightmleditor_icsbcn.class.php file:
<?php
global $CFG;
require_once($CFG->libdir.'/adminlib.php');
require_once($CFG->libdir.'/filelib.php');
/**
* General text area with html editor.
*/
class admin_setting_confightmleditor_icsbcn extends admin_setting_configtext {
private $rows;
private $cols;
private $options;
/**
* @param string $name
* @param string $visiblename
* @param string $description
* @param mixed $defaultsetting string or array
* @param mixed $paramtype
*/
public function __construct($name, $visiblename, $description, $defaultsetting, $paramtype=PARAM_RAW, $cols='60', $rows='8') {
$this->rows = $rows;
$this->cols = $cols;
parent::__construct($name, $visiblename, $description, $defaultsetting, $paramtype);
editors_head_setup();
}
private function get_options() {
global $USER;
$ctx = context_user::instance($USER->id);
$default = array();
$default['noclean'] = false;
$default['context'] = $ctx;
$default['maxbytes'] = 0;
$default['maxfiles'] = -1;
$default['forcehttps'] = false;
$default['subdirs'] = false;
$default['changeformat'] = 0;
$default['areamaxbytes'] = FILE_AREA_MAX_BYTES_UNLIMITED;
$default['return_types'] = (FILE_INTERNAL | FILE_EXTERNAL);
return $default;
}
/**
* Returns an XHTML string for the editor
*
* @param string $data
* @param string $query
* @return string XHTML string for the editor
*/
public function output_html($data, $query='') {
global $USER;
$default = $this->get_defaultsetting();
$defaultinfo = $default;
if (!is_null($default) and $default !== '') {
$defaultinfo = "\n".$default;
}
$ctx = context_user::instance($USER->id);
$editor = editors_get_preferred_editor(FORMAT_HTML);
$options = $this->get_options();
$draftitemid = file_get_unused_draft_itemid();
$component = is_null($this->plugin) ? 'core' : $this->plugin;
$data = file_prepare_draft_area($draftitemid, $options['context']->id, $component, $this->get_full_name().'_draftitemid', $draftitemid, $options, $data);
$fpoptions = array();
$args = new stdClass();
// need these three to filter repositories list
$args->accepted_types = array('web_image');
$args->return_types = $options['return_types'];
$args->context = $ctx;
$args->env = 'filepicker';
// advimage plugin
$image_options = initialise_filepicker($args);
$image_options->context = $ctx;
$image_options->client_id = uniqid();
$image_options->maxbytes = $options['maxbytes'];
$image_options->areamaxbytes = $options['areamaxbytes'];
$image_options->env = 'editor';
$image_options->itemid = $draftitemid;
// moodlemedia plugin
$args->accepted_types = array('video', 'audio');
$media_options = initialise_filepicker($args);
$media_options->context = $ctx;
$media_options->client_id = uniqid();
$media_options->maxbytes = $options['maxbytes'];
$media_options->areamaxbytes = $options['areamaxbytes'];
$media_options->env = 'editor';
$media_options->itemid = $draftitemid;
// advlink plugin
$args->accepted_types = '*';
$link_options = initialise_filepicker($args);
$link_options->context = $ctx;
$link_options->client_id = uniqid();
$link_options->maxbytes = $options['maxbytes'];
$link_options->areamaxbytes = $options['areamaxbytes'];
$link_options->env = 'editor';
$link_options->itemid = $draftitemid;
$fpoptions['image'] = $image_options;
$fpoptions['media'] = $media_options;
$fpoptions['link'] = $link_options;
$editor->use_editor($this->get_id(), $options, $fpoptions);
return format_admin_setting($this, $this->visiblename,
'<div class="form-textarea"><textarea rows="'. $this->rows .'" cols="'. $this->cols .'" id="'. $this->get_id() .'" name="'. $this->get_full_name() .'" spellcheck="true">'. s($data) .'</textarea></div>
<input value="'.$draftitemid.'" name="'.$this->get_full_name().'_draftitemid" type="hidden" />',
$this->description, true, '', $defaultinfo, $query);
}
public function write_setting($data) {
global $CFG;
if ($this->paramtype === PARAM_INT and $data === '') {
// do not complain if '' used instead of 0
$data = 0;
}
// $data is a string
$validated = $this->validate($data);
if ($validated !== true) {
return $validated;
}
$options = $this->get_options();
$fs = get_file_storage();
$component = is_null($this->plugin) ? 'core' : $this->plugin;
$wwwroot = $CFG->wwwroot;
if ($options['forcehttps']) {
$wwwroot = str_replace('http://', 'https://', $wwwroot);
}
$draftitemid = $_REQUEST[$this->get_full_name().'_draftitemid'];
$draftfiles = $fs->get_area_files($options['context']->id, 'user', 'draft', $draftitemid, 'id');
foreach ($draftfiles as $file) {
if (!$file->is_directory()) {
$strToSearch = "$wwwroot/draftfile.php/".$options['context']->id."/user/draft/$draftitemid/".$file->get_filename();
if (stripos($data, $strToSearch) !== false) {
$file_record = array(
'contextid' => context_system::instance()->id,
'component' => $component,
'filearea' => 'icsbcnmarketingimages',
'itemid' => 0,
'timemodified' => time()
);
$newfile = $fs->create_file_from_storedfile($file_record, $file);
$url = moodle_url::make_pluginfile_url($newfile->get_contextid(), $newfile->get_component(), $newfile->get_filearea(), $newfile->get_itemid(), $newfile->get_filepath(), $newfile->get_filename());
$data = str_ireplace($strToSearch, $url, $data);
}
}
}
return ($this->config_write($this->name, $data) ? '' : get_string('errorsetting', 'admin'));
}
}
In theme/icsbcn/lib.php:
I added these lines in function theme_icsbcn_pluginfile:
else if ($filearea === 'icsbcnmarketingimages') {
return $theme->setting_file_serve($filearea, $args, $forcedownload, $options);
}
Best regards!
Iban Cardona.
Location:
Barcelona, Barcelona, Espanya
Thursday, 8 January 2015
Moodle: Number of courses in which a user is enrolled
Hello,
Moodle is a software designed to create online courses. You can add a lot of tailor-made plugins.
One of the most interesting info that would be interesting could be... The number of courses in which a user is enrolled. We can know it by (tested with version 2.6.2):
Regards!
Moodle is a software designed to create online courses. You can add a lot of tailor-made plugins.
One of the most interesting info that would be interesting could be... The number of courses in which a user is enrolled. We can know it by (tested with version 2.6.2):
global $DB;
$sql_count = 'SELECT COUNT(c.id)
FROM mdl_course AS c
JOIN mdl_context AS ct ON c.id = ct.instanceid
JOIN mdl_role_assignments AS ra ON ra.contextid = ct.id
JOIN mdl_user AS u ON u.id = ra.userid
JOIN mdl_role AS r ON r.id = ra.roleid
WHERE u.id = ?';
$courses_count = $DB->count_records_sql($sql_count, array($idUser));
Regards!
Sunday, 7 December 2014
Moodle: custom CSS in Essential theme
When you want to custom a moodle instance, you could need to modify Essential theme, for example, I don't want to see headers in SCORM content. The best option is use customcss property.
We go to admin/settings.php?section=theme_essential_generic in our site and we search for customcss textarea. To avoid seeing headers in SCORM, we add:
Best regards!
We go to admin/settings.php?section=theme_essential_generic in our site and we search for customcss textarea. To avoid seeing headers in SCORM, we add:
#page-mod-scorm-player div[role=main] h2 {display: none;}
#page-mod-scorm-player header[role=banner] {display: none;}
Best regards!
Tuesday, 2 December 2014
Moodle: Delete one file in moodle filesystem
Hola,
After seeing how to add files and how to list them. Today we will see how to delete them:
Best regards!
After seeing how to add files and how to list them. Today we will see how to delete them:
$fs = get_file_storage();
// Prepare file record object
$fileinfo = array(
'component' => 'backup',
'filearea' => 'course',
'itemid' => 0,
'contextid' => 0,
'filepath' => '/',
'filename' => 'filename.xlsx'
);
// Get file
$file = $fs->get_file($fileinfo['contextid'], $fileinfo['component'], $fileinfo['filearea'], $fileinfo['itemid'], $fileinfo['filepath'],
$fileinfo['filename']);
// Delete it if it exists
if ($file) {
if ($file->delete()) {
return true;
} else {
return false;
}
}
Best regards!
Monday, 1 December 2014
Moodle: list files in moodle filesystem
Hello,
Last day we saw how to create an excel file in modle: http://icsbcn.blogspot.com/2014/11/moodle-create-and-save-excel-file-in.html
If we want to list that files, we can do this:
$content .= html_writer::start_tag('div', array('id' => 'list_files'));
$content .= html_writer::table($table);
$content .= html_writer::end_tag('div');
// End list excel files
Best regards!
Last day we saw how to create an excel file in modle: http://icsbcn.blogspot.com/2014/11/moodle-create-and-save-excel-file-in.html
If we want to list that files, we can do this:
// List excel files
$table = new html_table();
$table->head = array('filename', 'filedate', 'filesize', '');
$table->align = array('left', 'left', 'left','left');
// Get files
$fs = get_file_storage();
$files = $fs->get_area_files(0, 'backup', 'course', 0, 'timemodified DESC', false);
foreach ($files as $file) {
$filename = $file->get_filename();
$row = array();
$row[] = $filename; // filename
$row[] = date('d/m/Y H:i:s', $file->get_timecreated()); // creation date
$row[] = $this->formatSizeUnits($file->get_filesize()); // file size as human view
// Download link
$url = moodle_url::make_pluginfile_url($file->get_contextid(), $file->get_component(), $file->get_filearea(), $file->get_itemid(), $file->get_filepath(), $filename);
$row[] = html_writer::link($url, get_string('downloadfile', 'moodle'));
$table->data[] = $row;
}
// End get files
$content .= html_writer::start_tag('div', array('id' => 'list_files'));
$content .= html_writer::table($table);
$content .= html_writer::end_tag('div');
// End list excel files
Best regards!
Sunday, 30 November 2014
Moodle: Create and save an excel file in moodle filesystem
Hello,
Moodle filesystem is powerful but it's hard to understand too. In this code we will see how to create an excel file and save it in the moodle filesystem:
Documentation:
https://docs.moodle.org/dev/File_API_internals
https://docs.moodle.org/dev/File_API
Best regards!
Moodle filesystem is powerful but it's hard to understand too. In this code we will see how to create an excel file and save it in the moodle filesystem:
Documentation:
https://docs.moodle.org/dev/File_API_internals
https://docs.moodle.org/dev/File_API
// Create excel file
require_once("$CFG->libdir/phpexcel/PHPExcel.php");
$filenameTmp = tempnam(sys_get_temp_dir(), time());
$objPHPExcel = new PHPExcel();
// Excel metadata
$objPHPExcel->getProperties()->setCreator("www.ibancardonasubiela.tk")
->setLastModifiedBy("www.ibancardonasubiela.tk")
->setTitle("www.ibancardonasubiela.tk")
->setSubject("www.ibancardonasubiela.tk")
->setDescription("www.ibancardonasubiela.tk")
// Crear the first sheet$objPHPExcel->setActiveSheetIndex(0);
$objPHPExcel->getActiveSheet()->setTitle("www.ibancardonasubiela.tk");
// Header
$arrayHeader = array('aaa', 'bbb');
$countHeader = count($arrayHeader);
foreach ($arrayHeader as $pos => $value) {
$excelLetter = PHPExcel_Cell::stringFromColumnIndex($pos);
$objPHPExcel->getActiveSheet()->getStyle($excelLetter.'1')->getFont()->setSize(14);
$objPHPExcel->getActiveSheet()->getStyle($excelLetter.'1')->getFont()->setBold(true);
$objPHPExcel->getActiveSheet()->setCellValue($excelLetter.'1', $value);
$objPHPExcel->getActiveSheet()->getColumnDimension($excelLetter)->setAutoSize(true);
}
// Add content
// Save excel in a temporal file
$objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
$objWriter->save($filenameTmp);
// Copy excel to moodle filesystem
$fs = get_file_storage();
$file_record = array(
'contextid' => 0,
'component' => 'backup', // "mod_forum", "course", "mod_assignment", "backup"...
'filearea' => 'course', // "submissions", "intro" and "content" , "blogs","userfiles"...
'itemid' => 0,
'filepath' => '/',
'timecreated' => time(),
'timemodified' => time(),
'filename' => 'excel'.'_'.time().'.xlsx'
);
$fs->create_file_from_pathname($file_record, $filenameTmp);
// Delete temp file
unlink($filenameTmp);
Best regards!
Sunday, 9 November 2014
Moodle: get top category from course data
Hello!
If we have course data and we want to get top category from that, we can do this:
Best regards!
If we have course data and we want to get top category from that, we can do this:
$category = $DB->get_record('course_categories', array('id' => $courseObj->category));
$arrCats = explode("/", ($category->path));
$topCategory = $DB->get_record('course_categories', array('id' => intval($arrCats[1])));
Best regards!
Sunday, 26 October 2014
Moodle: purge all caches by console
Hello,
If we have a moodle installed, a very interesting method to delete all caches is to use system console. To do that, we have to go to our moodle route and execute:
Best regards!
If we have a moodle installed, a very interesting method to delete all caches is to use system console. To do that, we have to go to our moodle route and execute:
php admin/cli/purge_caches.php
Best regards!
Subscribe to:
Posts (Atom)

