moosh
moosh copied to clipboard
course_module id from activity id
How to get the id in the {course_modules} table from eg, the id in the {quiz} table (called 'instance' in {course_modules})?
Usage is quite high, I think. For example activity-add returns the activity instance id and activity-delete requires the course_modules id.
You need to be careful because it is easy to plug the activity instance id into activity-delete unthinkingly and thus delete a completely unrelated activity.
sql-run returns the required ids, but it is covered in print_r cruft.
I wrote a bash function to remove the cruft. (A command might be better as it could be used in a pipeline with xargs.)
function cm_id () {
local module activity_id module_string sqlrun_prefix sqlrun_suffix \
module_string_preshrunk module_id cm_string_preshrunk
module=$1
activity_id=$2
cd /var/www/cgi-bin/moodle || exit 1
module_string=$(Moosh -n sql-run "select id from {modules} where name='$module'")
sqlrun_prefix="
Record 1
stdClass Object
(
[id] => "
sqlrun_suffix="
)"
module_string_preshrunk=${module_string#"$sqlrun_prefix"}
module_id=${module_string_preshrunk%"$sqlrun_suffix"}
cm_string=$(Moosh -n sql-run "select id from {course_modules} where \
module=$module_id and instance=$activity_id")
cm_string_preshrunk=${cm_string#"$sqlrun_prefix"}
echo ${cm_string_preshrunk%"$sqlrun_suffix"}
cd - > /dev/null 2>&1
}
So I can do:
for n in {1..3}; do moosh -n activity-add -n "Test$n" -s 7 forum 44 | while IFS='<newline>' read -r item ; do cm_id forum $item ; done ; done
and
for n in {395..397} ; do cm_id forum $n | xargs Moosh -n activity-delete ; done
Yeah, not only that would be helpful for scripting - but I also look up the context / context_module information all the time, when investigating something data related.
This could be possibly implemented by extending info-context command that gives information about the context ID provided:
➜ moosh info-context 72
72, module: Quiz: quiz 3
Course: 16
Section: 1
http://localhost/vanilla37/mod/quiz/view.php?id=8
The command could even do some basic data interrogation - ie when you give it instance id without the module (plugin) name, it could list all possible matches.
There is actually a moodle function that does what my cm_id bash function does, get_coursemodule_from_instance
in lib/datalib.php
But making a moosh command out of it doesn't seem the right thing to do, because running it would not be something that made a change to your moodle cofiguration. It could only help some other moosh command.