merging MOODLE_19_QUESTIONS with HEAD
[moodle.git] / question / contextmoveq.php
1 <?php // $Id$
2 /**
3  * Page for moving questions
4  *
5  * @author me@jamiep.org
6  * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
7  * @package questionbank
8  */
10 // Includes.
11 require_once(dirname(__FILE__) . '/../config.php');
12 require_once(dirname(__FILE__) . '/editlib.php');
13 require_once($CFG->dirroot.'/question/contextmoveq_form.php');
15 $ids = required_param('ids',PARAM_SEQUENCE); // question ids
17 if (!$cmid = optional_param('cmid', 0, PARAM_INT)){
18     $courseid = required_param('courseid', PARAM_INT);
19 }
21 $tocatid = required_param('tocatid', PARAM_INT);
22 $returnurl = optional_param('returnurl', 0, PARAM_LOCALURL);
24 $thispageurl = new moodle_url();
25 $thispageurl->params(compact('tocatid', 'ids', 'returnurl'));
27 if ($cmid){
28     list($module, $cm) = get_module_from_cmid($cmid);
29     require_login($cm->course, false, $cm);
30     $thiscontext = get_context_instance(CONTEXT_MODULE, $cmid);
31     if (!$returnurl) {
32         $returnurl = "{$CFG->wwwroot}/question/edit.php?cmid={$cm->id}";
33     }
34     $thispageurl->param('cmid', $cmid);
35 } elseif ($courseid) {
36     require_login($courseid, false);
37     $thiscontext = get_context_instance(CONTEXT_COURSE, $courseid);
38     $module = null;
39     $cm = null;
40     if (!$returnurl) {
41         $returnurl = "{$CFG->wwwroot}/question/edit.php?courseid={$COURSE->id}";
42     }
43     $thispageurl->param('courseid', $COURSE->id);
44 } else {
45     error('Need to pass courseid or cmid to this script.');
46 }
49 if (!$questions = get_records_sql("SELECT q.*, c.contextid FROM {$CFG->prefix}question q, {$CFG->prefix}question_categories c  WHERE q.id IN ($ids) AND c.id = q.category")) {
50     print_error('questiondoesnotexist', 'question', $returnurl);
51 }
52 if (!$tocat = get_record('question_categories', 'id', $tocatid)){
53     print_error('categorydoesnotexist', 'question', $returnurl);
54 }
55 $tocat->context = get_context_instance_by_id($tocat->contextid);
56 require_capability('moodle/question:add', $tocat->context);
57 $tocoursefilesid =  get_filesdir_from_context($tocat->context);
58 $urls = array();
60 if ($tocoursefilesid == SITEID){
61     $toareaname = get_string('filesareasite', 'question');
62 } else {
63     $toareaname = get_string('filesareacourse', 'question');
64 }
65 $fromcoursefilesid = 0;
66 foreach (array_keys($questions) as $id){
67     question_require_capability_on($questions[$id], 'move');
68     get_question_options($questions[$id]);
69     $questions[$id]->context = get_context_instance_by_id($questions[$id]->contextid);
70     $thisfilesid =  get_filesdir_from_context($questions[$id]->context);
71     if ($fromcoursefilesid && $thisfilesid != $fromcoursefilesid){
72        error('You can\'t use this script to move questions that have files associated with them from different areas.');
73     } else {
74        $fromcoursefilesid =  $thisfilesid;
75     }
76     if ($tocoursefilesid != $fromcoursefilesid){
77         $urls = array_merge_recursive($urls, $QTYPES[$questions[$id]->qtype]->find_file_links($questions[$id], $fromcoursefilesid));
78     }
79 }
81 $brokenurls = array();
82 foreach (array_keys($urls) as $url){
83     if (!file_exists($CFG->dataroot."/$fromcoursefilesid/".$url)){
84         $brokenurls[] = $url;
85     }
86 }
87 if ($fromcoursefilesid == SITEID){
88     $fromareaname = get_string('filesareasite', 'question');
89 } else {
90     $fromareaname = get_string('filesareacourse', 'question');
91 }
93 $contextmoveform = new question_context_move_question_form($thispageurl,
94         compact('urls', 'fromareaname', 'toareaname', 'brokenurls',
95                     'fromcoursefilesid', 'tocoursefilesid'));
96 if ($contextmoveform->is_cancelled()){
97     redirect($returnurl);
98 }elseif ($moveformdata = $contextmoveform->get_data()) {
99     if (is_array($moveformdata->urls)){
100         check_dir_exists($CFG->dataroot."/$tocoursefilesid/", true);
101         $flipurls = array_keys($urls);
102         //actions on files
103         foreach ($moveformdata->urls as $key => $urlaction){
104             $source = $CFG->dataroot."/$fromcoursefilesid/".$flipurls[$key];
105             $destination = $flipurls[$key];
106             if (($urlaction != QUESTION_FILEDONOTHING) && ($urlaction != QUESTION_FILEMOVELINKSONLY)){
107                 while (file_exists($CFG->dataroot."/$tocoursefilesid/".$destination)){
108                     $matches = array();
109                     //check for '_'. copyno after filename, before extension.
110                     if (preg_match('!\_([0-9]+)(\.[^\.\\/]+)?$!', $destination, $matches)){
111                         $copyno = $matches[1]+1;
112                     } else {
113                         $copyno = 1;
114                     }
115                     //replace old copy no with incremented one.
116                     $destination = preg_replace('!(\_[0-9]+)?(\.[^\.\\/]+)?$!', '_'.$copyno.'\\2', $destination, 1);
117                 }
118             }
119             switch ($urlaction){
120                 case QUESTION_FILECOPY :
121                     if (!copy($source, $CFG->dataroot."/$tocoursefilesid/".$destination)){
122                         print_error('errorfilecannotbecopied', 'question', $onerrorurl, $source);
123                     }
124                     break;
125                 case QUESTION_FILEMOVE :
126                     if (!rename($source, $CFG->dataroot."/$tocoursefilesid/".$destination)){
127                         print_error('errorfilecannotbemoved', 'question', $onerrorurl, $source);
128                     }
129                     break;
130                 case QUESTION_FILEMOVELINKSONLY :
131                 case QUESTION_FILEDONOTHING :
132                     break;
133                 default :
134                     error('Invalid action selected!', $onerrorurl);
135             }
136             //now search and replace urls in questions.
137             switch ($urlaction){
138                 case QUESTION_FILECOPY :
139                 case QUESTION_FILEMOVE :
140                 case QUESTION_FILEMOVELINKSONLY :
141                     $url = $flipurls[$key];
142                     $questionswithlinks = array_unique($urls[$url]);
143                     foreach ($questionswithlinks as $questionid){
144                         $QTYPES[$questions[$questionid]->qtype]->replace_file_links($questions[$questionid], $fromcoursefilesid, $tocoursefilesid, $url, $destination);
145                     }
146                     break;
147                 case  QUESTION_FILEDONOTHING :
148                     break;
149                 default :
150                     error('Invalid action selected!', $onerrorurl);
151                     break;
152             }
155         }
156     }
157     //now move questions
158     if (!execute_sql("UPDATE {$CFG->prefix}question SET category = {$tocat->id} WHERE id IN ({$ids})", false)){
159         error("Could not move the questions {$ids} to category ".$tocat->name, $onerrorurl);
160     }
161     redirect($returnurl);
164 $streditingcategories = get_string('editcategories', 'quiz');
165 $crumbs = array();
166 if ($cmid) {
167     // Page header
168     $context = get_context_instance(CONTEXT_MODULE, $cm->id);
169     $strupdatemodule = has_capability('moodle/course:manageactivities', $context)
170         ? update_module_button($cm->id, $COURSE->id, get_string('modulename', $cm->modname))
171         : "";
172     $crumbs[] = array('name' => get_string('modulenameplural', $cm->modname),
173                         'link' => "$CFG->wwwroot/mod/{$cm->modname}/index.php?id=$COURSE->id",
174                         'type' => 'activity');
175     $crumbs[] = array('name' => format_string($module->name),
176                         'link' => "$CFG->wwwroot/mod/{$cm->modname}/view.php?id={$cm->id}",
177                         'type' => 'title');
178 } else {
179     // Print basic page layout.
180     $strupdatemodule = '';
182 $strmovingquestions = get_string('movingquestions', 'question');
183 $crumbs[] = array('name' => $strmovingquestions, 'link' => '', 'type' => 'title');
185 $navigation = build_navigation($crumbs);
186 print_header_simple($strmovingquestions, '', $navigation, "", "", true, $strupdatemodule);
188 // print tabs
189 if ($cm!==null) {
190     $currenttab = 'edit';
191     $mode = 'questions';
192     ${$cm->modname} = $module;
193     include($CFG->dirroot."/mod/{$cm->modname}/tabs.php");
194 } else {
195     $currenttab = 'questions';
196     include('tabs.php');
198 //parameter for get_string
199 $questionsstr = new object();
200 $questionsstr->tocontext = print_context_name($tocat->context);
201 $questionsstr->fromareaname = $fromareaname;
203 //comma seperated string "'xx', 'cx', 'sdf' and 'fgdhfg'"
204 $questionnamestojoin = array();
205 foreach ($questions as $question){
206    $questionnamestojoin[] =  $question->name;
208 $tojoincount = count($questionnamestojoin);
210 if ($tojoincount > 1){
211     $a = new object();
212     $a->one = $questionnamestojoin[$tojoincount -2].'"</strong>';
213     $a->two = '<strong>"'.$questionnamestojoin[$tojoincount -1];
214     $questionnamestojoin[$tojoincount -2] = get_string('and', '', $a);
215     unset($questionnamestojoin[$tojoincount -1]);
217 $questionsstr->questions = '<strong>"'.join($questionnamestojoin, '"</strong>, <strong>"').'"</strong>';
219 if (count($urls)){
220     $defaults = array();
221     for ($default_key =0; $default_key < count($urls); $default_key++){
222         switch ($tocoursefilesid){
223             case SITEID:
224                 $defaults['urls'][$default_key] = QUESTION_FILEMOVE;
225                 break;
226             default :
227                 $defaults['urls'][$default_key] = QUESTION_FILECOPY;
228                 break;
230         }
231     }
232     $contextmoveform->set_data($defaults);
234     //some parameters for get_string
235     $questionsstr->urlcount = count($urls);
237     $questionsstr->toareaname = $toareaname;
239     print_box(get_string('movingquestionsandfiles', 'question', $questionsstr), 'boxwidthnarrow boxaligncenter generalbox');
240 } else {
241     print_box(get_string('movingquestionsnofiles', 'question', $questionsstr), 'boxwidthnarrow boxaligncenter generalbox');
243 $contextmoveform->display();
244 print_footer($COURSE);
245 ?>