34
Tutorial: Creación de un módulo actividad. Moodle (1.9.3) Copyright © 2009 Raúl Ivorra Oltra. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.3 or any later version published by the Free Software Foundation; with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts. A copy of the license is included in the section entitled "GNU Free Documentation License".

Tutorial: Creación de un módulo actividad. Moodle (1.9.3)gplsi.dlsi.ua.es/~slujan/materiales/creacion-modulo-moodle.pdf · 2.2 Instalación de Moodle ... nos en inglés y traducidos

  • Upload
    donga

  • View
    229

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Tutorial: Creación de un módulo actividad. Moodle (1.9.3)gplsi.dlsi.ua.es/~slujan/materiales/creacion-modulo-moodle.pdf · 2.2 Instalación de Moodle ... nos en inglés y traducidos

Tutorial:

Creación de un

módulo actividad.

Moodle (1.9.3)

Copyright © 2009 Raúl Ivorra Oltra.

Permission is granted to copy, distribute and/or modify this document under the terms of

the GNU Free Documentation License, Version 1.3 or any later version published by the Free

Software Foundation; with no Invariant Sections, no Front-Cover Texts, and no Back-Cover

Texts. A copy of the license is included in the section entitled "GNU Free Documentation

License".

Page 2: Tutorial: Creación de un módulo actividad. Moodle (1.9.3)gplsi.dlsi.ua.es/~slujan/materiales/creacion-modulo-moodle.pdf · 2.2 Instalación de Moodle ... nos en inglés y traducidos

Índice

1 Introducción...................................................................................... 1

2 Antes de empezar..............................................................................1

2.1 Recomendaciones.................................................................................. 12.2 Instalación de Moodle............................................................................ 1

3 Esquema de un módulo...................................................................... 2

3.1 Ficheros de idiomas............................................................................... 33.2 Permisos de un módulo..........................................................................4

4 Revisión de un módulo. El módulo Tarea (assigment)........................5

4.1 mod_form.php....................................................................................... 54.2 install.xml..............................................................................................64.3 upgrade.php...........................................................................................64.4 lib.php................................................................................................... 74.5 settings.php...........................................................................................84.6 access.php............................................................................................. 8

5 Desarrollo de un módulo de ejemplo..................................................8

5.1 Creación del formulario de configuración de la instancia........................95.1.1 select................................................................................................ 105.1.2 Botón de acción. Nosubmit...................................................................11

5.2 Librería del módulo.............................................................................. 125.3 Tablas de un módulo............................................................................ 135.4 Editar ficheros obligatorios.................................................................. 145.5 Editar view.php....................................................................................14

6 Instalación del módulo.....................................................................15

6.1 Desinstalación de la actividad.............................................................. 15

7 ANEXOS............................................................................................18

7.1 ANEXO I: Código fuente de assigment..................................................187.1.1 mod_form.php....................................................................................187.1.2 install.xml..........................................................................................197.1.3 upgrade.php.......................................................................................217.1.4 access.php.........................................................................................227.1.5 settings.php.......................................................................................23

7.2 Anexo II: Ficheros del módulo ejemplo................................................ 247.2.1 mod_form.php....................................................................................247.2.2 ....................................................................................................... 247.2.3 install.xml..........................................................................................247.2.4 upgrade.php.......................................................................................25

8 GNU Free Documentation License....................................................26

Page 3: Tutorial: Creación de un módulo actividad. Moodle (1.9.3)gplsi.dlsi.ua.es/~slujan/materiales/creacion-modulo-moodle.pdf · 2.2 Instalación de Moodle ... nos en inglés y traducidos

Índice de FigurasIlustración 1: Formulario de alta de nueva instancia..........................................................10

Ilustración 2: Editor XMLDB mostrando las tablas de un módulo.........................................13

Ilustración 3: Editor XMLDB de tabla...............................................................................14

Ilustración 4: Menú de gestión de actividades.................................................................. 15

Índice de CódigoCódigo 1: Ejemplo de fichero de idioma............................................................................ 4

Código 2: Uso de las cadenas de idioma............................................................................4

Código 3: Fichero de permisos......................................................................................... 4

Código 4: Uso de los permisos......................................................................................... 5

Código 5: Clase para la creación del formulario de alta de instancias....................................5

Código 6: Comprobación de número de versión..................................................................6

Código 7: Alterar tabla de la base de datos........................................................................7

Código 8: Recuperar registros de la base de datos..............................................................7

Código 9: Añadir parámetro a un módulo.......................................................................... 8

Código 10: Permiso de lectura......................................................................................... 8

Código 11: Clase para el formulario de alta de instancias de un módulo................................9

Código 12: Añadir checkbox a un formulario......................................................................9

Código 13: Añadir elementos estándar a un formulario....................................................... 9

Código 14: Añadir select a formulario..............................................................................10

Código 15: Formulario con botón NoSubmit y su procesamiento.........................................12

3/31

Page 4: Tutorial: Creación de un módulo actividad. Moodle (1.9.3)gplsi.dlsi.ua.es/~slujan/materiales/creacion-modulo-moodle.pdf · 2.2 Instalación de Moodle ... nos en inglés y traducidos

1 Introducción.

Este tutorial es parte del trabajo realizado en la beca de colaboración del curso 2008-2009

para el Departamento de Lenguajes y Sistemas Informáticos de la Universidad de Alicante por

el alumno Raúl Ivorra Oltra. El tutor de la beca ha sido Dr. Luján Mora.

Este tutorial es una actualización y ampliación para Moodle 1.9.3 del tutorial publicado por

Javier Rodríguez Martín de la Escuela Politécnica de Cáceres, con el objetivo de facilitar el ca-

mino, dar pautas de desarrollo a los programadores noveles y comentar aquellas incidencias

que se han presentado en la creación de un nuevo módulo.

La versión anterior de este manual se puede descargar de [TUTORIAL_1_6].

2 Antes de empezar.

Antes de desarrollar un módulo para Moodle es conveniente seguir los siguientes

puntos.

2.1 Recomendaciones.

Antes de iniciarse en la programación de cualquier aspecto de Moodle es necesario

entender la plataforma, cómo funciona, para qué sirve cada opción, cuál es el papel del

profesor, del programador o del administrador. Desde el sitio Web de Moodle se puede

descargar manuales de la plataforma [MANMOODLE_ES] aunque no están tan actualiza-

dos como las versiones en inglés de los mismos manuales y se recomienda siempre

comprobar el contenido en inglés también [MANMOODLE_EN].

Otra recomendación interesante y prácticamente obligatoria si se pretende que otros

desarrolladores entiendan, mejoren o continúen el trabajo realizado es seguir el manual

de estilo de código [MANCODIGO_ES]. En este manual se dan una serie de reglas gene-

rales para el tratamiento de ficheros, funciones y variables de un módulo. También se

comentan las reglas de estilo de código, la estructura de la base de datos y las normas

de seguridad en la creación de una actividad.

2.2 Instalación de Moodle.

Antes de comenzar con el tema central de este tutorial se darán unas pautas básicas

para instalar la plataforma. Todo el proceso de instalación según Windows, Linux o Mac

está descrito en la web oficial de Moodle [MODINSTALL_ES] y con más detalle en [MOO-

DINSTALL_EN].

Moodle necesita los siguientes requisitos para ejecutarse:

• Un servidor Web como por ejemplo, Apache. También soporta IIS,.

• Una instalación de PHP. Sirve cualquier versión a partir de la 4.3.0. Aunque se

recomienda PHP5 (> 5.2.4) ya que Moodle 2.0 no soportará PHP4.

• Una base de datos. Mysql (4.1.16 en adelante) es la más popular aunque Post-

greSQL, Microsoft SQL Server y Oracle también están soportadas.

1/31

Page 5: Tutorial: Creación de un módulo actividad. Moodle (1.9.3)gplsi.dlsi.ua.es/~slujan/materiales/creacion-modulo-moodle.pdf · 2.2 Instalación de Moodle ... nos en inglés y traducidos

Al paquete MySQL, PHP y Apache se le denomina plataforma AMP y simplifica la

instalación de la plataforma. La documentación acerca de las particularidades de cada

paquete se encuentra en [MOODAMP_ES] y en [MOODAMP_EN]. Así mismo existen pa-

quetes con Moodle, MySQL, Apache y PHP para Windows y para Mac y se pueden en-

contrar en [MAMP_WIN] y [MAMP_MAC], estos paquetes no existen para Linux. Con

este paquete tendremos todo lo necesario para hacer funcionar la plataforma.

El siguiente paso, si no se ha elegido un paquete con Moodle en él, es obtener la

plataforma [MOODDOWN] y descomprimir el archivo obtenido. Se debe colocar la

carpeta completa en su servidor web (http://suservidor.com/moodle) y a continuación

ejecutar el script de instalación usando un navegador común. Para acceder a este script

simplemente habrá que redirigir el navegador a la dirección http://suservidor.com/mo-

odle/install.php. El proceso de instalación es automático, requiriéndose la intervención

del usuario en contadas ocasiones. Una vez realizado el proceso de instalación se podrá

ejecutar Moodle desde la dirección http://susservidor.com/moodle, asegurándose el

usuario de que Apache y Mysql están ejecutándose. Existe una lista de preguntas fre-

cuentes sobre la instalación de Moodle [MOODFAQ_ES] e información para la realización

de actualizaciones del software de la plataforma en la Web [MODUPDATE_ES].

3 Esquema de un módulo.

Previo al desarrollo de una actividad es necesario conocer el esquema de un módulo. Los

módulos se almacenan en la carpeta moodle/mod, cada uno en un directorio, siendo la

estructura general de archivos y directorios como se explica en [MODACT_EN] y que resumi-

mos a continuación:

• mod_form.php: Formulario para crear o modificar una instancia de la actividad.

• version.php: para definir meta información, como por ejemplo la versión del módulo.

• lang/: directorio para almacenar los archivos de idioma del módulo. El módulo debe te-

ner archivos de idioma que contenga las cadenas para ese módulo. Deberán ser al me-

nos en inglés y traducidos a los idiomas de los usuarios finales que utilicen la actividad.

• db/: Directorio donde se almacenarán los ficheros con las tablas de las bases de datos

necesarias para la actividad.

• access.php: Fichero de permisos del módulo. Los permisos no son obligatorios

pero sí muy recomendables para garantizar qué usuarios pueden acceder a las

distintas partes del módulo.

• install.xml: Fichero que describe la estructura de las tablas del módulo.

• upgrade.php: código de actualización, aquí es donde se deben de hacer las alte-

raciones de las tablas, si las hay, entre versiones.

• index.php: Este fichero sirve para mostrar todas las instancias de una actividad en un

curso, es decir, una lista con todas las instancias del mismo módulo.

2/31

Page 6: Tutorial: Creación de un módulo actividad. Moodle (1.9.3)gplsi.dlsi.ua.es/~slujan/materiales/creacion-modulo-moodle.pdf · 2.2 Instalación de Moodle ... nos en inglés y traducidos

• view.php: Esta es la página que muestra una instancia de la actividad.

• lib.php: librería de funciones del módulo. En este fichero se implementarán todas las

funciones y procedimientos del módulo. Si el módulo se llama ejemplo, entonces las

funciones mínimas y obligatorias que ha de tener la actividad tienen que ser de la

forma:

• ejemplo_install(): Acciones a realizar al instalar el módulo.

• ejemplo_add_instance(): código para añadir una nueva instancia.

• ejemplo_update_instance(): función para actualizar una instancia existente.

• ejemplo_delete_instance(): código para borrar una instancia.

• ejemplo_user_outline(): da un resumen concreto de la actividad de un usuario.

• ejemplo_user_complete(): devuelve un informe más detallado de la contribución

de un usuario.

• ejemplo_get_view_actions(): Clasifica las acciones para el log. Se usa en el in-

forme de participación.

• Todas las funciones, procedimientos y constantes, creados en lib.php, tienen que

comenzar con el nombre del módulo.

• settings.php (opcional): Formulario con las opciones generales del módulo.

3.1 Ficheros de idiomas.

Moodle es una plataforma internacional. Cada módulo ha de tener un archivo de

idioma de forma que cada cadena que forme parte de la interfaz, se extraiga de un

conjunto de archivos de idioma. Estructura del carpeta de idioma:

• lang/:En esta carpeta se encuentra todos los ficheros de idioma. Cada idioma

tiene la misma estructura de carpetas dentro de esta. Según el código de estilo

han de definirse los textos al menos en inglés. Para el caso del español interna-

cional el nombre de la carpeta es es_utf8. El idioma por defecto es el inglés

en_utf8. En caso de que una cadena no se encuentre en un idioma determinado

se mostrará la cadena del archivo del idioma inglés. La ruta para el fichero sería

lang/idioma/nombremodulo.php.

• idioma/help/nombremodulo: En esta carpeta es donde se localizan los ficheros

de ayuda y que pese a tener extensión .html se comportan como ficheros .php.

Los obligatorios son.

• index.html: Listado de todos los ficheros de ayuda que dispone la actividad.

• mods.html: Descripción del contenido y propósito del módulo.

• El desarrollador creará más ficheros de ayuda en función de las partes del

módulo que considere que necesitan una explicación.

3/31

Page 7: Tutorial: Creación de un módulo actividad. Moodle (1.9.3)gplsi.dlsi.ua.es/~slujan/materiales/creacion-modulo-moodle.pdf · 2.2 Instalación de Moodle ... nos en inglés y traducidos

Por otro lado para utilizar estas cadenas en el código el módulo disponemos de la

función get_string [REF_GET_STRING] mediante la cual podremos obtener la cadena de

texto en el idioma que el usuario tenga configurado el interfaz. En caso de no existir la

cadena en ese idioma se mostrará la del idioma inglés. El segundo parámetro es opcio-

nal y es donde especificamos el nombre del módulo, en caso de no especificarlo buscará

en el paquete de idioma de la plataforma.

3.2 Permisos de un módulo.

Los permisos permiten establecer las diferentes vistas que tendrán los distintos tipos

de usuarios para un módulo. Los tipos de usuarios son los roles en Moodle

[MOODROL_ES]. Ejemplos de roles son administrador, profesor, estudiante, etc. Asig-

nando permisos a la actividad se puede restringir el acceso a cierta información, confi-

gurar distintos tipos de vistas para los diferentes roles, establecer capacidades para los

administradores, etc. Para establecer permisos en la actividad, se creará un fichero de-

nominado access.php, en la carpeta db. Si el módulo se denomina ejemplo y queremos

establecer que usuario (rol) tendrá acceso a la vista del mismo, y que los profesores

puedan calificar el la actividad, el fichero quedaría de la siguiente manera como

muestra Código 3.

4/31

//moodle$string['modulename'] = 'Ejemplo'; $string['modulenameplural'] = 'Ejemploss'; //Del propio módulo$string['Name'] = 'Nombre para la actividad Ejemplo';

Código 1: Ejemplo de fichero de idioma

<?php$mod_inicio_capabilities = array('mod/inicio:view' => array('captype' => 'read','contextlevel' => CONTEXT_MODULE,'legacy' => array('guest' => CAP_ALLOW,'student' => CAP_ALLOW,'teacher' => CAP_ALLOW,'editingteacher' => CAP_ALLOW,'admin' => CAP_ALLOW)

),'mod/inicio:grade' => array('captype' => 'write','contextlevel' => CONTEXT_MODULE,'legacy' => array('teacher' => CAP_ALLOW,'editingteacher' => CAP_ALLOW, 'admin' => CAP_ALLOW)

));

?>

Código 3: Fichero de permisos

get_string('modulename','ejemplo');

Código 2: Uso de las cadenas de idioma

Page 8: Tutorial: Creación de un módulo actividad. Moodle (1.9.3)gplsi.dlsi.ua.es/~slujan/materiales/creacion-modulo-moodle.pdf · 2.2 Instalación de Moodle ... nos en inglés y traducidos

CONTEXT_MODULE establece el contexto en el que se aplicará el permiso, en este

caso, al módulo, y CAP_ALLOW un tipo de habilidad que se asigna a los roles. La forma

de utilizar estos permisos es muy sencilla.

En Código 4 mostramos cómo comprobar si se tiene un permiso para actuar en con-

secuencia.

La documentación de esta función está en [REF_HAS_CAPABILITIES].

4 Revisión de un módulo. El módulo Tarea (assigment).

En este capítulo repasaremos un módulo de la instalación estándar del Moodle para obtener

las claves para desarrollar nuestros propios módulos. En el Anexo I tenemos el código comple-

to de este módulo.

Los ficheros a estudiar son los básicos de cualquier módulo que son: mod_form.php,insta-

ll.xml, upgrade.php, access.php, lib.php y settings.php.

4.1 mod_form.php

Como ya se ha comentado anteriormente éste es uno de los ficheros obligatorios de

todo módulo y mediante el cual se configurará cada instancia del módulo que se añade

a un curso.

Moodle proporciona un mecanismo estándar para este paso, y para ello está definida

la clase moodleform_mod. La clase ha de llamarse obligatoriamente mod_nombremó-

dulo_mod_form.

Se extiende esta clase y se crea el método definition() mediante el cual definiremos

el formulario que presentará las distintas opciones a configurar de la instancia. Los

distintos campos que podemos utilizar se pueden encontrar en [REF_LIB_MOD_FORM].

Para añadir campos al formulario tenemos varias funciones básicas:

• addElement: Añade un elemento al formulario, el primer parámetro es el tipo de

elemento y el segundo el nombre. El resto de parámetros ya dependen del tipo

de elemento.

• setType: Establece el tipo de contenido del elemento.

5/31

$context = get_context_instance(CONTEXT_MODULE,$cm->id);if(has_capability('mod/ejemplo:view', $context)){// Código si tienes permiso

}

Código 4: Uso de los permisos

class mod_assignment_mod_form extends moodleform_mod {

Código 5: Clase para la creación del formulario de alta de instancias

Page 9: Tutorial: Creación de un módulo actividad. Moodle (1.9.3)gplsi.dlsi.ua.es/~slujan/materiales/creacion-modulo-moodle.pdf · 2.2 Instalación de Moodle ... nos en inglés y traducidos

• setDefault: Establece el valor por defecto de un elemento.

• addRule: Establece las restricciones de un elemento como por ejemplo que es un

campo obligatorio, o que sólo puede tener números.

Cabe destacar que en los elementos declarados en mod_form.php serán guardados

en los campos de la tabla con ese nombre al procesar el formulario sin que lo indique-

mos explícitamente.

4.2 install.xml

Este fichero define las tablas que necesita el módulo. Desde que se implantó XMLDB

en Moodle no es necesario tener un fichero distinto para cada base de datos soportada,

la plataforma provee mecanismos para la creación de las tablas, para el acceso y para

la modificación de los datos.

Analizando el fichero se puede observar que tenemos tablas y sentencias, y que

éstas están formando listas doblemente enlazadas mediante los campos NEXT y PRE-

VIOUS. Es por ello, y por la restricciones en los tipos de los campos a definir y sus valo-

res permitidos por los que recomendamos el uso del editor de XMLDB que tiene la pla-

taforma.

La primera tabla tiene el mismo nombre del módulo y es obligatoria, así como los

campos id,course y name. El resto de campos que proporciona la plantilla son reco-

mendables también. Para este módulo se han añadido además más campos. Al igual

que las tablas y los campos, los índices y las claves, si se añaden y si hay más de una,

hay que enlazarlos.

Para el módulo se ha definido una tabla adicional assignment_submissions siguiendo

la nomenclatura recomendada nombremodulo_tablanueva.

Las sentencias (statements) sirven para insertar fila, por ahora según la documenta-

ción, al instalar el módulo, y en este caso se están insertando valores en la tabla

log_display. Para más detalles consultar [REF_INSTALL_XML].

4.3 upgrade.php

En este fichero se encuentran las acciones para actualizar a una versión posterior de

un módulo.

Para ello en primer lugar se comprueba la versión del módulo para saber las accio-

nes a realizar.

6/31

if ($result && $oldversion < 2007091900) {

Código 6: Comprobación de número de versión

Page 10: Tutorial: Creación de un módulo actividad. Moodle (1.9.3)gplsi.dlsi.ua.es/~slujan/materiales/creacion-modulo-moodle.pdf · 2.2 Instalación de Moodle ... nos en inglés y traducidos

Para posteriormente mediante XMLDB realizar la modificaciones a las tablas que las

precisen. Como ya se ha comentado anteriormente XMLDB permite abstraernos del

gestor de bases de datos utilizado, empleando un mecanismo común para todos.

4.4 lib.php

En este fichero tenemos las funciones básicas del módulo como se comenta en el ca-

pítulo 3, y las clases que se crean oportunas, así como las constantes del módulo.

Lo más importante que podemos aprender de esta librería es a acceder a la base de

datos mediante los mecanismos que proporciona la plataforma.

• get_records(tabla,[campo],[valor],...): Esta función nos devolverá todos los re-

gistros de la tabla en forma de objetos, pudiéndolos filtrar por campo y valor. En

caso de no encontrar coincidencias devuelve false. Más referencia en

[REF_GET_RECORDS].

• insert_record: Esta función nos permite insertar registros en una tabla. Tiene 2

campos obligatorios, la tabla sobre la que actuar y el objeto a insertar. De dicho

objeto se insertarán las propiedades que tengan el mismo nombre que los

campos de la tabla.[REF_INSERT_RECORDS]. Podemos obtener el id del nuevo

registro insertado.

• update_record: Función para actualizar un registro de la base de datos. El objeto

ha de tener un campo id por el cual buscar en la tabla. [REF_UPDATE_RECORD]

• delete_records: Función para borrar registros de una tabla. Podemos especificar

hasta 3 pares (campo, valor) para filtrar los registros que deseamos borrar.

[REF_DELETE_RECORDS]. En caso de que no fuese suficiente tendríamos que

construir la sentencia SQL para utilizar [REF_DELETE_RECORDS_SELECT].

Dado que tanto para obtener e insertar datos en las tabla se utilizan objetos, en este

fichero se crean los objetos para poder usarlos cómodamente a lo largo de todo el mó-

dulo.

7/31

$table = new XMLDBTable('assignment_submissions');$field = new XMLDBField('data1');$field->setAttributes(XMLDB_TYPE_TEXT, 'small', null, null, null, null, null, null, 'numfiles');$result = $result && change_field_notnull($table, $field);

Código 7: Alterar tabla de la base de datos

$resulset = get_records('modulo_tabla','campo','valor');if($resulset){foreach($resulset as $row) {echo $row->campo1;

}}

}

Código 8: Recuperar registros de la base de datos

Page 11: Tutorial: Creación de un módulo actividad. Moodle (1.9.3)gplsi.dlsi.ua.es/~slujan/materiales/creacion-modulo-moodle.pdf · 2.2 Instalación de Moodle ... nos en inglés y traducidos

4.5 settings.php

Este fichero se utiliza para configurar el módulo. Los valores que se establezcan en

este fichero se aplican a todos los módulos y no hay que crear una tabla con los campos

para guardarlos.

En este caso se está añadiendo una opción tipo select con los parámetros nombre,

nombre visible, descripción, valor por defecto y opciones. En el fichero de la instalación

de Moodle /lib/adminlib.php se encuentran las demás funciones para los demás tipos de

campos como por ejemplo texto, checkbox, fichero, etc.

4.6 access.php

En este fichero se definen 3 permisos: view,submit,y grade. Cada permiso se conce-

de a algunos de los roles definidos en la plataforma mediante:

En cuanto a los permisos, existen roles generales, aplicables a todo el sitio que se

pueden consultar y modificar con una cuenta de administrador en Usuario-> Permisos y

por otro lado cada curso tiene sus roles locales que ha de ser configurados cuando se

crea un curso desde una cuenta de administrador del curso (vale la de administrador

del sitio) en el apartado Asignar Roles. Este modelo permite que el mismo usuario sea

alumno, profesor, administrador, etc dependiendo del curso en el que se encuentre.

5 Desarrollo de un módulo de ejemplo.

En primer lugar hay que descargarse la plantilla para un nuevo módulo de [NEWMOD]. Esta

plantilla tiene todos los ficheros obligatorios, y la estructura de directorios adecuada ya comen-

tada anteriormente.

Los pasos básicos para realizar un módulo son:

• Desarrollo del formulario para configurar cada nueva instancia del módulo

• Creación de las tablas editando el fichero db/install.xml.

8/31

$settings->add(new admin_setting_configselect('assignment_maxbytes' , get_string('maximumsize' , 'assignment'),get_string('configmaxbytes', 'assignment'), 1048576, get_max_upload_sizes($CFG->maxbytes) ) );

Código 9: Añadir parámetro a un módulo

'mod/assignment:view' => array(

'captype' => 'read','contextlevel' => CONTEXT_MODULE,'legacy' => array(

'guest' => CAP_ALLOW,'student' => CAP_ALLOW,'teacher' => CAP_ALLOW,'editingteacher' => CAP_ALLOW,'admin' => CAP_ALLOW

))

Código 10: Permiso de lectura

Page 12: Tutorial: Creación de un módulo actividad. Moodle (1.9.3)gplsi.dlsi.ua.es/~slujan/materiales/creacion-modulo-moodle.pdf · 2.2 Instalación de Moodle ... nos en inglés y traducidos

• Edición de la librería de funciones del archivo lib.php.

• Edición del resto de archivos obligatorios para adecuarlos al nuevo módulo:

index.php, version.php y ficheros de idiomas.

• Edición del fichero view.php que muestra cada instancia.

5.1 Creación del formulario de configuración de la instancia.

El fichero mod_form.php es llamado cada vez que se añade una instancia de una

actividad y con él la configuraremos. En la plantilla ya tenemos los campos obligatorios

como name y otros típicos como intro.

Aquí nos serviremos de la modularidad que nos ofrece la plataforma para no preocu-

parnos de cómo guardar los datos en la base de datos ni en cómo se define un formula-

rio en HTML, simplemente con extender la clase moodlemod_form como en la plantilla y

añadir los campos de configuración de la instancia que definamos en la BD es suficien-

te.

Cambiaremos newmodule por el nombre de nuestro módulo, con mod_ delante del

nombre del módulo.

A continuación podremos añadir elementos al formulario. Los distintos tipos de ele-

mentos se pueden encontrar en [REF_LIB_MOD_FORM]. Por ejemplo si queremos un

checkbox, con el nombre 'secure' el código a añadir quedaría como muestra Código 12:

Con este código y con los botones estándar, si existe el campo secure en la base de

datos, es todo lo que hay que hacer para guardar ese campo en la configuración de la

instancia.

Los tipos de campos básicos no presentan ninguna dificultad, pero algunos presen-

tan particularidades no muy documentadas y que pasaremos a mencionar.

9/31

class mod_ejemplo_mod_form extends moodleform_mod {

function definition() {

Código 11: Clase para el formulario de alta de instancias de un módulo

$mform->addElement('checkbox','secure',get_string('secure', 'ejemplo'));

Código 12: Añadir checkbox a un formulario

// add standard elements, common to all modules$this->standard_coursemodule_elements();// add standard buttons, common to all modules$this->add_action_buttons();

Código 13: Añadir elementos estándar a un formulario

Page 13: Tutorial: Creación de un módulo actividad. Moodle (1.9.3)gplsi.dlsi.ua.es/~slujan/materiales/creacion-modulo-moodle.pdf · 2.2 Instalación de Moodle ... nos en inglés y traducidos

5.1.1 select

Para definir un campo select hay que utilizar la sentencia:

Donde $FORUM_TYPES será un array en el cual el índice es el valor que

guardará el formulario, y el valor, el texto que mostrará el desplegable. Por lo

tanto si el valor a mostrar y el valor a guardar son el mismo, la matriz tendrá

como índice y valor la misma cadena.

10/31

$mform->addElement('select', 'type', get_string('forumtype', 'forum'), $FORUM_TYPES, $attributes);

Código 14: Añadir select a formulario

Ilustración 1: Formulario de alta de nueva instancia

Page 14: Tutorial: Creación de un módulo actividad. Moodle (1.9.3)gplsi.dlsi.ua.es/~slujan/materiales/creacion-modulo-moodle.pdf · 2.2 Instalación de Moodle ... nos en inglés y traducidos

5.1.2 Botón de acción. Nosubmit.

El caso de los botones en los formularios es especial en tanto en cuanto no

podemos asignar una acción directamente al botón fuera de las estándar de un

formulario, como submit o reset.

Para estos casos existe un mecanismo mediante el cual el formulario se envía

con todos los datos, pero al procesarlos se puede discernir si ha sido pulsado el

botón de submit u otro botón de acción, pudiendo realizar entonces las tareas

asignadas a este botón. Es importante recalcar que el fichero que procesa el

formulario ha de ser el mismo que lo genera, es por esto que en caso de formu-

lario de configuración de las instancias no es posible hacer uso de estos botones

ya que el fichero que procesa el formulario forma parte de la plataforma y no lo

debemos modificar. El caso más común es el de añadir o eliminar valores de un

campo tipo select.

Si se necesitan los datos introducidos en el formulario para mostrarlos al

volver a procesar el formulario es necesario hacerlo en el método define() antes

de mostrar el formulario, de otra forma no aparecerían.

Todo esto sólo es aplicable a formularios que necesitemos además del

mod_form.php ya no tenemos control sobre el fichero que lo procesa al formar

parte de la plataforma.

11/31

Page 15: Tutorial: Creación de un módulo actividad. Moodle (1.9.3)gplsi.dlsi.ua.es/~slujan/materiales/creacion-modulo-moodle.pdf · 2.2 Instalación de Moodle ... nos en inglés y traducidos

5.2 Librería del módulo.

Todo módulo ha de tener una librería con las funciones para el manejo de las instan-

cias en el fichero lib.php como se cita en el Capítulo 3: Estructura de un módulo. En

este fichero se definen también las constantes y clases que pueda necesitar el módulo.

En este fichero substituiremos newmodule por el nombre de nuestro módulo

(ejemplo en este caso) en todos los sitios oportunos siguiendo las instrucciones que nos

proporciona el propio fichero de la plantilla.

Además también es donde crearemos clases con propiedades de forma análoga a las

tablas del módulo para facilitarnos el acceso a los datos como se ha comentado en el

capítulo 4.4.

12/31

//ejemplo_form.phpclass ejemplo_form extends moodleform {function ejemplo_form(){// El fichero que procesa el formulario es el mismo que lo generaparent::moodleform('ejemplo_form.php');

}function definition(){$mform =& $this->_form;// Recogemos el valor del boton 'testbtn' si para saber si se ha pulsado$testbtn = optional_param('testbtn',NULL,PARAM_RAW);// Registramos el boton de no submit$mform->registerNoSubmitButton('testbtn'); // antes de definir el botón// Añadirmos el botón al formulari$mform->addElement('submit', 'testbtn', 'Botón de test');// añadimos un campo de texto$mform->addElement('text', 'texto','Campo de texto','size="15"');$valores=array(); // o recuperamos los valores de algún otro sitioif($testbtn!=NULL) //se ha pulsado el boton{

$texto = optional_param('texto',NULL,PARAM_RAW);

if($texto!=NULL){// añadimos el valor a$valores[]=$texto;

} }// añadirmos el campo tipo select con el nombre e id lista$mform->addElement('select', 'lista', 'lista', $valores);// Añadirmos los botones por defecto$this->add_action_buttons();

}}$mform= new ejemplo_form();

if($mform->no_submit_button_pressed()==1){// Acciones especiales del boton// mostramos el formularioprint_header('Formulario de prueba');$mform->display();print_footer();

}else{if($mform->is_submitted()==1){// procesamos el formulario

}}

Código 15: Formulario con botón NoSubmit y su procesamiento

Page 16: Tutorial: Creación de un módulo actividad. Moodle (1.9.3)gplsi.dlsi.ua.es/~slujan/materiales/creacion-modulo-moodle.pdf · 2.2 Instalación de Moodle ... nos en inglés y traducidos

5.3 Tablas de un módulo.

Todo módulo necesita al menos una tabla para guardar las propiedades de cada

instancia, aunque se pueden declarar más.

En el Anexo II tenemos el código del fichero install.xml para nuestro ejemplo. En él

se define una tabla, un índice, una clave, y se insertan valores en la tabla log_display al

instalarse el módulo. Se puede observar que para cada campo, se ha de indicar el

campo siguiente, y lo mismo sucede para las tablas.

La sintaxis no es muy amigable para editar el fichero manualmente y por eso se re-

comienda editarlo desde la plataforma con un usuario administrador en el menú Misce-

lánea → Editor XMLDB.

La plantilla ya proporciona un fichero válido en el que sólo hay que modificar el

nombre de la tabla y algunos comentarios. Una vez instalado el módulo ya podremos

editar las tablas desde Moodle.

Usando este editor se evitarán errores ya que el editor no permite guardar la tabla

con errores y solamente nos permite dar valores válidos a las propiedades. Hay que te-

ner en cuenta que al usar el editor se cambia el fichero install.xml de la instalación, y es

importante tenerlo en cuenta si se desarrolla el módulo desde otra carpeta a la de

instalación.

13/31

Ilustración 2: Editor XMLDB mostrando las tablas de un módulo

Page 17: Tutorial: Creación de un módulo actividad. Moodle (1.9.3)gplsi.dlsi.ua.es/~slujan/materiales/creacion-modulo-moodle.pdf · 2.2 Instalación de Moodle ... nos en inglés y traducidos

5.4 Editar ficheros obligatorios.

• index.php: Solamente con cambiar newmodule por el nombre de nuestro módulo ya

listará todas las instancias del mismo.

• version.php: con la fecha de que identifica a la versión. El valor que utilicemos lo

tendremos en cuenta en el fichero db/update.php.

• Ficheros de idioma: En inglés ha de estar para facilitar la traducción a otros idiomas es

el lang/en_utf8/ejemplo.php y en castellano lang/es_utf8/ejemplo.php

5.5 Editar view.php.

Este fichero es quizás el más importante de un módulo ya que muestra la instancia,

es decir, muestra la nueva actividad.

En la plantilla, como en los anteriores, substituyendo newmodule por el nombre de

nuestro módulo tendremos la base para crear nuestra actividad ya que en una variable

14/31

Ilustración 3: Editor XMLDB de tabla

Page 18: Tutorial: Creación de un módulo actividad. Moodle (1.9.3)gplsi.dlsi.ua.es/~slujan/materiales/creacion-modulo-moodle.pdf · 2.2 Instalación de Moodle ... nos en inglés y traducidos

tendremos todos los valores de la instancia. A partir de ahí ya es cosa del desarrollador

darle la funcionalidad deseada a la actividad.

6 Instalación del módulo.

Una vez que el módulo esté creado y programado correctamente, habrá que situarlo dentro

de la carpeta ...moodle/mod/nombremodulo. En esta carpeta es donde están situados todos

los módulos del programa. El siguiente paso es entrar en el sistema como administrador y diri-

gir el navegador hacia la página http://suservidor/moodle/admin/index.php. Una vez realizado

este paso se crearán las tablas de la base de datos automáticamente y se podrá usar el módu-

lo.

Para actualizar un módulo se seguirá el mismo proceso, pero en esta ocasión la plataforma

ejecutará las acciones descritas en el update.php del módulo.

6.1 Desinstalación de la actividad.

Para eliminar un módulo instalado hay que acceder a la plataforma como administra-

dor y situarse en la página de actividades desde la ruta Administración -> Módulos ->

Actividades, pinchando en el enlace borrar del módulo que se desee desinstalar, como

se puede comprobar en la ilustración 4.

15/31

Ilustración 4: Menú de gestión de actividades

Page 19: Tutorial: Creación de un módulo actividad. Moodle (1.9.3)gplsi.dlsi.ua.es/~slujan/materiales/creacion-modulo-moodle.pdf · 2.2 Instalación de Moodle ... nos en inglés y traducidos

Las tablas de los módulos empiezan por mld_nombremodulo y al desinstalarlo se eli-

minan tanto las tablas como los datos. Si esto no sucediera automáticamente habría

que eliminar las tablas de forma manual.

16/31

Page 20: Tutorial: Creación de un módulo actividad. Moodle (1.9.3)gplsi.dlsi.ua.es/~slujan/materiales/creacion-modulo-moodle.pdf · 2.2 Instalación de Moodle ... nos en inglés y traducidos

Bibliografía[TUTORIAL_1_6]: Tutorial para la creación de un módulo en Moodle 1.6,

http://moodle.org/mod/forum/discuss.php?d=75378

[MANMOODLE_ES]: Manuales de Moodle, http://docs.moodle.org/es/Manuales_de_Moodle

[MANMOODLE_EN]: Getting started for teachers,

http://docs.moodle.org/en/Getting_started_for_teachers

[MANCODIGO_ES]: Manuales de Moodle, http://docs.moodle.org/es/Manual_de_Estilo_de_C

%C3%B3digo

[MODINSTALL_ES]: Instalación de moodle, http://docs.moodle.org/es/Instalaci%C3%B3n_de_moodle

[MOODINSTALL_EN]: Installing Moodle, http://docs.moodle.org/en/Installing_Moodle

[MOODAMP_ES]: Instalación AMP, http://docs.moodle.org/es/Instalaci%C3%B3n_AMP

[MOODAMP_EN]: Installing AMP, http://docs.moodle.org/en/Installing_AMP

[MAMP_WIN]: Moodle packages for Windows, http://download.moodle.org/windows/

[MAMP_MAC]: Moodle packages for Mac OS X, http://download.moodle.org/macosx/

[MOODDOWN]: Moodle Packages, http://download.moodle.org/

[MOODFAQ_ES]: FAQ Instalación, http://docs.moodle.org/es/FAQ_Instalaci%C3%B3n

[MODUPDATE_ES]: Actualización de moodle, http://docs.moodle.org/es/Actualizaci

%C3%B3n_de_moodle

[MODACT_EN]: Development:Modules, http://docs.moodle.org/en/Development:Modules

[REF_GET_STRING]: Function get_string, http://phpdocs.moodle.org/19/moodlecore/_lib---

moodlelib.php.html#functionget_string

[MOODROL_ES]: Roles, http://docs.moodle.org/es/Roles

[REF_HAS_CAPABILITIES]: has_capability:This function returns whether the current user has the

capability of performing a function, http://phpdocs.moodle.org/19/default/_lib---

accesslib.php.html#functionhas_capability

[REF_LIB_MOD_FORM]: Development:lib/formslib.php Form Definition,

http://docs.moodle.org/en/Development:lib/formslib.php_Form_Definition

[REF_INSTALL_XML]: Development:XMLDB defining an XML structure,

http://docs.moodle.org/en/Development:XMLDB_defining_an_XML_structure

[REF_GET_RECORDS]: Function get_records, http://xref.moodle.org/_functions/get_records.html

[REF_INSERT_RECORDS]: Insert a record into a table and return the "id" field if required,

http://phpdocs.moodle.org/19/default/_lib---dmllib.php.html#functioninsert_record

[REF_UPDATE_RECORD]: Update a record in a table, http://phpdocs.moodle.org/19/default/_lib---

dmllib.php.html#functionupdate_record

[REF_DELETE_RECORDS]: Delete the records from a table where all the given fields match the given

values., http://phpdocs.moodle.org/19/default/_lib---dmllib.php.html#functiondelete_records

[REF_DELETE_RECORDS_SELECT]: Delete one or more records from a table, http://phpdocs.moodle.org/

19/default/_lib---dmllib.php.html#functiondelete_records_select

[NEWMOD]: Plantilla para nuevo módulo, http://download.moodle.org/plugins/mod/NEWMODULE.zip

17/31

Page 21: Tutorial: Creación de un módulo actividad. Moodle (1.9.3)gplsi.dlsi.ua.es/~slujan/materiales/creacion-modulo-moodle.pdf · 2.2 Instalación de Moodle ... nos en inglés y traducidos

ANEXOSANEXO I: Código fuente de assigment.

mod_form.php<?phprequire_once ($CFG->dirroot.'/course/moodleform_mod.php');

class mod_assignment_mod_form extends moodleform_mod {

function definition() {global $CFG;$mform =& $this->_form;

// this hack is needed for different settings of each subtypeif (!empty($this->_instance)) {if($ass = get_record('assignment', 'id', (int)$this->_instance)) {$type = $ass->assignmenttype;

} else {error('incorrect assignment');

}} else {$type = required_param('type', PARAM_ALPHA);

}$mform->addElement('hidden', 'assignmenttype', $type);$mform->setDefault('assignmenttype', $type);$mform->addElement('hidden', 'type', $type);$mform->setDefault('type', $type);

require($CFG->dirroot.'/mod/assignment/type/'.$type.'/assignment.class.php');$assignmentclass = 'assignment_'.$type;$assignmentinstance = new $assignmentclass();

//-------------------------------------------------------------------------------$mform->addElement('header', 'general', get_string('general', 'form'));

$mform->addElement('text','name',get_string('assignmentname', 'assignment'),array('size'=> '64'));

if (!empty($CFG->formatstringstriptags)) {$mform->setType('name', PARAM_TEXT);

} else {$mform->setType('name', PARAM_CLEAN);

}$mform->addRule('name', null, 'required', null, 'client');

$mform->addElement('htmleditor', 'description', get_string('description', 'assignment'));$mform->setType('description', PARAM_RAW);$mform->setHelpButton('description', array('writing', 'questions', 'richtext'), false,

'editorhelpbutton');$mform->addRule('description', get_string('required'), 'required', null, 'client');

$mform->addElement('modgrade', 'grade', get_string('grade'));$mform->setDefault('grade', 100);

$mform->addElement('date_time_selector', 'timeavailable', get_string('availabledate', 'assignment'), array('optional'=>true));

$mform->setDefault('timeavailable', time());$mform->addElement('date_time_selector', 'timedue', get_string('duedate', 'assignment'),

array('optional'=>true));$mform->setDefault('timedue', time()+7*24*3600);

$ynoptions = array( 0 => get_string('no'), 1 => get_string('yes'));

$mform->addElement('select', 'preventlate', get_string('preventlate', 'assignment'), $ynoptions);$mform->setDefault('preventlate', 0);

$mform->addElement('header', 'typedesc', get_string('type'.$type,'assignment'));$assignmentinstance->setup_elements($mform);

$features = new stdClass;$features->groups = true;$features->groupings = true;$features->groupmembersonly = true;$this->standard_coursemodule_elements($features);

$this->add_action_buttons();}

}?>

18/31

Page 22: Tutorial: Creación de un módulo actividad. Moodle (1.9.3)gplsi.dlsi.ua.es/~slujan/materiales/creacion-modulo-moodle.pdf · 2.2 Instalación de Moodle ... nos en inglés y traducidos

install.xml<?xml version="1.0" encoding="UTF-8" ?><XMLDB PATH="mod/assignment/db" VERSION="20070919" COMMENT="XMLDB file for Moodle mod/assignment"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:noNamespaceSchemaLocation="../../../lib/xmldb/xmldb.xsd"

><TABLES><TABLE NAME="assignment" COMMENT="Defines assignments" NEXT="assignment_submissions"><FIELDS><FIELD NAME="id" TYPE="int" LENGTH="10" NOTNULL="true" UNSIGNED="true" SEQUENCE="true"

ENUM="false" NEXT="course"/><FIELD NAME="course" TYPE="int" LENGTH="10" NOTNULL="true" UNSIGNED="true" DEFAULT="0"

SEQUENCE="false" ENUM="false" PREVIOUS="id" NEXT="name"/><FIELD NAME="name" TYPE="char" LENGTH="255" NOTNULL="true" SEQUENCE="false" ENUM="false"

PREVIOUS="course" NEXT="description"/><FIELD NAME="description" TYPE="text" LENGTH="small" NOTNULL="true" SEQUENCE="false"

ENUM="false" PREVIOUS="name" NEXT="format"/><FIELD NAME="format" TYPE="int" LENGTH="4" NOTNULL="true" UNSIGNED="true" DEFAULT="0"

SEQUENCE="false" ENUM="false" PREVIOUS="description" NEXT="assignmenttype"/><FIELD NAME="assignmenttype" TYPE="char" LENGTH="50" NOTNULL="true" SEQUENCE="false"

ENUM="false" PREVIOUS="format" NEXT="resubmit"/><FIELD NAME="resubmit" TYPE="int" LENGTH="2" NOTNULL="true" UNSIGNED="true" DEFAULT="0"

SEQUENCE="false" ENUM="false" PREVIOUS="assignmenttype" NEXT="preventlate"/><FIELD NAME="preventlate" TYPE="int" LENGTH="2" NOTNULL="true" UNSIGNED="true" DEFAULT="0"

SEQUENCE="false" ENUM="false" PREVIOUS="resubmit" NEXT="emailteachers"/><FIELD NAME="emailteachers" TYPE="int" LENGTH="2" NOTNULL="true" UNSIGNED="true" DEFAULT="0"

SEQUENCE="false" ENUM="false" PREVIOUS="preventlate" NEXT="var1"/><FIELD NAME="var1" TYPE="int" LENGTH="10" NOTNULL="false" UNSIGNED="false" DEFAULT="0"

SEQUENCE="false" ENUM="false" PREVIOUS="emailteachers" NEXT="var2"/><FIELD NAME="var2" TYPE="int" LENGTH="10" NOTNULL="false" UNSIGNED="false" DEFAULT="0"

SEQUENCE="false" ENUM="false" PREVIOUS="var1" NEXT="var3"/><FIELD NAME="var3" TYPE="int" LENGTH="10" NOTNULL="false" UNSIGNED="false" DEFAULT="0"

SEQUENCE="false" ENUM="false" PREVIOUS="var2" NEXT="var4"/><FIELD NAME="var4" TYPE="int" LENGTH="10" NOTNULL="false" UNSIGNED="false" DEFAULT="0"

SEQUENCE="false" ENUM="false" PREVIOUS="var3" NEXT="var5"/><FIELD NAME="var5" TYPE="int" LENGTH="10" NOTNULL="false" UNSIGNED="false" DEFAULT="0"

SEQUENCE="false" ENUM="false" PREVIOUS="var4" NEXT="maxbytes"/><FIELD NAME="maxbytes" TYPE="int" LENGTH="10" NOTNULL="true" UNSIGNED="true" DEFAULT="100000"

SEQUENCE="false" ENUM="false" PREVIOUS="var5" NEXT="timedue"/><FIELD NAME="timedue" TYPE="int" LENGTH="10" NOTNULL="true" UNSIGNED="true" DEFAULT="0"

SEQUENCE="false" ENUM="false" PREVIOUS="maxbytes" NEXT="timeavailable"/><FIELD NAME="timeavailable" TYPE="int" LENGTH="10" NOTNULL="true" UNSIGNED="true" DEFAULT="0"

SEQUENCE="false" ENUM="false" PREVIOUS="timedue" NEXT="grade"/><FIELD NAME="grade" TYPE="int" LENGTH="10" NOTNULL="true" UNSIGNED="false" DEFAULT="0"

SEQUENCE="false" ENUM="false" PREVIOUS="timeavailable" NEXT="timemodified"/><FIELD NAME="timemodified" TYPE="int" LENGTH="10" NOTNULL="true" UNSIGNED="true" DEFAULT="0"

SEQUENCE="false" ENUM="false" PREVIOUS="grade"/></FIELDS><KEYS><KEY NAME="primary" TYPE="primary" FIELDS="id" />

</KEYS><INDEXES><INDEX NAME="course" UNIQUE="false" FIELDS="course"/>

</INDEXES></TABLE>

<TABLE NAME="assignment_submissions" COMMENT="Info about submitted assignments" PREVIOUS="assignment">

<FIELDS><FIELD NAME="id" TYPE="int" LENGTH="10" NOTNULL="true" UNSIGNED="true" SEQUENCE="true"

ENUM="false" NEXT="assignment"/><FIELD NAME="assignment" TYPE="int" LENGTH="10" NOTNULL="true" UNSIGNED="true" DEFAULT="0"

SEQUENCE="false" ENUM="false" PREVIOUS="id" NEXT="userid"/><FIELD NAME="userid" TYPE="int" LENGTH="10" NOTNULL="true" UNSIGNED="true" DEFAULT="0"

SEQUENCE="false" ENUM="false" PREVIOUS="assignment" NEXT="timecreated"/><FIELD NAME="timecreated" TYPE="int" LENGTH="10" NOTNULL="true" UNSIGNED="true" DEFAULT="0"

SEQUENCE="false" ENUM="false" PREVIOUS="userid" NEXT="timemodified"/><FIELD NAME="timemodified" TYPE="int" LENGTH="10" NOTNULL="true" UNSIGNED="true" DEFAULT="0"

SEQUENCE="false" ENUM="false" PREVIOUS="timecreated" NEXT="numfiles"/><FIELD NAME="numfiles" TYPE="int" LENGTH="10" NOTNULL="true" UNSIGNED="true" DEFAULT="0"

SEQUENCE="false" ENUM="false" PREVIOUS="timemodified" NEXT="data1"/><FIELD NAME="data1" TYPE="text" LENGTH="small" NOTNULL="false" SEQUENCE="false" ENUM="false"

PREVIOUS="numfiles" NEXT="data2"/><FIELD NAME="data2" TYPE="text" LENGTH="small" NOTNULL="false" SEQUENCE="false" ENUM="false"

PREVIOUS="data1" NEXT="grade"/><FIELD NAME="grade" TYPE="int" LENGTH="11" NOTNULL="true" UNSIGNED="false" DEFAULT="0"

SEQUENCE="false" ENUM="false" PREVIOUS="data2" NEXT="submissioncomment"/><FIELD NAME="submissioncomment" TYPE="text" LENGTH="small" NOTNULL="true" SEQUENCE="false"

ENUM="false" PREVIOUS="grade" NEXT="format"/><FIELD NAME="format" TYPE="int" LENGTH="4" NOTNULL="true" UNSIGNED="true" DEFAULT="0"

SEQUENCE="false" ENUM="false" PREVIOUS="submissioncomment" NEXT="teacher"/><FIELD NAME="teacher" TYPE="int" LENGTH="10" NOTNULL="true" UNSIGNED="true" DEFAULT="0"

SEQUENCE="false" ENUM="false" PREVIOUS="format" NEXT="timemarked"/><FIELD NAME="timemarked" TYPE="int" LENGTH="10" NOTNULL="true" UNSIGNED="true" DEFAULT="0"

SEQUENCE="false" ENUM="false" PREVIOUS="teacher" NEXT="mailed"/>

19/31

Page 23: Tutorial: Creación de un módulo actividad. Moodle (1.9.3)gplsi.dlsi.ua.es/~slujan/materiales/creacion-modulo-moodle.pdf · 2.2 Instalación de Moodle ... nos en inglés y traducidos

<FIELD NAME="mailed" TYPE="int" LENGTH="1" NOTNULL="true" UNSIGNED="true" DEFAULT="0" SEQUENCE="false" ENUM="false" PREVIOUS="timemarked"/>

</FIELDS><KEYS><KEY NAME="primary" TYPE="primary" FIELDS="id" NEXT="assignment"/><KEY NAME="assignment" TYPE="foreign" FIELDS="assignment" REFTABLE="assignment" REFFIELDS="id"

PREVIOUS="primary"/></KEYS><INDEXES><INDEX NAME="userid" UNIQUE="false" FIELDS="userid" NEXT="mailed"/><INDEX NAME="mailed" UNIQUE="false" FIELDS="mailed" PREVIOUS="userid" NEXT="timemarked"/><INDEX NAME="timemarked" UNIQUE="false" FIELDS="timemarked" PREVIOUS="mailed"/>

</INDEXES></TABLE></TABLES><STATEMENTS><STATEMENT NAME="insert log_display" TYPE="insert" TABLE="log_display" COMMENT="Initial insert of

records on table log_display"><SENTENCES><SENTENCE TEXT="(module, action, mtable, field) VALUES ('assignment', 'view', 'assignment',

'name')" /><SENTENCE TEXT="(module, action, mtable, field) VALUES ('assignment', 'add', 'assignment',

'name')" /><SENTENCE TEXT="(module, action, mtable, field) VALUES ('assignment', 'update', 'assignment',

'name')" /><SENTENCE TEXT="(module, action, mtable, field) VALUES ('assignment', 'view submission',

'assignment', 'name')" /><SENTENCE TEXT="(module, action, mtable, field) VALUES ('assignment', 'upload', 'assignment',

'name')" /></SENTENCES>

</STATEMENT></STATEMENTS>

</XMLDB>

20/31

Page 24: Tutorial: Creación de un módulo actividad. Moodle (1.9.3)gplsi.dlsi.ua.es/~slujan/materiales/creacion-modulo-moodle.pdf · 2.2 Instalación de Moodle ... nos en inglés y traducidos

upgrade.php<?php //$Id: upgrade.php,v 1.7.2.5 2008/05/01 20:37:22 skodak Exp $

// This file keeps track of upgrades to// the assignment module//// Sometimes, changes between versions involve// alterations to database structures and other// major things that may break installations.//// The upgrade function in this file will attempt// to perform all the necessary actions to upgrade// your older installtion to the current version.//// If there's something it cannot do itself, it// will tell you what you need to do.//// The commands in here will all be database-neutral,// using the functions defined in lib/ddllib.php

function xmldb_assignment_upgrade($oldversion=0) {

global $CFG, $THEME, $db;

$result = true;

if ($result && $oldversion < 2007091900) { /// MDL-11268

/// Changing nullability of field data1 on table assignment_submissions to null$table = new XMLDBTable('assignment_submissions');$field = new XMLDBField('data1');$field->setAttributes(XMLDB_TYPE_TEXT, 'small', null, null, null, null, null, null, 'numfiles');

/// Launch change of nullability for field data1$result = $result && change_field_notnull($table, $field);

/// Changing nullability of field data2 on table assignment_submissions to null$field = new XMLDBField('data2');$field->setAttributes(XMLDB_TYPE_TEXT, 'small', null, null, null, null, null, null, 'data1');

/// Launch change of nullability for field data2$result = $result && change_field_notnull($table, $field);

}

if ($result && $oldversion < 2007091902) {// add draft tracking default to existing upload assignments$sql = "UPDATE {$CFG->prefix}assignment SET var4=1 WHERE assignmenttype='upload'";$result = execute_sql($sql);

}

//===== 1.9.0 upgrade line ======//

if ($result && $oldversion < 2007101511) {notify('Processing assignment grades, this may take a while if there are many assignments...',

'notifysuccess');// change grade typo to text if no grades MDL-13920require_once $CFG->dirroot.'/mod/assignment/lib.php';// too much debug output$db->debug = false;assignment_update_grades();$db->debug = true;

}

return $result;}

?>

21/31

Page 25: Tutorial: Creación de un módulo actividad. Moodle (1.9.3)gplsi.dlsi.ua.es/~slujan/materiales/creacion-modulo-moodle.pdf · 2.2 Instalación de Moodle ... nos en inglés y traducidos

access.php<?php//// Capability definitions for the assignment module.//// The capabilities are loaded into the database table when the module is// installed or updated. Whenever the capability definitions are updated,// the module version number should be bumped up.//// The system has four possible values for a capability:// CAP_ALLOW, CAP_PREVENT, CAP_PROHIBIT, and inherit (not set).////// CAPABILITY NAMING CONVENTION//// It is important that capability names are unique. The naming convention// for capabilities that are specific to modules and blocks is as follows:// [mod/block]/<component_name>:<capabilityname>//// component_name should be the same as the directory name of the mod or block.//// Core moodle capabilities are defined thus:// moodle/<capabilityclass>:<capabilityname>//// Examples: mod/forum:viewpost// block/recent_activity:view// moodle/site:deleteuser//// The variable name for the capability definitions array follows the format// $<componenttype>_<component_name>_capabilities//// For the core capabilities, the variable is $moodle_capabilities.

$mod_assignment_capabilities = array(

'mod/assignment:view' => array(

'captype' => 'read','contextlevel' => CONTEXT_MODULE,'legacy' => array('guest' => CAP_ALLOW,'student' => CAP_ALLOW,'teacher' => CAP_ALLOW,'editingteacher' => CAP_ALLOW,'admin' => CAP_ALLOW

)),

'mod/assignment:submit' => array(

'captype' => 'write','contextlevel' => CONTEXT_MODULE,'legacy' => array('student' => CAP_ALLOW

)),

'mod/assignment:grade' => array('riskbitmask' => RISK_XSS,

'captype' => 'write','contextlevel' => CONTEXT_MODULE,'legacy' => array('teacher' => CAP_ALLOW,'editingteacher' => CAP_ALLOW,'admin' => CAP_ALLOW

))

);

?>

22/31

Page 26: Tutorial: Creación de un módulo actividad. Moodle (1.9.3)gplsi.dlsi.ua.es/~slujan/materiales/creacion-modulo-moodle.pdf · 2.2 Instalación de Moodle ... nos en inglés y traducidos

settings.php<?php //$Id: settings.php,v 1.1.2.3 2008/01/24 20:29:36 skodak Exp $

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

$settings->add(new admin_setting_configselect('assignment_maxbytes', get_string('maximumsize', 'assignment'), get_string('configmaxbytes', 'assignment'), 1048576, get_max_upload_sizes($CFG->maxbytes)));

$options = array(ASSIGNMENT_COUNT_WORDS => trim(get_string('numwords', '')), ASSIGNMENT_COUNT_LETTERS => trim(get_string('numletters', '')));$settings->add(new admin_setting_configselect('assignment_itemstocount', get_string('itemstocount',

'assignment'),get_string('configitemstocount', 'assignment'), ASSIGNMENT_COUNT_WORDS, $options));

$settings->add(new admin_setting_configcheckbox('assignment_showrecentsubmissions', get_string('showrecentsubmissions', 'assignment'),get_string('configshowrecentsubmissions', 'assignment'), 1));

?>

23/31

Page 27: Tutorial: Creación de un módulo actividad. Moodle (1.9.3)gplsi.dlsi.ua.es/~slujan/materiales/creacion-modulo-moodle.pdf · 2.2 Instalación de Moodle ... nos en inglés y traducidos

Anexo II: Ficheros del módulo ejemplo.

mod_form.php<?php //$Id: mod_form.php,v 1.3 2008/08/10 08:05:15 mudrd8mz Exp $

/** * This file defines de main newmodule configuration form * It uses the standard core Moodle (>1.8) formslib. For * more info about them, please visit: * * http://docs.moodle.org/en/Development:lib/formslib.php * * The form must provide support for, at least these fields: * - name: text element of 64cc max * * Also, it's usual to use these fields: * - intro: one htmlarea element to describe the activity * (will be showed in the list of activities of * newmodule type (index.php) and in the header * of the newmodule main page (view.php). * - introformat: The format used to write the contents * of the intro field. It automatically defaults * to HTML when the htmleditor is used and can be * manually selected if the htmleditor is not used * (standard formats are: MOODLE, HTML, PLAIN, MARKDOWN) * See lib/weblib.php Constants and the format_text() * function for more info */

require_once ('moodleform_mod.php');

class mod_ejemplo_mod_form extends moodleform_mod {

function definition() {

global $COURSE;$mform =& $this->_form;

//-------------------------------------------------------------------------------/// Adding the "general" fieldset, where all the common settings are showed$mform->addElement('header', 'general', get_string('general', 'form'));

/// Adding the standard "name" field$mform->addElement('text', 'name', get_string('ejemploname', 'ejemplo'), array('size'=>'64'));$mform->setType('name', PARAM_TEXT);$mform->addRule('name', null, 'required', null, 'client');

/// Adding the optional "intro" and "introformat" pair of fields$mform->addElement('htmleditor', 'intro', get_string('ejemplointro', 'ejemplo'));$mform->setType('intro', PARAM_RAW);$mform->addRule('intro', get_string('required'), 'required', null, 'client');$mform->setHelpButton('intro', array('writing', 'richtext'), false, 'editorhelpbutton');

$mform->addElement('format', 'introformat', get_string('format'));

//-------------------------------------------------------------------------------/// Adding the rest of newmodule settings, spreeading all them into this fieldset/// or adding more fieldsets ('header' elements) if needed for better logic

$mform->addElement('header', 'ejemploheader', get_string('ejemploheader', 'ejemplo'));$mform->addElement('text', 'campotexto', get_string('ejemplofieldset', 'ejemplo'),

array('size'=>'64'));

//-------------------------------------------------------------------------------// add standard elements, common to all modules$this->standard_coursemodule_elements();

//-------------------------------------------------------------------------------// add standard buttons, common to all modules$this->add_action_buttons();

}}

?>

install.xml<?xml version="1.0" encoding="UTF-8" ?><XMLDB PATH="mod/ejemplo/db" VERSION="20090130" COMMENT="XMLDB file for Moodle mod/ejemplo"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:noNamespaceSchemaLocation="../../../lib/xmldb/xmldb.xsd"

>

24/31

Page 28: Tutorial: Creación de un módulo actividad. Moodle (1.9.3)gplsi.dlsi.ua.es/~slujan/materiales/creacion-modulo-moodle.pdf · 2.2 Instalación de Moodle ... nos en inglés y traducidos

<TABLES><TABLE NAME="ejemplo" COMMENT="Default comment for ejemplo, please edit me">

<FIELDS><FIELD NAME="id" TYPE="int" LENGTH="10" NOTNULL="true" UNSIGNED="true" SEQUENCE="true"

ENUM="false" NEXT="course"/><FIELD NAME="course" TYPE="int" LENGTH="10" NOTNULL="true" UNSIGNED="true" DEFAULT="0"

SEQUENCE="false" ENUM="false" COMMENT="Course ejemplo activity belongs to" PREVIOUS="id" NEXT="name"/>

<FIELD NAME="name" TYPE="char" LENGTH="255" NOTNULL="true" SEQUENCE="false" ENUM="false" COMMENT="name field for moodle instances" PREVIOUS="course" NEXT="intro"/>

<FIELD NAME="intro" TYPE="text" LENGTH="medium" NOTNULL="false" SEQUENCE="false" ENUM="false" COMMENT="General introduction of the ejemplo activity" PREVIOUS="name" NEXT="introformat"/>

<FIELD NAME="introformat" TYPE="int" LENGTH="4" NOTNULL="true" UNSIGNED="true" DEFAULT="0" SEQUENCE="false" ENUM="false" COMMENT="Format of the intro field (MOODLE, HTML, MARKDOWN...)" PREVIOUS="intro" NEXT="timecreated"/>

<FIELD NAME="timecreated" TYPE="int" LENGTH="10" NOTNULL="true" UNSIGNED="true" DEFAULT="0" SEQUENCE="false" ENUM="false" PREVIOUS="introformat" NEXT="timemodified"/>

<FIELD NAME="timemodified" TYPE="int" LENGTH="10" NOTNULL="true" UNSIGNED="true" DEFAULT="0" SEQUENCE="false" ENUM="false" PREVIOUS="timecreated"/>

</FIELDS><KEYS><KEY NAME="primary" TYPE="primary" FIELDS="id" /></KEYS>

<INDEXES><INDEX NAME="course" UNIQUE="false" FIELDS="course"/></INDEXES>

</TABLE></TABLES><STATEMENTS><STATEMENT NAME="insert log_display" TYPE="insert" TABLE="log_display" COMMENT="Initial insert of

records on table log_display. Each record describes how data will be showed by log reports."><SENTENCES><SENTENCE TEXT="(module, action, mtable, field) VALUES ('ejemplo', 'add', 'ejemplo', 'name')" /

><SENTENCE TEXT="(module, action, mtable, field) VALUES ('ejemplo', 'update', 'ejemplo',

'name')" /><SENTENCE TEXT="(module, action, mtable, field) VALUES ('ejemplo', 'view', 'ejemplo',

'name')" /></SENTENCES>

</STATEMENT></STATEMENTS>

</XMLDB>

upgrade.php<?php //$Id: upgrade.php,v 1.2 2007/08/08 22:36:54 stronk7 Exp $

// This file keeps track of upgrades to// the module//// Sometimes, changes between versions involve// alterations to database structures and other// major things that may break installations.//// The upgrade function in this file will attempt// to perform all the necessary actions to upgrade// your older installtion to the current version.//// If there's something it cannot do itself, it// will tell you what you need to do.//// The commands in here will all be database-neutral,// using the functions defined in lib/ddllib.php

function xmldb__upgrade($oldversion=0) {

global $CFG, $THEME, $db;

$result = true;return $result;

}

?>

25/31

Page 29: Tutorial: Creación de un módulo actividad. Moodle (1.9.3)gplsi.dlsi.ua.es/~slujan/materiales/creacion-modulo-moodle.pdf · 2.2 Instalación de Moodle ... nos en inglés y traducidos

GNU Free Documentation License

Version 1.3, 3 November 2008

Copyright © 2000, 2001, 2002, 2007, 2008 Free Software Foundation, Inc. <http://fsf.org/>

Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.

0. PREAMBLE

The purpose of this License is to make a manual, textbook, or other functional and useful document "free" in the sense of freedom: to assure everyone the effective freedom to copy and redistribute it, with or without modifying it, either commercially or noncom-mercially. Secondarily, this License preserves for the author and publisher a way to get credit for their work, while not being considered responsible for modifications made by others.

This License is a kind of "copyleft", which means that derivative works of the docu-ment must themselves be free in the same sense. It complements the GNU General Public Li-cense, which is a copyleft license designed for free software.

We have designed this License in order to use it for manuals for free software, becau-se free software needs free documentation: a free program should come with manuals provi-ding the same freedoms that the software does. But this License is not limited to softwa-re manuals; it can be used for any textual work, regardless of subject matter or whether it is published as a printed book. We recommend this License principally for works whose purpose is instruction or reference.

1. APPLICABILITY AND DEFINITIONS

This License applies to any manual or other work, in any medium, that contains a noti-ce placed by the copyright holder saying it can be distributed under the terms of this License. Such a notice grants a world-wide, royalty-free license, unlimited in duration, to use that work under the conditions stated herein. The "Document", below, refers to any such manual or work. Any member of the public is a licensee, and is addressed as "you". You accept the license if you copy, modify or distribute the work in a way requiring permission under copyright law.

A "Modified Version" of the Document means any work containing the Document or a portion of it, either copied verbatim, or with modifications and/or translated into ano-ther language.

A "Secondary Section" is a named appendix or a front-matter section of the Document that deals exclusively with the relationship of the publishers or authors of the Document to the Document's overall subject (or to related matters) and contains nothing that could fall directly within that overall subject. (Thus, if the Document is in part a textbook of mathematics, a Secondary Section may not explain any mathematics.) The relationship could be a matter of historical connection with the subject or with related matters, or of legal, commercial, philosophical, ethical or political position regarding them.

The "Invariant Sections" are certain Secondary Sections whose titles are designated, as being those of Invariant Sections, in the notice that says that the Document is relea-sed under this License. If a section does not fit the above definition of Secondary then it is not allowed to be designated as Invariant. The Document may contain zero Invariant Sections. If the Document does not identify any Invariant Sections then there are none.

The "Cover Texts" are certain short passages of text that are listed, as Front-Cover Texts or Back-Cover Texts, in the notice that says that the Document is released under

26/31

Page 30: Tutorial: Creación de un módulo actividad. Moodle (1.9.3)gplsi.dlsi.ua.es/~slujan/materiales/creacion-modulo-moodle.pdf · 2.2 Instalación de Moodle ... nos en inglés y traducidos

this License. A Front-Cover Text may be at most 5 words, and a Back-Cover Text may be at most 25 words.

A "Transparent" copy of the Document means a machine-readable copy, represented in a format whose specification is available to the general public, that is suitable for revi-sing the document straightforwardly with generic text editors or (for images composed of pixels) generic paint programs or (for drawings) some widely available drawing editor, and that is suitable for input to text formatters or for automatic translation to a va-riety of formats suitable for input to text formatters. A copy made in an otherwise Transparent file format whose markup, or absence of markup, has been arranged to thwart or discourage subsequent modification by readers is not Transparent. An image format is not Transparent if used for any substantial amount of text. A copy that is not "Transpa-rent" is called "Opaque".

Examples of suitable formats for Transparent copies include plain ASCII without ma-rkup, Texinfo input format, LaTeX input format, SGML or XML using a publicly available DTD, and standard-conforming simple HTML, PostScript or PDF designed for human modifica-tion. Examples of transparent image formats include PNG, XCF and JPG. Opaque formats in-clude proprietary formats that can be read and edited only by proprietary word proces-sors, SGML or XML for which the DTD and/or processing tools are not generally available, and the machine-generated HTML, PostScript or PDF produced by some word processors for output purposes only.

The "Title Page" means, for a printed book, the title page itself, plus such following pages as are needed to hold, legibly, the material this License requires to appear in the title page. For works in formats which do not have any title page as such, "Title Page" means the text near the most prominent appearance of the work's title, preceding the be-ginning of the body of the text.

The "publisher" means any person or entity that distributes copies of the Document to the public.

A section "Entitled XYZ" means a named subunit of the Document whose title either is precisely XYZ or contains XYZ in parentheses following text that translates XYZ in ano-ther language. (Here XYZ stands for a specific section name mentioned below, such as "Acknowledgements", "Dedications", "Endorsements", or "History".) To "Preserve the Title" of such a section when you modify the Document means that it remains a section "Entitled XYZ" according to this definition.

The Document may include Warranty Disclaimers next to the notice which states that this License applies to the Document. These Warranty Disclaimers are considered to be in-cluded by reference in this License, but only as regards disclaiming warranties: any other implication that these Warranty Disclaimers may have is void and has no effect on the meaning of this License.

2. VERBATIM COPYING

You may copy and distribute the Document in any medium, either commercially or noncom-mercially, provided that this License, the copyright notices, and the license notice sa-ying this License applies to the Document are reproduced in all copies, and that you add no other conditions whatsoever to those of this License. You may not use technical measu-res to obstruct or control the reading or further copying of the copies you make or distribute. However, you may accept compensation in exchange for copies. If you distribu-te a large enough number of copies you must also follow the conditions in section 3.

You may also lend copies, under the same conditions stated above, and you may publicly display copies.

3. COPYING IN QUANTITY

If you publish printed copies (or copies in media that commonly have printed covers) of the Document, numbering more than 100, and the Document's license notice requires Co-ver Texts, you must enclose the copies in covers that carry, clearly and legibly, all these Cover Texts: Front-Cover Texts on the front cover, and Back-Cover Texts on the back

27/31

Page 31: Tutorial: Creación de un módulo actividad. Moodle (1.9.3)gplsi.dlsi.ua.es/~slujan/materiales/creacion-modulo-moodle.pdf · 2.2 Instalación de Moodle ... nos en inglés y traducidos

cover. Both covers must also clearly and legibly identify you as the publisher of these copies. The front cover must present the full title with all words of the title equally prominent and visible. You may add other material on the covers in addition. Copying with changes limited to the covers, as long as they preserve the title of the Document and sa-tisfy these conditions, can be treated as verbatim copying in other respects.

If the required texts for either cover are too voluminous to fit legibly, you should put the first ones listed (as many as fit reasonably) on the actual cover, and continue the rest onto adjacent pages.

If you publish or distribute Opaque copies of the Document numbering more than 100, you must either include a machine-readable Transparent copy along with each Opaque copy, or state in or with each Opaque copy a computer-network location from which the general network-using public has access to download using public-standard network protocols a complete Transparent copy of the Document, free of added material. If you use the latter option, you must take reasonably prudent steps, when you begin distribution of Opaque co-pies in quantity, to ensure that this Transparent copy will remain thus accessible at the stated location until at least one year after the last time you distribute an Opaque copy (directly or through your agents or retailers) of that edition to the public.

It is requested, but not required, that you contact the authors of the Document well before redistributing any large number of copies, to give them a chance to provide you with an updated version of the Document.

4. MODIFICATIONS

You may copy and distribute a Modified Version of the Document under the conditions of sections 2 and 3 above, provided that you release the Modified Version under precisely this License, with the Modified Version filling the role of the Document, thus licensing distribution and modification of the Modified Version to whoever possesses a copy of it. In addition, you must do these things in the Modified Version:

* A. Use in the Title Page (and on the covers, if any) a title distinct from that of the Document, and from those of previous versions (which should, if there were any, be listed in the History section of the Document). You may use the same title as a previous version if the original publisher of that version gives permission.

* B. List on the Title Page, as authors, one or more persons or entities responsi-ble for authorship of the modifications in the Modified Version, together with at least five of the principal authors of the Document (all of its principal authors, if it has fewer than five), unless they release you from this requirement.

* C. State on the Title page the name of the publisher of the Modified Version, as the publisher.

* D. Preserve all the copyright notices of the Document.

* E. Add an appropriate copyright notice for your modifications adjacent to the other copyright notices.

* F. Include, immediately after the copyright notices, a license notice giving the public permission to use the Modified Version under the terms of this License, in the form shown in the Addendum below.

* G. Preserve in that license notice the full lists of Invariant Sections and re-quired Cover Texts given in the Document's license notice.

* H. Include an unaltered copy of this License.

* I. Preserve the section Entitled "History", Preserve its Title, and add to it an item stating at least the title, year, new authors, and publisher of the Modified Version as given on the Title Page. If there is no section Entitled "History" in the Document, create one stating the title, year, authors, and publisher of the Document as given on its Title Page, then add an item describing the Modified Version as stated in the pre-vious sentence.

* J. Preserve the network location, if any, given in the Document for public access to a Transparent copy of the Document, and likewise the network locations given in the Document for previous versions it was based on. These may be placed in the "History" section. You may omit a network location for a work that was published at least four ye-ars before the Document itself, or if the original publisher of the version it refers to gives permission.

28/31

Page 32: Tutorial: Creación de un módulo actividad. Moodle (1.9.3)gplsi.dlsi.ua.es/~slujan/materiales/creacion-modulo-moodle.pdf · 2.2 Instalación de Moodle ... nos en inglés y traducidos

* K. For any section Entitled "Acknowledgements" or "Dedications", Preserve the Title of the section, and preserve in the section all the substance and tone of each of the contributor acknowledgements and/or dedications given therein.

* L. Preserve all the Invariant Sections of the Document, unaltered in their text and in their titles. Section numbers or the equivalent are not considered part of the section titles.

* M. Delete any section Entitled "Endorsements". Such a section may not be inclu-ded in the Modified Version.

* N. Do not retitle any existing section to be Entitled "Endorsements" or to con-flict in title with any Invariant Section.

* O. Preserve any Warranty Disclaimers.

If the Modified Version includes new front-matter sections or appendices that qualify as Secondary Sections and contain no material copied from the Document, you may at your option designate some or all of these sections as invariant. To do this, add their titles to the list of Invariant Sections in the Modified Version's license notice. These titles must be distinct from any other section titles.

You may add a section Entitled "Endorsements", provided it contains nothing but endor-sements of your Modified Version by various parties—for example, statements of peer re-view or that the text has been approved by an organization as the authoritative defini-tion of a standard.

You may add a passage of up to five words as a Front-Cover Text, and a passage of up to 25 words as a Back-Cover Text, to the end of the list of Cover Texts in the Modified Version. Only one passage of Front-Cover Text and one of Back-Cover Text may be added by (or through arrangements made by) any one entity. If the Document already includes a co-ver text for the same cover, previously added by you or by arrangement made by the same entity you are acting on behalf of, you may not add another; but you may replace the old one, on explicit permission from the previous publisher that added the old one.

The author(s) and publisher(s) of the Document do not by this License give permission to use their names for publicity for or to assert or imply endorsement of any Modified Version.

5. COMBINING DOCUMENTS

You may combine the Document with other documents released under this License, under the terms defined in section 4 above for modified versions, provided that you include in the combination all of the Invariant Sections of all of the original documents, unmodi-fied, and list them all as Invariant Sections of your combined work in its license noti-ce, and that you preserve all their Warranty Disclaimers.

The combined work need only contain one copy of this License, and multiple identical Invariant Sections may be replaced with a single copy. If there are multiple Invariant Sections with the same name but different contents, make the title of each such section unique by adding at the end of it, in parentheses, the name of the original author or pu-blisher of that section if known, or else a unique number. Make the same adjustment to the section titles in the list of Invariant Sections in the license notice of the combi-ned work.

In the combination, you must combine any sections Entitled "History" in the various original documents, forming one section Entitled "History"; likewise combine any sections Entitled "Acknowledgements", and any sections Entitled "Dedications". You must delete all sections Entitled "Endorsements".

6. COLLECTIONS OF DOCUMENTS

You may make a collection consisting of the Document and other documents released under this License, and replace the individual copies of this License in the various do-cuments with a single copy that is included in the collection, provided that you follow the rules of this License for verbatim copying of each of the documents in all other respects.

29/31

Page 33: Tutorial: Creación de un módulo actividad. Moodle (1.9.3)gplsi.dlsi.ua.es/~slujan/materiales/creacion-modulo-moodle.pdf · 2.2 Instalación de Moodle ... nos en inglés y traducidos

You may extract a single document from such a collection, and distribute it individua-lly under this License, provided you insert a copy of this License into the extracted do-cument, and follow this License in all other respects regarding verbatim copying of that document.

7. AGGREGATION WITH INDEPENDENT WORKS

A compilation of the Document or its derivatives with other separate and independent documents or works, in or on a volume of a storage or distribution medium, is called an "aggregate" if the copyright resulting from the compilation is not used to limit the le-gal rights of the compilation's users beyond what the individual works permit. When the Document is included in an aggregate, this License does not apply to the other works in the aggregate which are not themselves derivative works of the Document.

If the Cover Text requirement of section 3 is applicable to these copies of the Docu-ment, then if the Document is less than one half of the entire aggregate, the Document's Cover Texts may be placed on covers that bracket the Document within the aggregate, or the electronic equivalent of covers if the Document is in electronic form. Otherwise they must appear on printed covers that bracket the whole aggregate.

8. TRANSLATION

Translation is considered a kind of modification, so you may distribute translations of the Document under the terms of section 4. Replacing Invariant Sections with transla-tions requires special permission from their copyright holders, but you may include translations of some or all Invariant Sections in addition to the original versions of these Invariant Sections. You may include a translation of this License, and all the li-cense notices in the Document, and any Warranty Disclaimers, provided that you also in-clude the original English version of this License and the original versions of those no-tices and disclaimers. In case of a disagreement between the translation and the original version of this License or a notice or disclaimer, the original version will prevail.

If a section in the Document is Entitled "Acknowledgements", "Dedications", or "History", the requirement (section 4) to Preserve its Title (section 1) will typically require changing the actual title.

9. TERMINATION

You may not copy, modify, sublicense, or distribute the Document except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, or distribute it is void, and will automatically terminate your rights under this License.

However, if you cease all violation of this License, then your license from a particu-lar copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the cop-yright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.

Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.

Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, receipt of a copy of some or all of the same material does not give you any rights to use it.

10. FUTURE REVISIONS OF THIS LICENSE

The Free Software Foundation may publish new, revised versions of the GNU Free Docu-mentation License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. See

30/31

Page 34: Tutorial: Creación de un módulo actividad. Moodle (1.9.3)gplsi.dlsi.ua.es/~slujan/materiales/creacion-modulo-moodle.pdf · 2.2 Instalación de Moodle ... nos en inglés y traducidos

http://www.gnu.org/copyleft/.

Each version of the License is given a distinguishing version number. If the Document specifies that a particular numbered version of this License "or any later version" ap-plies to it, you have the option of following the terms and conditions either of that specified version or of any later version that has been published (not as a draft) by the Free Software Foundation. If the Document does not specify a version number of this Li-cense, you may choose any version ever published (not as a draft) by the Free Software Foundation. If the Document specifies that a proxy can decide which future versions of this License can be used, that proxy's public statement of acceptance of a version perma-nently authorizes you to choose that version for the Document.

11. RELICENSING

"Massive Multiauthor Collaboration Site" (or "MMC Site") means any World Wide Web server that publishes copyrightable works and also provides prominent facilities for any-body to edit those works. A public wiki that anybody can edit is an example of such a server. A "Massive Multiauthor Collaboration" (or "MMC") contained in the site means any set of copyrightable works thus published on the MMC site.

"CC-BY-SA" means the Creative Commons Attribution-Share Alike 3.0 license published by Creative Commons Corporation, a not-for-profit corporation with a principal place of bu-siness in San Francisco, California, as well as future copyleft versions of that license published by that same organization.

"Incorporate" means to publish or republish a Document, in whole or in part, as part of another Document.

An MMC is "eligible for relicensing" if it is licensed under this License, and if all works that were first published under this License somewhere other than this MMC, and subsequently incorporated in whole or in part into the MMC, (1) had no cover texts or in-variant sections, and (2) were thus incorporated prior to November 1, 2008.

The operator of an MMC Site may republish an MMC contained in the site under CC-BY-SA on the same site at any time before August 1, 2009, provided the MMC is eligible for re-licensing.

31/31