]> git.mjollnir.org Git - moodle.git/commitdiff
MDL-16493 file and picture element migrated; waiting for file picker to mature, prese...
authorskodak <skodak>
Sun, 14 Sep 2008 08:22:44 +0000 (08:22 +0000)
committerskodak <skodak>
Sun, 14 Sep 2008 08:22:44 +0000 (08:22 +0000)
18 files changed:
mod/data/db/upgrade.php
mod/data/field/checkbox/field.class.php
mod/data/field/date/field.class.php
mod/data/field/file/field.class.php
mod/data/field/latlong/field.class.php
mod/data/field/menu/field.class.php
mod/data/field/multimenu/field.class.php
mod/data/field/number/field.class.php
mod/data/field/picture/field.class.php
mod/data/field/radiobutton/field.class.php
mod/data/field/text/field.class.php
mod/data/field/textarea/field.class.php
mod/data/field/url/field.class.php
mod/data/lib.php
mod/data/preset_class.php [deleted file]
mod/data/preset_new.php [deleted file]
mod/data/version.php
mod/data/view.php

index e0731452ec1fc4983b8a9ffd8a1bc7f164c1d572..5ffbde45faa09b7ee040e8319de4757a58f8ceb4 100644 (file)
@@ -40,7 +40,7 @@ function xmldb_data_upgrade($oldversion) {
         upgrade_mod_savepoint($result, 2007101512, 'data');
     }
 
-    if ($result && $oldversion <  2007101513) {
+    if ($result && $oldversion < 2007101513) {
         // Upgrade all the data->notification currently being
         // NULL to 0
         $sql = "UPDATE {data} SET notification=0 WHERE notification IS NULL";
@@ -56,15 +56,97 @@ function xmldb_data_upgrade($oldversion) {
     }
 
     if ($result && $oldversion < 2008081400) {
-        if ($datainstances = $DB->get_records('data')) {
+        if ($rs = $DB->get_recordset('data')) {
             $pattern = '/\#\#delete\#\#(\s+)\#\#approve\#\#/';
             $replacement = '##delete##$1##approve##$1##export##';
-            foreach ($datainstances as $data) {
+            foreach ($rs as $data) {
                 $data->listtemplate = preg_replace($pattern, $replacement, $data->listtemplate);
                 $data->singletemplate = preg_replace($pattern, $replacement, $data->singletemplate);
                 $DB->update_record('data', $data);
             }
+            $rs->close();
         }
+        upgrade_mod_savepoint($result, 2008081400, 'data');
+    }
+
+    if ($result && $oldversion < 2008091400) {
+
+        /////////////////////////////////////
+        /// new file storage upgrade code ///
+        /////////////////////////////////////
+
+        $fs = get_file_storage();
+
+        $empty = $DB->sql_empty(); // silly oracle empty string handling workaround
+
+        $sqlfrom = "FROM {data_content} c
+                    JOIN {data_fields} f     ON f.id = c.fieldid
+                    JOIN {data_records} r    ON r.id = c.recordid
+                    JOIN {data} d            ON d.id = r.dataid
+                    JOIN {modules} m         ON m.name = 'data'
+                    JOIN {course_modules} cm ON (cm.module = m.id AND cm.instance = d.id)
+                   WHERE c.content <> '$empty' AND c.content IS NOT NULL
+                         AND (f.type = 'file' OR f.type = 'picture')";
+
+        $count = $DB->count_records_sql("SELECT COUNT('x') $sqlfrom");
+
+        if ($rs = $DB->get_recordset_sql("SELECT c.id, f.type, r.dataid, c.recordid, f.id AS fieldid, r.userid, c.content, c.content1, d.course, r.userid, cm.id AS cmid $sqlfrom ORDER BY d.course, d.id")) {
+
+            $pbar = new progress_bar('migratedatafiles', 500, true);
+
+            $olddebug = $DB->get_debug();
+            $DB->set_debug(false); // lower debug level, there might be very many files
+            $i = 0;
+            foreach ($rs as $content) {
+                $i++;
+                upgrade_set_timeout(60); // set up timeout, may also abort execution
+                $pbar->update($i, $count, "Migrating data entries - $i/$count.");
+
+                $filepath = "$CFG->dataroot/$content->course/$CFG->moddata/data/$content->dataid/$content->fieldid/$content->recordid/$content->content";
+                $context = get_context_instance(CONTEXT_MODULE, $content->cmid);
+
+                if (!file_exists($filepath)) {
+                    continue;
+                }
+
+                $filearea = 'data_content';
+                $oldfilename = $content->content;
+                $filename    = clean_param($oldfilename, PARAM_FILE);
+                if ($filename === '') {
+                    continue;
+                }
+                if (!$fs->file_exists($context->id, $filearea, $content->id, '/', $filename)) {
+                    $file_record = array('contextid'=>$context->id, 'filearea'=>$filearea, 'itemid'=>$content->id, 'filepath'=>'/', 'filename'=>$filename, 'userid'=>$content->userid);
+                    if ($fs->create_file_from_pathname($file_record, $filepath)) {
+                        unlink($filepath);
+                        if ($oldfilename !== $filename) {
+                            // update filename if needed
+                            $DB->set_field('data_content', 'content', $filename, array('id'=>$content->id));
+                        }
+                        if ($content->type == 'picture') {
+                            // migrate thumb
+                            $filepath = "$CFG->dataroot/$content->course/$CFG->moddata/data/$content->dataid/$content->fieldid/$content->recordid/thumb/$content->content";
+                            if (!$fs->file_exists($context->id, $filearea, $content->id, '/', 'thumb_'.$filename)) {
+                                $file_record['filename'] = 'thumb_'.$file_record['filename'];
+                                $fs->create_file_from_pathname($file_record, $filepath);
+                                unlink($filepath);
+                            }
+                        }
+                    }
+                }
+
+                // remove dirs if empty
+                @rmdir("$CFG->dataroot/$content->course/$CFG->moddata/data/$content->dataid/$content->fieldid/$content->recordid/thumb");
+                @rmdir("$CFG->dataroot/$content->course/$CFG->moddata/data/$content->dataid/$content->fieldid/$content->recordid");
+                @rmdir("$CFG->dataroot/$content->course/$CFG->moddata/data/$content->dataid/$content->fieldid");
+                @rmdir("$CFG->dataroot/$content->course/$CFG->moddata/data/$content->dataid");
+                @rmdir("$CFG->dataroot/$content->course/$CFG->moddata/data");
+                @rmdir("$CFG->dataroot/$content->course/$CFG->moddata");
+            }
+            $DB->set_debug($olddebug); // reset debug level
+            $rs->close();
+        }
+        upgrade_mod_savepoint($result, 2008091400, 'data');
     }
 
     return $result;
index 607ea4171a9763cda52f22135b78f9fc08868b41..b319df79c4f29e344925050a5edd3bc7a33d4ca3 100755 (executable)
@@ -26,10 +26,6 @@ class data_field_checkbox extends data_field_base {
 
     var $type = 'checkbox';
 
-    function data_field_checkbox($field=0, $data=0) {
-        parent::data_field_base($field, $data);
-    }
-
     function display_add_field($recordid=0) {
         global $CFG, $DB;
 
index ab438375bc5090e33ffcaad1afdc219c59b70e47..6d7297cd1193c45c50791cf90a42c84766c684e6 100755 (executable)
@@ -34,10 +34,6 @@ class data_field_date extends data_field_base {
     var $month = 0;
     var $year  = 0;
 
-    function data_field_date($field=0, $data=0) {
-        parent::data_field_base($field, $data);
-    }
-
     function display_add_field($recordid=0) {
         global $DB;
 
index fff1789db36a8a36803a4abc40eb65e3c5397edf..f83b68ff19636516bcd5f293246be260ba73c96f 100755 (executable)
 class data_field_file extends data_field_base {
     var $type = 'file';
 
-    function data_field_file($field=0, $data=0) {
-        parent::data_field_base($field, $data);
-    }
-
     function display_add_field($recordid=0) {
         global $CFG, $DB;
+
+        $file        = false;
+        $content     = false;
+        $displayname = '';
+        $fs = get_file_storage();
         if ($recordid){
             if ($content = $DB->get_record('data_content', array('fieldid'=>$this->field->id, 'recordid'=>$recordid))) {
-                $contents[0] = $content->content;
-                $contents[1] = $content->content1;
-            } else {
-                $contents[0] = '';
-                $contents[1] = '';
+                if (!empty($content->content)) {
+                    if ($file = $FS->get_file($this->context->id, 'data_content', $content->id, '/', $content->content)) {
+                        if (empty($content->content1)) {
+                            $displayname = $file->get_filename();
+                        } else {
+                            $displayname = $content->content1;
+                        }
+                    }
+                }
             }
-            $src         = empty($contents[0]) ? '' : $contents[0];
-            $name        = empty($contents[1]) ? $src : $contents[1];
-            $displayname = empty($contents[1]) ? '' : $contents[1];
-            require_once($CFG->libdir.'/filelib.php');
-            $source = get_file_url($this->data->course.'/'.$CFG->moddata.'/data/'.$this->data->id.'/'.$this->field->id.'/'.$recordid);
-        } else {
-            $src = '';
-            $name = '';
-            $displayname = '';
-            $source = '';
         }
-        $str = '<div title="' . s($this->field->description) . '">';
+
+        $str = '<div title="'.s($this->field->description).'">';
         $str .= '<fieldset><legend><span class="accesshide">'.$this->field->name.'</span></legend>';
         $str .= '<input type="hidden" name ="field_'.$this->field->id.'_file" value="fakevalue" />';
-        $str .= get_string('file','data'). ' <input type="file" name ="field_'.$this->field->id.'" id="field_'.
+        $str .= get_string('file','data').' <input type="file" name ="field_'.$this->field->id.'" id="field_'.
                             $this->field->id.'" title="'.s($this->field->description).'" /><br />';
-        $str .= get_string('optionalfilename','data').' <input type="text" name="field_' .$this->field->id.'_filename"
+        $str .= get_string('optionalfilename','data').' <input type="text" name="field_'.$this->field->id.'_filename"
                             id="field_'.$this->field->id.'_filename" value="'.s($displayname).'" /><br />';
-        $str .= '<input type="hidden" name="MAX_FILE_SIZE" value="'.s($this->field->param3).'" />';
+        //$str .= '<input type="hidden" name="MAX_FILE_SIZE" value="'.s($this->field->param3).'" />';
         $str .= '</fieldset>';
         $str .= '</div>';
-        if ($recordid and isset($content) and !empty($content->content)) {
-            // Print icon
-            require_once($CFG->libdir.'/filelib.php');
-            $icon = mimeinfo('icon', $src);
+        if ($file) {
+            // Print icon if file already exists
+            $browser = get_file_browser();
+            $icon    = mimeinfo_from_type('icon', $file->get_mimetype());
+            $src     = $browser->encodepath($CFG->wwwroot.'/pluginfile.php', $this->context->id.'/data_content/'.$content->id.'/'.$file->get_filename());
             $str .= '<img src="'.$CFG->pixpath.'/f/'.$icon.'" class="icon" alt="'.$icon.'" />'.
-                    '<a href="'.$source.'/'.$src.'" >'.$name.'</a>';
+                    '<a href="'.$src.'" >'.s($file->get_filename()).'</a>';
         }
         return $str;
     }
@@ -93,20 +90,27 @@ class data_field_file extends data_field_base {
         global $CFG, $DB;
 
         if (!$content = $DB->get_record('data_content', array('fieldid'=>$this->field->id, 'recordid'=>$recordid))) {
-            return false;
+            return '';
         }
-        $width = $this->field->param1 ? ' width = "'.s($this->field->param1).'" ':' ';
-        $height = $this->field->param2 ? ' height = "'.s($this->field->param2).'" ':' ';
+
         if (empty($content->content)) {
             return '';
         }
-        require_once($CFG->libdir.'/filelib.php');
-        $src  = $content->content;
-        $name = empty($content->content1) ? $src : $content->content1;
-        $source = get_file_url($this->data->course.'/'.$CFG->moddata.'/data/'.$this->data->id.'/'.$this->field->id.'/'.$recordid);
-        $icon = mimeinfo('icon', $src);
+
+        $fs      = get_file_storage();
+        $browser = get_file_browser();
+        if (!$file = $fs->get_file($this->context->id, 'data_content', $content->id, '/', $content->content)) {
+            return '';
+        }
+
+        $name   = empty($content->content1) ? $file->get_filename() : $content->content1;
+        $icon   = mimeinfo_from_type('icon', $file->get_mimetype());
+        $src    = $browser->encodepath($CFG->wwwroot.'/pluginfile.php', '/'.$this->context->id.'/data_content/'.$content->id.'/'.$file->get_filename());
+        $width  = $this->field->param1 ? ' width  = "'.s($this->field->param1).'" ':' ';
+        $height = $this->field->param2 ? ' height = "'.s($this->field->param2).'" ':' ';
+
         $str = '<img src="'.$CFG->pixpath.'/f/'.$icon.'" height="16" width="16" alt="'.$icon.'" />&nbsp;'.
-                        '<a href="'.$source.'/'.$src.'" >'.$name.'</a>';
+               '<a href="'.$src.'" >'.s($name).'</a>';
         return $str;
     }
 
@@ -115,34 +119,32 @@ class data_field_file extends data_field_base {
     function update_content($recordid, $value, $name) {
         global $CFG, $DB;
 
-        if (!$oldcontent = $DB->get_record('data_content', array('fieldid'=>$this->field->id, 'recordid'=>$recordid))) {
+        if (!$content = $DB->get_record('data_content', array('fieldid'=>$this->field->id, 'recordid'=>$recordid))) {
         // Quickly make one now!
-            $oldcontent = new object;
-            $oldcontent->fieldid = $this->field->id;
-            $oldcontent->recordid = $recordid;
-            if ($oldcontent->id = $DB->insert_record('data_content', $oldcontent)) {
+            $content = new object();
+            $content->fieldid  = $this->field->id;
+            $content->recordid = $recordid;
+            if ($id = $DB->insert_record('data_content', $content)) {
                 print_error('cannotinsertempty', 'data');
             }
+            $content = $DB->get_record('data_content', array('id'=>$id));
         }
-        $content = new object;
-        $content->id = $oldcontent->id;
-        $names = explode('_',$name);
+
+        $names = explode('_', $name);
         switch ($names[2]) {
             case 'file':
                 // file just uploaded
-#                $course = get_course('course', 'id', $this->data->course);
-                $filename = $_FILES[$names[0].'_'.$names[1]];
-                $filename = $filename['name'];
-                $dir = $this->data->course.'/'.$CFG->moddata.'/data/'.$this->data->id.'/'.$this->field->id.'/'.$recordid;
-                // only use the manager if file is present, to avoid "are you sure you selected a file to upload" msg
+                $tmpfile = $_FILES[$names[0].'_'.$names[1]];
+                $filename = $tmpfile['name'];
+                $pathanme = $tmpfile['tmp_name'];
                 if ($filename){
-                    require_once($CFG->libdir.'/uploadlib.php');
-                    // FIX ME: $course not defined here
-                    $um = new upload_manager($names[0].'_'.$names[1],true,false,$this->data->course,false,$this->field->param3);
-                    if ($um->process_file_uploads($dir)) {
-                        $newfile_name = $um->get_new_filename();
-                        $content->content = $newfile_name;
-                        $DB->update_record('data_content',$content);
+                    $fs = get_file_storage();
+                    // TODO: uploaded file processing will be in file picker ;-)
+                    $fs->delete_area_files($this->context->id, 'data_content', $content->id);
+                    $file_record = array('contextid'=>$this->context->id, 'filearea'=>'data_content', 'itemid'=>$content->id, 'filepath'=>'/', 'filename'=>$filename);
+                    if ($file = $fs->create_file_from_pathname($file_record, $pathanme)) {
+                        $content->content = $file->get_filename();
+                        $DB->update_record('data_content', $content);
                     }
                 }
                 break;
@@ -172,6 +174,10 @@ class data_field_file extends data_field_base {
         return false;
     }
 
+    function file_ok($path) {
+        return true;
+    }
+
 }
 
 ?>
index 348289038fcdc09e8a018e1f33b4a8f31508aac4..9985c84d145b96077623510d8f804ce3b8d3148b 100755 (executable)
@@ -43,10 +43,6 @@ class data_field_latlong extends data_field_base {
     );
     // Other map sources listed at http://kvaleberg.com/extensions/mapsources/index.php?params=51_30.4167_N_0_7.65_W_region:earth
 
-    function data_field_latlong($field=0, $data=0) {
-        parent::data_field_base($field, $data);
-    }
-
     function display_add_field($recordid=0) {
         global $CFG, $DB;
 
index ff002da3ed0e3d80151331be7526d9cebd802a44..c855a90ce39fa12f25036dc65554222e15333616 100755 (executable)
@@ -26,10 +26,6 @@ class data_field_menu extends data_field_base {
 
     var $type = 'menu';
 
-    function data_field_menu($field=0, $data=0) {
-        parent::data_field_base($field, $data);
-    }
-
     function display_add_field($recordid=0) {
         global $DB;
 
index 0101e901dbe1c2b934c6d5e7dfc05b7c9e64f39c..030ef4d149ff951c8dc3ad9ed964b933abe91236 100755 (executable)
@@ -26,11 +26,6 @@ class data_field_multimenu extends data_field_base {
 
     var $type = 'multimenu';
 
-    function data_field_multimenu($field=0, $data=0) {
-        parent::data_field_base($field, $data);
-    }
-
-
     function display_add_field($recordid=0) {
         global $DB;
 
index fc6eeaec8717f4c3b57787dbdcad027679e0e98b..23835e29a9972b5339233acc73d9319c1ebfbcea 100755 (executable)
 class data_field_number extends data_field_base {
     var $type = 'number';
 
-    function data_field_number($field=0, $data=0) {
-        parent::data_field_base($field, $data);
-    }
-
     function update_content($recordid, $value, $name='') {
         global $DB;
 
index 6bc8b1c2e2d7014469a65c96c8bb2b7100f26830..5f299f8df31ad9339793c53faf05ec6b857bd785 100755 (executable)
 //                                                                       //
 ///////////////////////////////////////////////////////////////////////////
 
-require_once($CFG->dirroot.'/mod/data/field/file/field.class.php');
-// Base class is 'file'
-
-class data_field_picture extends data_field_file {
+class data_field_picture extends data_field_base {
     var $type = 'picture';
     var $previewwidth  = 50;
     var $previewheight = 50;
 
-    function data_field_picture($field=0, $data=0) {
-        parent::data_field_base($field, $data);
-    }
-
     function display_add_field($recordid=0) {
         global $CFG, $DB;
 
-        $filepath = '';
-        $filename = '';
-        $description = '';
-        if ($recordid) {
+        $file        = false;
+        $content     = false;
+        $displayname = '';
+        $alttext     = '';
+        $fs = get_file_storage();
+        if ($recordid){
             if ($content = $DB->get_record('data_content', array('fieldid'=>$this->field->id, 'recordid'=>$recordid))) {
-                $filename = $content->content;
-                $description = $content->content1;
+                if (!empty($content->content)) {
+                    if ($file = $FS->get_file($this->context->id, 'data_content', $content->id, '/', $content->content)) {
+                        if (empty($content->content1)) {
+                            $displayname = $file->get_filename();
+                        } else {
+                            $displayname = $content->content1;
+                        }
+                    }
+                }
+                $alttext = $content->content1;
             }
-            $path = $this->data->course.'/'.$CFG->moddata.'/data/'.$this->data->id.'/'.$this->field->id.'/'.$recordid;
-            require_once($CFG->libdir.'/filelib.php');
-            $filepath = get_file_url("$path/$filename");
         }
+
         $str = '<div title="'.s($this->field->description).'">';
         $str .= '<fieldset><legend><span class="accesshide">'.$this->field->name.'</span></legend>';
         $str .= '<input type="hidden" name ="field_'.$this->field->id.'_file" id="field_'.$this->field->id.'_file"  value="fakevalue" />';
         $str .= '<label for="field_'.$this->field->id.'">'.get_string('picture','data'). '</label>&nbsp;<input type="file" name ="field_'.$this->field->id.'" id="field_'.$this->field->id.'" /><br />';
-        $str .= '<label for="field_'.$this->field->id.'_filename">'.get_string('alttext','data') .'</label>&nbsp;<input type="text" name="field_'
-                .$this->field->id.'_filename" id="field_'.$this->field->id.'_filename" value="'.s($description).'" /><br />';
-        $str .= '<input type="hidden" name="MAX_FILE_SIZE" value="'.s($this->field->param3).'" />';
-        if ($filepath) {
-            $str .= '<img width="'.s($this->previewwidth).'" height="'.s($this->previewheight).'" src="'.$filepath.'" alt="" />';
+        $str .= '<label for="field_'.$this->field->id.'_alttext">'.get_string('alttext','data') .'</label>&nbsp;<input type="text" name="field_'
+                .$this->field->id.'_alttext" id="field_'.$this->field->id.'_alttext" value="'.s($alttext).'" /><br />';
+        //$str .= '<input type="hidden" name="MAX_FILE_SIZE" value="'.s($this->field->param3).'" />';
+        if ($file) {
+            $browser = get_file_browser();
+            $src     = $browser->encodepath($CFG->wwwroot.'/pluginfile.php', $this->context->id.'/data_content/'.$content->id.'/'.$file->get_filename());
+            $str .= '<img width="'.s($this->previewwidth).'" height="'.s($this->previewheight).'" src="'.$src.'" alt="" />';
         }
         $str .= '</fieldset>';
         $str .= '</div>';
+
         return $str;
     }
 
@@ -86,38 +90,32 @@ class data_field_picture extends data_field_file {
     function display_browse_field($recordid, $template) {
         global $CFG, $DB;
 
-        if ($content = $DB->get_record('data_content', array('fieldid'=>$this->field->id, 'recordid'=>$recordid))) {
-            if (isset($content->content)) {
-                $contents[0] = $content->content;
-                $contents[1] = $content->content1;
-            }
-            if (empty($contents[0])) {
-                // Nothing to show
-                return '';
-            }
-            $alt = empty($contents[1])? '':$contents[1];
-            $title = empty($contents[1])? '':$contents[1];
-            $src = $contents[0];
-            $path = $this->data->course.'/'.$CFG->moddata.'/data/'.$this->data->id.'/'.$this->field->id.'/'.$recordid;
+        if (!$content = $DB->get_record('data_content', array('fieldid'=>$this->field->id, 'recordid'=>$recordid))) {
+            return false;
+        }
 
-            $thumbnaillocation = $CFG->dataroot .'/'. $path .'/thumb/'.$src;
-            require_once($CFG->libdir.'/filelib.php');
-            $source = get_file_url("$path/$src");
-            $thumbnailsource = file_exists($thumbnaillocation) ? get_file_url("$path/thumb/$src") : $source;
+        if (empty($content->content)) {
+            return '';
+        }
 
-            if ($template == 'listtemplate') {
-                $width = $this->field->param4 ? ' width="'.s($this->field->param4).'" ' : ' ';
-                $height = $this->field->param5 ? ' height="'.s($this->field->param5).'" ' : ' ';
-                $str = '<a href="view.php?d='.$this->field->dataid.'&amp;rid='.$recordid.'"><img '.
-                     $width.$height.' src="'.$thumbnailsource.'" alt="'.s($alt).'" title="'.s($title).'" style="border:0px" /></a>';
-            } else {
-                $width = $this->field->param1 ? ' width="'.s($this->field->param1).'" ':' ';
-                $height = $this->field->param2 ? ' height="'.s($this->field->param2).'" ':' ';
-                $str = '<a href="'.$source.'"><img '.$width.$height.' src="'.$source.'" alt="'.s($alt).'" title="'.s($title).'" style="border:0px" /></a>';
-            }
-            return $str;
+        $browser = get_file_browser();
+
+        $alt   = $content->content1;
+        $title = $alt;
+
+        if ($template == 'listtemplate') {
+            $src = $browser->encodepath($CFG->wwwroot.'/pluginfile.php', '/'.$this->context->id.'/data_content/'.$content->id.'/'.'thumb_'.$content->content);
+            // no need to add width/height, because the thumb is resized properly
+            $str = '<a href="view.php?d='.$this->field->dataid.'&amp;rid='.$recordid.'"><img src="'.$src.'" alt="'.s($alt).'" title="'.s($title).'" style="border:0px" /></a>';
+
+        } else {
+            $src = $browser->encodepath($CFG->wwwroot.'/pluginfile.php', '/'.$this->context->id.'/data_content/'.$content->id.'/'.$content->content);
+            $width  = $this->field->param1 ? ' width="'.s($this->field->param1).'" ':' ';
+            $height = $this->field->param2 ? ' height="'.s($this->field->param2).'" ':' ';
+            $str = '<a href="'.$src.'"><img '.$width.$height.' src="'.$src.'" alt="'.s($alt).'" title="'.s($title).'" style="border:0px" /></a>';
         }
-        return false;
+
+        return $str;
     }
 
     function update_field() {
@@ -134,6 +132,7 @@ class data_field_picture extends data_field_file {
         if ($oldfield && ($oldfield->param4 != $this->field->param4 || $oldfield->param5 != $this->field->param5)) {
             // Check through all existing records and update the thumbnail
             if ($contents = $DB->get_records('data_content', array('fieldid'=>$this->field->id))) {
+                $fs = get_file_storage();
                 if (count($contents) > 20) {
                     notify(get_string('resizingimages', 'data'), 'notifysuccess');
                     echo "\n\n";
@@ -141,9 +140,15 @@ class data_field_picture extends data_field_file {
                     ob_flush();
                 }
                 foreach ($contents as $content) {
+                    if (!$file = $fs->get_file($this->context->id, 'data_content', $content->id, '/', $content->content)) {
+                        continue;
+                    }
+                    if ($thumbfile = $fs->get_file($this->context->id, 'data_content', $content->id, '/', 'thumb_'.$content->content)) {
+                        $thumbfile->delete();
+                    }
                     @set_time_limit(300);
                     // Might be slow!
-                    $this->update_thumbnail($content);
+                    $this->update_thumbnail($content, $file);
                 }
             }
         }
@@ -151,135 +156,85 @@ class data_field_picture extends data_field_file {
     }
 
     function update_content($recordid, $value, $name) {
-        global $DB;
-
-        parent::update_content($recordid, $value, $name);
-        $content = $DB->get_record('data_content',array('fieldid'=>$this->field->id, 'recordid'=>$recordid));
-        $this->update_thumbnail($content);
-        // Regenerate the thumbnail
-    }
+        global $CFG, $DB;
 
-    function update_thumbnail($content) {
-        // (Re)generate thumbnail image according to the dimensions specified in the field settings.
-        // If thumbnail width and height are BOTH not specified then no thumbnail is generated, and
-        // additionally an attempted delete of the existing thumbnail takes place.
-        global $CFG;
-        require_once($CFG->libdir . '/gdlib.php');
-        $datalocation = $CFG->dataroot .'/'.$this->data->course.'/'.$CFG->moddata.'/data/'.
-                        $this->data->id.'/'.$this->field->id.'/'.$content->recordid;
-        $originalfile = $datalocation.'/'.$content->content;
-        if (!file_exists($originalfile)) {
-            return;
-        }
-        if (!file_exists($datalocation.'/thumb')) {
-            mkdir($datalocation.'/thumb', 0777);
-            // robertall: Why hardcode 0777??
-        }
-        $thumbnaillocation = $datalocation.'/thumb/'.$content->content;
-        $imageinfo = GetImageSize($originalfile);
-        $image->width  = $imageinfo[0];
-        $image->height = $imageinfo[1];
-        $image->type   = $imageinfo[2];
-        if (!$image->width || !$image->height) {
-            // Should not happen
-            return;
+        if (!$content = $DB->get_record('data_content', array('fieldid'=>$this->field->id, 'recordid'=>$recordid))) {
+        // Quickly make one now!
+            $content = new object();
+            $content->fieldid  = $this->field->id;
+            $content->recordid = $recordid;
+            if ($id = $DB->insert_record('data_content', $content)) {
+                print_error('cannotinsertempty', 'data');
+            }
+            $content = $DB->get_record('data_content', array('id'=>$id));
         }
-        switch ($image->type) {
-            case 1:
-                if (function_exists('ImageCreateFromGIF')) {
-                    $im = ImageCreateFromGIF($originalfile);
-                } else {
-                    return;
+
+        $names = explode('_', $name);
+        switch ($names[2]) {
+            case 'file':
+                // file just uploaded
+                $tmpfile = $_FILES[$names[0].'_'.$names[1]];
+                $filename = $tmpfile['name'];
+                $pathanme = $tmpfile['tmp_name'];
+                if ($filename){
+                    $fs = get_file_storage();
+                    // TODO: uploaded file processing will be in file picker ;-)
+                    $fs->delete_area_files($this->context->id, 'data_content', $content->id);
+                    $file_record = array('contextid'=>$this->context->id, 'filearea'=>'data_content', 'itemid'=>$content->id, 'filepath'=>'/', 'filename'=>$filename);
+                    if ($file = $fs->create_file_from_pathname($file_record, $pathanme)) {
+                        $content->content = $file->get_filename();
+                        $DB->update_record('data_content', $content);
+                        // Regenerate the thumbnail
+                        $this->update_thumbnail($content, $file);
+                    }
                 }
                 break;
-            case 2:
-                if (function_exists('ImageCreateFromJPEG')) {
-                    $im = ImageCreateFromJPEG($originalfile);
-                } else {
-                    return;
-                }
+
+            case 'alttext':
+                // only changing alt tag
+                $content->content1 = clean_param($value, PARAM_NOTAGS);
+                $DB->update_record('data_content', $content);
                 break;
-            case 3:
-                if (function_exists('ImageCreateFromPNG')) {
-                    $im = ImageCreateFromPNG($originalfile);
-                } else {
-                    return;
-                }
+
+            default:
                 break;
         }
-        $thumbwidth  = isset($this->field->param4)?$this->field->param4:'';
-        $thumbheight = isset($this->field->param5)?$this->field->param5:'';
-        if ($thumbwidth || $thumbheight) {
-            // Only if either width OR height specified do we want a thumbnail
-            $wcrop = $image->width;
-            $hcrop = $image->height;
-            if ($thumbwidth && !$thumbheight) {
-                $thumbheight = $image->height * $thumbwidth / $image->width;
-            } else if($thumbheight && !$thumbwidth) {
-                $thumbwidth = $image->width * $thumbheight / $image->height;
-            } else {
-                // BOTH are set - may need to crop if aspect ratio differs
-                $hratio = $image->height / $thumbheight;
-                $wratio = $image->width  / $thumbwidth;
-                if ($wratio > $hratio) {
-                    // Crop the width
-                    $wcrop = intval($thumbwidth * $hratio);
-                } elseif($hratio > $wratio) {
-                    //Crop the height
-                    $hcrop = intval($thumbheight * $wratio);
-                }
-            }
-
-            // At this point both $thumbwidth and $thumbheight are set, and $wcrop and $hcrop
-
-            if (function_exists('ImageCreateTrueColor') and $CFG->gdversion >= 2) {
-                $im1 = ImageCreateTrueColor($thumbwidth,$thumbheight);
-            } else {
-                $im1 = ImageCreate($thumbwidth,$thumbheight);
-            }
-            if ($image->type == 3) {
-                // Prevent alpha blending for PNG images
-                imagealphablending($im1, false);
-            }
-            $cx = $image->width  / 2;
-            $cy = $image->height / 2;
-
-            // These "half" measurements use the "crop" values rather than the actual dimensions
-            $halfwidth  = floor($wcrop * 0.5);
-            $halfheight = floor($hcrop * 0.5);
+    }
 
-            ImageCopyBicubic($im1, $im, 0, 0, $cx-$halfwidth, $cy-$halfheight,
-                             $thumbwidth, $thumbheight, $halfwidth*2, $halfheight*2);
+    function update_thumbnail($content, $file) {
+        // (Re)generate thumbnail image according to the dimensions specified in the field settings.
+        // If thumbnail width and height are BOTH not specified then no thumbnail is generated, and
+        // additionally an attempted delete of the existing thumbnail takes place.
+        $fs = get_file_storage();
+        $file_record = array('contextid'=>$file->get_contextid(), 'filearea'=>$file->get_filearea(),
+                             'itemid'=>$file->get_itemid(), 'filepath'=>$file->get_filepath(),
+                             'filename'=>'thumb_'.$file->get_filename(), 'userid'=>$file->get_userid());
+        try {
+            // this may fail for various reasons
+            $fs->convert_image($file_record, $file, $this->field->param4, $this->field->param5, true);
+            return true;
+        } catch (Exception $e) {
+            return false;
+        }
+    }
 
-            if ($image->type == 3) {
-                // Save alpha transparency for PNG images
-                imagesavealpha($im1, true);
-            }
-            if (function_exists('ImageJpeg') && $image->type != 3) {
-                @touch($thumbnaillocation);
-                // Helps in Safe mode
-                if (ImageJpeg($im1, $thumbnaillocation, 90)) {
-                    @chmod($thumbnaillocation, 0666);
-                    // robertall: Why hardcode 0666??
-                }
-            } elseif (function_exists('ImagePng') && $image->type == 3) {
-                @touch($thumbnaillocation);
-                // Helps in Safe mode
-                if (ImagePng($im1, $thumbnaillocation, 9)) {
-                    @chmod($thumbnaillocation, 0666);
-                    // robertall: Why hardcode 0666??
-                }
-            }
-        } else {
-            // Try to remove the thumbnail - we don't want thumbnailing active
-            @unlink($thumbnaillocation);
+    function notemptyfield($value, $name) {
+        $names = explode('_',$name);
+        if ($names[2] == 'file') {
+            $filename = $_FILES[$names[0].'_'.$names[1]];
+            return !empty($filename['name']);
+            // if there's a file in $_FILES, not empty
         }
+        return false;
     }
 
     function text_export_supported() {
         return false;
     }
 
+    function file_ok($path) {
+        return true;
+    }
 }
 
 ?>
index 68f7af6a3c48c4c5dade0c76444187a465b4633b..6f024a38bcca39e14e26bd4e8d8b5934827f5426 100755 (executable)
@@ -26,11 +26,6 @@ class data_field_radiobutton extends data_field_base {
 
     var $type = 'radiobutton';
 
-    function data_field_radiobutton($field=0, $data=0) {
-        parent::data_field_base($field, $data);
-    }
-
-
     function display_add_field($recordid=0) {
         global $CFG, $DB;
 
index 31df447b3758babd98a9146b0b6ec54f0c45ab71..2b42d5ea87c88e7ff28fff1d9440fe50d311d11b 100755 (executable)
@@ -26,10 +26,6 @@ class data_field_text extends data_field_base {
 
     var $type = 'text';
 
-    function data_field_text($field=0, $data=0) {
-        parent::data_field_base($field, $data);
-    }
-    
     function display_search_field($value = '') {
         return '<input type="text" size="16" name="f_'.$this->field->id.'" value="'.$value.'" />';   
     }
index 4933a08dddacf4c2f869c8945a6b3c6a62fcb134..0146103ad64fed0d1be1b2d6fdc4d7291c1fcf86 100755 (executable)
@@ -26,11 +26,6 @@ class data_field_textarea extends data_field_base {
 
     var $type = 'textarea';
 
-    function data_field_textarea($field=0, $data=0) {
-        parent::data_field_base($field, $data);
-    }
-
-
     function display_add_field($recordid=0) {
         global $CFG, $DB;
 
index e8c3ee54f9026db6913a1d57f899cdbb64a16c84..ab972617e4eb1b8930d0faa65e0cd2c942cb0993 100755 (executable)
 class data_field_url extends data_field_base {
     var $type = 'url';
 
-    function data_field_text($field=0, $data=0) {
-        parent::data_field_base($field, $data);
-    }
-
     function display_add_field($recordid=0) {
         global $CFG, $DB;
 
index 5dd7e7b838c4a81e0664a17f87828a8f84304fec..6c61fb9ca526d156c94d7382d886941afcc7b1af 100755 (executable)
@@ -35,7 +35,7 @@ define ('DATA_TIMEMODIFIED', -4);
 define ('DATA_CAP_EXPORT', 'mod/data:viewalluserpresets');
 // Users having assigned the default role "Non-editing teacher" can export database records
 // Using the mod/data capability "viewalluserpresets" existing in Moodle 1.9.x.
-// In Moodle >= 2, new roles may be introduced and used instead. 
+// In Moodle >= 2, new roles may be introduced and used instead.
 
 class data_field_base {     // Base class for Database Field Types (see field/*/field.class.php)
 
@@ -46,9 +46,11 @@ class data_field_base {     // Base class for Database Field Types (see field/*/
     var $iconwidth = 16;    // Width of the icon for this fieldtype
     var $iconheight = 16;   // Width of the icon for this fieldtype
 
+    var $cm;                // course module or cmifno
+    var $context;           // activity context
 
 // Constructor function
-    function data_field_base($field=0, $data=0) {   // Field or data or both, each can be id or object
+    function __construct($field=0, $data=0, $cm=0) {   // Field or data or both, each can be id or object
         global $DB;
 
         if (empty($field) && empty($data)) {
@@ -80,9 +82,17 @@ class data_field_base {     // Base class for Database Field Types (see field/*/
             }
         }
 
+        if ($cm) {
+            $this->cm = $cm;
+        } else {
+            $this->cm = get_coursemodule_from_instance('data', $this->data->id);
+        }
+
         if (empty($this->field)) {         // We need to define some default values
             $this->define_default_field();
         }
+
+        $this->context = get_context_instance(CONTEXT_MODULE, $this->cm->id);
     }
 
 
@@ -165,8 +175,8 @@ class data_field_base {     // Base class for Database Field Types (see field/*/
         global $DB;
 
         if (!empty($this->field->id)) {
-            $DB->delete_records('data_fields', array('id'=>$this->field->id));
             $this->delete_content();
+            $DB->delete_records('data_fields', array('id'=>$this->field->id));
         }
         return true;
     }
@@ -268,30 +278,23 @@ class data_field_base {     // Base class for Database Field Types (see field/*/
     function delete_content($recordid=0) {
         global $DB;
 
-        $this->delete_content_files($recordid);
-
         if ($recordid) {
-            return $DB->delete_records('data_content', array('fieldid'=>$this->field->id, 'recordid'=>$recordid));
+            $conditions = array('fieldid'=>$this->field->id, 'recordid'=>$recordid);
         } else {
-            return $DB->delete_records('data_content', array('fieldid'=>$this->field->id));
+            $conditions = array('fieldid'=>$this->field->id);
         }
-    }
-
-// Deletes any files associated with this field
-    function delete_content_files($recordid='') {
-        global $CFG;
-
-        require_once($CFG->libdir.'/filelib.php');
 
-        $dir = $CFG->dataroot.'/'.$this->data->course.'/'.$CFG->moddata.'/data/'.$this->data->id.'/'.$this->field->id;
-        if ($recordid) {
-            $dir .= '/'.$recordid;
+        if ($rs = $DB->get_recordset('data_content', $conditions)) {
+            $fs = get_file_storage();
+            foreach ($rs as $content) {
+                $fs->delete_area_files($this->context->id, 'data_content', $content->id);
+            }
+            $rs->close();
         }
 
-        return fulldelete($dir);
+        return $DB->delete_records('data_content', $conditions);
     }
 
-
 // Check if a field from an add form is empty
     function notemptyfield($value, $name) {
         return !empty($value);
@@ -332,18 +335,21 @@ class data_field_base {     // Base class for Database Field Types (see field/*/
         return $str;
     }
 
-//  Per default, it is assumed that fields support text exporting. Override this (return false) on fields not supporting text exporting. 
+//  Per default, it is assumed that fields support text exporting. Override this (return false) on fields not supporting text exporting.
     function text_export_supported() {
         return true;
     }
 
-//  Per default, return the record's text value only from the "content" field. Override this in fields class if necesarry. 
+//  Per default, return the record's text value only from the "content" field. Override this in fields class if necesarry.
     function export_text_value($record) {
         if ($this->text_export_supported()) {
             return $record->content;
         }
     }
 
+    function file_ok($relativepath) {
+        return false;
+    }
 }
 
 
@@ -379,7 +385,7 @@ function data_generate_default_template(&$data, $template, $recordid=0, $form=fa
                 //    $str .= ' for="[['.$field->name.'#id]]"';
                 //}
                 //$str .= '>'.$field->name.'</label>';
-                
+
             //} else {
                 $str .= $field->name.': ';
             //}
@@ -546,35 +552,37 @@ function data_get_field_new($type, $data) {
  * invoke plugin methods                                                *
  * input: $param $field - record from db                                *
  ************************************************************************/
-function data_get_field($field, $data) {
+function data_get_field($field, $data, $cm=null) {
     global $CFG;
 
     if ($field) {
         require_once('field/'.$field->type.'/field.class.php');
         $newfield = 'data_field_'.$field->type;
-        $newfield = new $newfield($field, $data);
+        $newfield = new $newfield($field, $data, $cm);
         return $newfield;
     }
 }
 
 
-/***************************************************************************
- * given record id, returns true if the record belongs to the current user *
- * input @param $rid - record id                                           *
- * output bool                                                             *
- ***************************************************************************/
-function data_isowner($rid){
+/**
+ * Given record object (or id), returns true if the record belongs to the current user
+ * @param mixed $rid - record object or id
+ * @return bool
+ */
+function data_isowner($record) {
     global $USER, $DB;
 
-    if (empty($USER->id)) {
+    if (!isloggedin()) {
         return false;
     }
 
-    if ($record = $DB->get_record('data_records', array('id'=>$rid))) {
-        return ($record->userid == $USER->id);
+    if (!is_object($record)) {
+        if (!$record = $DB->get_record('data_records', array('id'=>$record))) {
+            return false;
+        }
     }
 
-    return false;
+    return ($record->userid == $USER->id);
 }
 
 /***********************************************************************
@@ -598,7 +606,7 @@ function data_atmaxentries($data){
  * output int                                                         *
  **********************************************************************/
 function data_numentries($data){
-    global $USER, $CFG, $DB;
+    global $USER, $DB;
     $sql = 'SELECT COUNT(*) FROM {data_records} WHERE dataid=? AND userid=?';
     return $DB->count_records_sql($sql, array($data->id, $USER->id));
 }
@@ -659,7 +667,7 @@ function data_tags_check($dataid, $template) {
  * Adds an instance of a data                                           *
  ************************************************************************/
 function data_add_instance($data) {
-    global $CFG, $DB;
+    global $DB;
 
     if (empty($data->assessed)) {
         $data->assessed = 0;
@@ -680,7 +688,7 @@ function data_add_instance($data) {
  * updates an instance of a data                                        *
  ************************************************************************/
 function data_update_instance($data) {
-    global $CFG, $DB;
+    global $DB;
 
     $data->timemodified = time();
     $data->id           = $data->instance;
@@ -707,38 +715,36 @@ function data_update_instance($data) {
  * deletes an instance of a data                                        *
  ************************************************************************/
 function data_delete_instance($id) {    // takes the dataid
-    global $CFG, $DB;
+    global $DB;
 
-    if (! $data = $DB->get_record('data', array('id'=>$id))) {
+    if (!$data = $DB->get_record('data', array('id'=>$id))) {
         return false;
     }
 
-    // Delete all the associated information
+    $cm = get_coursemodule_from_instance('data', $data->id);
+    $context = get_context_instance(CONTEXT_MODULE, $cm->id);
 
-    // get all the records in this data
-    $sql = 'SELECT c.* FROM {data_records} r LEFT JOIN {data_content} c ON c.recordid = r.id WHERE r.dataid =?';
+/// Delete all the associated information
 
-    if ($contents = $DB->get_records_sql($sql, array($id))){
+    // files
+    $fs = get_file_storage();
+    $fs->delete_area_files($context->id, 'data_content');
 
-        foreach($contents as $content){
+    // get all the records in this data
+    $sql = "SELECT r.id
+              FROM {data_records} r
+             WHERE r.dataid = ?";
 
-            $field = $DB->get_record('data_fields', array('id'=>$content->fieldid));
-            if ($g = data_get_field($field, $data)){
-                $g->delete_content_files($id, $content->recordid, $content->content);
-            }
-            //delete the content itself
-            $DB->delete_records('data_content', array('id'=>$content->id));
-        }
-    }
+    $DB->delete_records_select('data_content', "recordid IN ($sql)", array($id));
 
     // delete all the records and fields
     $DB->delete_records('data_records', array('dataid'=>$id));
     $DB->delete_records('data_fields', array('dataid'=>$id));
 
     // Delete the instance itself
-
     $result = $DB->delete_records('data', array('id'=>$id));
 
+    // cleanup gradebook
     data_grade_item_delete($data);
 
     return $result;
@@ -748,7 +754,7 @@ function data_delete_instance($id) {    // takes the dataid
  * returns a summary of data activity of this user                      *
  ************************************************************************/
 function data_user_outline($course, $user, $mod, $data) {
-    global $CFG, $DB;
+    global $DB;
 
     if ($countrecords = $DB->count_records('data_records', array('dataid'=>$data->id, 'userid'=>$user->id))) {
         $result = new object();
@@ -781,7 +787,7 @@ function data_user_complete($course, $user, $mod, $data) {
  * @return array array of grades, false if none
  */
 function data_get_user_grades($data, $userid=0) {
-    global $CFG, $DB;
+    global $DB;
 
     $user = $userid ? "AND u.id = :userid" : "";
     $params = array('userid'=>$userid, 'dataid'=>$data->id);
@@ -908,7 +914,7 @@ function data_grade_item_delete($data) {
 function data_get_participants($dataid) {
 // Returns the users with data in one data
 // (users with records in data_records, data_comments and data_ratings)
-    global $CFG, $DB;
+    global $DB;
 
     $records = $DB->get_records_sql("SELECT DISTINCT u.id, u.id
                                        FROM {user} u, {data_records} r
@@ -924,17 +930,17 @@ function data_get_participants($dataid) {
 
     $participants = array();
 
-    if ($records){
+    if ($records) {
         foreach ($records as $record) {
             $participants[$record->id] = $record;
         }
     }
-    if ($comments){
+    if ($comments) {
         foreach ($comments as $comment) {
             $participants[$comment->id] = $comment;
         }
     }
-    if ($ratings){
+    if ($ratings) {
         foreach ($ratings as $rating) {
             $participants[$rating->id] = $rating;
         }
@@ -1027,9 +1033,9 @@ function data_print_template($template, $records, $data, $search='',$page=0, $re
         } else {
             $replacement[] = '';
         }
-        
+
         $patterns[] = '##timeadded##';
-        $replacement[] = userdate($record->timecreated); 
+        $replacement[] = userdate($record->timecreated);
 
         $patterns[] = '##timemodified##';
         $replacement [] = userdate($record->timemodified);
@@ -1093,7 +1099,7 @@ function data_print_template($template, $records, $data, $search='',$page=0, $re
  ************************************************************************/
 function data_print_preference_form($data, $perpage, $search, $sort='', $order='ASC', $search_array = '', $advanced = 0, $mode= ''){
     global $CFG, $DB;
-    
+
     $cm = get_coursemodule_from_instance('data', $data->id);
     $context = get_context_instance(CONTEXT_MODULE, $cm->id);
     echo '<br /><div class="datapreferences">';
@@ -1169,7 +1175,7 @@ function data_print_preference_form($data, $perpage, $search, $sort='', $order='
         $checked = '';
     }
     print '
-            
+
         <script type="text/javascript">
         //<![CDATA[
         <!-- Start
@@ -1202,10 +1208,10 @@ function data_print_preference_form($data, $perpage, $search, $sort='', $order='
     echo '&nbsp;<input type="hidden" name="advanced" value="0" />';
     echo '&nbsp;<input type="checkbox" id="advancedcheckbox" name="advanced" value="1" '.$checked.' onchange="showHideAdvSearch(this.checked);" /><label for="advancedcheckbox">'.get_string('advancedsearch', 'data').'</label>';
     echo '&nbsp;<input type="submit" value="'.get_string('savesettings','data').'" />';
-    
+
     echo '<br />';
     echo '<div class="dataadvancedsearch" id="data_adv_form" style="display: ';
-    
+
     if ($advanced) {
         echo 'inline';
     }
@@ -1214,7 +1220,7 @@ function data_print_preference_form($data, $perpage, $search, $sort='', $order='
     }
     echo ';margin-left:auto;margin-right:auto;" >';
     echo '<table class="boxaligncenter">';
-    
+
     // print ASC or DESC
     echo '<tr><td colspan="2">&nbsp;</td></tr>';
     $i = 0;
@@ -1406,10 +1412,11 @@ function data_print_rating_menu($recordid, $userid, $scale) {
     choose_from_menu($scale, $recordid, $rating->rating, "$strrate...", '', -999);
 }
 
-
+/**
+ * Returns a list of ratings for a particular post - sorted.
+ */
 function data_get_ratings($recordid, $sort="u.firstname ASC") {
-// Returns a list of ratings for a particular post - sorted.
-    global $CFG, $DB;
+    global  $DB;
 
     return $DB->get_records_sql("SELECT u.*, r.rating
                                    FROM {data_ratings} r, {user} u
@@ -1417,7 +1424,6 @@ function data_get_ratings($recordid, $sort="u.firstname ASC") {
                                ORDER BY $sort", array($recordid));
 }
 
-
 // prints all comments + a text box for adding additional comment
 function data_print_comments($data, $record, $page=0, $mform=false) {
     global $CFG, $DB;
@@ -2025,7 +2031,7 @@ class PresetImporter {
 
                 if (array_key_exists($cid, $preservedfields)){
                     print_error('notinjectivemap', 'data');
-                } 
+                }
                 else $preservedfields[$cid] = true;
             }
 
@@ -2116,7 +2122,7 @@ class PresetImporter {
 
         if (strstr($this->folder, '/temp/')) {
         // Removes the temporary files
-            clean_preset($this->folder); 
+            clean_preset($this->folder);
         }
 
         return true;
@@ -2436,6 +2442,97 @@ function data_get_exportdata($dataid, $fields, $selectedfields) {
     return $exportdata;
 }
 
+/**
+ * Lists all browsable file areas
+ */
+function data_get_file_areas($course, $cm, $context) {
+    $areas = array();
+    if (has_capability('moodle/course:managefiles', $context)) {
+        $areas['data_intro'] = get_string('areaintro', 'data');
+    }
+    return $areas;
+}
+
+/**
+ * Serves the data attachments. Implements needed access control ;-)
+ */
+function data_pluginfile($course, $cminfo, $context, $filearea, $args) {
+    global $CFG, $DB;
+
+    if (!$cminfo->uservisible) {
+        return false;
+    }
+
+    if ($filearea === 'data_intro') {
+        // all users may access it
+        $relativepath = '/'.implode('/', $args);
+        $fullpath = $context->id.'data_intro0'.$relativepath;
+
+        $fs = get_file_storage();
+        if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
+            return false;
+        }
+
+        $lifetime = isset($CFG->filelifetime) ? $CFG->filelifetime : 86400;
+
+        // finally send the file
+        send_stored_file($file, $lifetime, 0);
+
+    } else if ($filearea === 'data_content') {
+        $contentid = (int)array_shift($args);
+
+        if (!$content = $DB->get_record('data_content', array('id'=>$contentid))) {
+            return false;
+        }
+
+        if (!$field = $DB->get_record('data_fields', array('id'=>$content->fieldid))) {
+            return false;
+        }
+
+        if (!$record = $DB->get_record('data_records', array('id'=>$content->recordid))) {
+            return false;
+        }
+
+        if (!$data = $DB->get_record('data', array('id'=>$field->dataid))) {
+            return false;
+        }
+
+        //check if approved
+        if (!$record->approved and !data_isowner($record) and !has_capability('mod/data:approve', $context)) {
+            return false;
+        }
+
+        // group access
+        if ($record->groupid) {
+            $groupmode = groups_get_activity_groupmode($cminfo, $course);
+            if ($groupmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context)) {
+                if (!groups_is_member($record->groupid)) {
+                    return false;
+                }
+            }
+        }
+
+        $fieldobj = data_get_field($field, $data, $cminfo);
+
+        $relativepath = '/'.implode('/', $args);
+        $fullpath = $context->id.'data_content'.$content->id.$relativepath;
+
+        if (!$fieldobj->file_ok($relativepath)) {
+            return false;
+        }
+
+        $fs = get_file_storage();
+        if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
+            return false;
+        }
+
+        // finally send the file
+        send_stored_file($file, 0, 0, true); // download MUST be forced - security!
+    }
+
+    return false;
+}
+
 require_once($CFG->libdir . '/portfoliolib.php');
 class data_portfolio_caller extends portfolio_module_caller_base {
 
diff --git a/mod/data/preset_class.php b/mod/data/preset_class.php
deleted file mode 100644 (file)
index 8b65f24..0000000
+++ /dev/null
@@ -1,821 +0,0 @@
-<?php
-// $Id$
-
-/**
- * This object is a representation of a file-based preset for database activities
- */
-
-class Data_Preset
-{
-    
-    /**
-     * Required files in a preset directory
-     * @var array $required_files
-     */
-    var $required_files = array('singletemplate.html',
-                                'listtemplate.html',
-                                'listtemplateheader.html',
-                                'listtemplatefooter.html',
-                                'addtemplate.html',
-                                'rsstemplate.html',
-                                'csstemplate.css',
-                                'jstemplate.js',
-                                'preset.xml');
-    
-    /**
-    * The preset's shortname.
-    * TODO document
-    * @var string $shortname
-    */
-    var $shortname;
-  
-    /**
-     * A database activity object
-     * @var object $data
-     */
-    var $data;
-
-    /**
-     * Directory mapped to this Preset object.
-     * @var string $directory
-     */
-    var $directory;
-
-    /**
-     * This Preset's singletemplate
-     * @var string $singletemplate
-     */
-    var $singletemplate;
-
-    /**
-     * This Preset's listtemplate
-     * @var string $listtemplate
-     */
-    var $listtemplate;
-    
-    /**
-     * This Preset's listtemplateheader
-     * @var string $listtemplateheader
-     */
-    var $listtemplateheader;
-    
-    /**
-     * This Preset's listtemplatefooter
-     * @var string $listtemplatefooter
-     */
-    var $listtemplatefooter;
-    
-    /**
-     * This Preset's addtemplate
-     * @var string $addtemplate
-     */
-    var $addtemplate;
-    
-    /**
-     * This Preset's rsstemplate
-     * @var string $rsstemplate
-     */
-    var $rsstemplate;
-    
-    /**
-     * This Preset's csstemplate
-     * @var string $csstemplate
-     */
-    var $csstemplate;
-    
-    /**
-     * This Preset's jstemplate
-     * @var string $jstemplate
-     */
-    var $jstemplate;
-    
-    /**
-     * This Preset's xml
-     * @var string $xml
-     */
-    var $xml;
-    var $user_id;
-
-    /**
-     * Constructor
-     */
-    function Data_Preset($shortname = null, $data_id = null, $directory = null, $user_id = null) {
-        global $DB;
-
-        $this->shortname = $shortname;
-        $this->user_id = $user_id;
-        
-        if (empty($directory)) {
-            $this->directory = $this->get_path();
-        } else {
-            $this->directory = $directory;
-        }
-       
-        if (!empty($data_id)) {  
-            if (!$this->data = $DB->get_record('data', array('id'=>$data_id))) {
-                print_error('wrongdataid','data'); 
-            } else { 
-                $this->listtemplate       = $this->data->listtemplate;
-                $this->singletemplate     = $this->data->singletemplate;
-                $this->listtemplateheader = $this->data->listtemplateheader;
-                $this->listtemplatefooter = $this->data->listtemplatefooter;
-                $this->addtemplate        = $this->data->addtemplate;
-                $this->rsstemplate        = $this->data->rsstemplate;
-                $this->csstemplate        = $this->data->csstemplate;
-                $this->jstemplate         = $this->data->jstemplate;
-            }
-        }
-    }
-    
-    /**
-     * Returns the best name to show for a preset
-     * If the shortname has spaces in it, replace them with underscores. 
-     * Convert the name to lower case.
-     */
-    function best_name($shortname = null) {
-        if (empty($shortname)) {
-            $shortname = $this->shortname;
-        }
-
-        /// We are looking inside the preset itself as a first choice, but also in normal data directory
-        $string = get_string('presetname'.$shortname, 'data', NULL, $this->directory.'/lang/');
-
-        if (substr($string, 0, 1) == '[') {
-            return strtolower(str_replace(' ', '_', $shortname));
-        } else {
-            return $string;
-        }
-    }
-    
-    /**
-    * TODO figure out what's going on here with the user id. This method doesn't look quite right to me. 
-    */
-    function get_path() {
-        global $USER, $CFG, $COURSE;
-
-        $context = get_context_instance(CONTEXT_COURSE, $COURSE->id);
-
-        if ($this->user_id > 0 && ($this->user_id == $USER->id || has_capability('mod/data:viewalluserpresets', $context))) {
-            return $CFG->dataroot.'/data/preset/'.$this->user_id.'/'.$this->shortname;
-        } else if ($this->user_id == 0) {
-            return $CFG->dirroot.'/mod/data/preset/'.$this->shortname;
-        } else if ($this->user_id < 0) {
-            return $CFG->dataroot.'/temp/data/'.-$this->user_id.'/'.$this->shortname;
-        }
-
-        return 'Does it disturb you that this code will never run?';
-    }
-   
-   
-   /**
-    * A preset is a directory with a number of required files. 
-    * This function verifies that the given directory contains
-    * all these files, thus validating as a preset directory.
-    * 
-    * @param string $directory An optional directory to check. Will use this Preset's directory if not provided.
-    * @return mixed True if the directory contains all the files required to qualify as Preset object; 
-    *                 an array of the missing filename is returned otherwise
-    */
-    function has_all_required_files($directory = null) 
-    {
-        if (empty($directory)) {
-            $directory = $this->directory;
-        } else {
-            $directory = rtrim($directory, '/\\') . '/';
-        }
-        
-        $missing_files = array();
-
-        foreach ($this->required_files as $file) {
-            if(!file_exists($directory . '/' . $file)) {
-                $missing_files[] = $file;
-            }
-        }
-        
-        if (!empty($missing_files)) {
-            return $missing_files;
-        }
-
-        return true;
-    }
-    
-    /**
-    * Deletes all the files in the directory mapped by this Preset object.
-    *
-    * @return boolean False if an error occured while trying to delete one of the files, true otherwise.
-    */
-    function clean_files() 
-    {
-        foreach ($this->required_files as $file) {
-            if (!unlink($this->directory . '/' . $file)) {
-                return $file;
-            }
-        }
-
-        return true;
-    }
-   
-    function get_template_files()
-    {
-        $template_files = array();
-
-        foreach ($this->required_files as $file) {
-            if (preg_match('/^([a-z]+template[a-z]?)\.[a-z]{2,4}$/', $file, $matches)) {
-                $template_files[$matches[1]] = $file;
-            }
-        }
-
-        return $template_files; 
-    }
-    
-    /**
-    * Exports this Preset object as a series of files in the Preset's directory.
-    * @return string The path/name of the resulting zip file if successful.
-    */
-    function export() {
-        global $CFG, $DB;
-
-        $this->directory = $CFG->dataroot.'/temp';
-        // write all templates, but not the xml yet
-
-        $template_files = $this->get_template_files();
-        foreach ($template_files as $var => $file) {
-            $handle = fopen($this->directory . '/' . $file, 'w');
-            fwrite($handle, $this->$var);
-            fclose($handle);
-        }
-
-        /* All the display data is now done. Now assemble preset.xml */
-        $fields = $DB->get_records('data_fields', array('dataid'=>$this->data->id));
-        $presetfile = fopen($this->directory.'/preset.xml', 'w');
-        $presetxml = "<preset>\n\n";
-
-        /* Database settings first. Name not included? */
-        $settingssaved = array('intro', 
-                               'comments',
-                               'requiredentries', 
-                               'requiredentriestoview', 
-                               'maxentries',
-                               'rssarticles', 
-                               'approval', 
-                               'scale', 
-                               'assessed',
-                               'defaultsort', 
-                               'defaultsortdir', 
-                               'editany');
-
-        $presetxml .= "<settings>\n";
-        foreach ($settingssaved as $setting) {
-            $presetxml .= "<$setting>{$this->data->$setting}</$setting>\n";
-        }
-        $presetxml .= "</settings>\n\n";
-
-        /* Now for the fields. Grabs all settings that are non-empty */
-        if (!empty($fields)) {
-            foreach ($fields as $field) {
-                $presetxml .= "<field>\n";
-                foreach ($field as $key => $value) {
-                    if ($value != '' && $key != 'id' && $key != 'dataid') {
-                        $presetxml .= "<$key>$value</$key>\n";
-                    }
-                }
-                $presetxml .= "</field>\n\n";
-            }
-        }
-
-        $presetxml .= "</preset>";
-        fwrite($presetfile, $presetxml);
-        fclose($presetfile);
-
-        /* Check all is well */
-        if (is_array($missing_files = $this->has_all_required_files())) {
-            $missing_files = implode(', ', $missing_files);
-            print_error('filesnotgenerated', 'data', null, $missing_files); 
-        }
-        
-        // Remove export.zip
-        @unlink($this->directory.'/export.zip');
-        
-        $filelist = array();
-        foreach ($this->required_files as $file) {
-            $filelist[$file] = $this->directory . '/' . $file;
-        }
-
-        // zip_files is part of moodlelib
-        $status = zip_files($filelist, $this->directory.'/export.zip');
-
-        /* made the zip... now return the filename for storage.*/
-        return $this->directory.'/export.zip';
-    }
-    
-    
-    /**
-    * Loads the contents of the preset folder to initialise this Preset object.
-    * TODO document
-    */
-    function load_from_file($directory = null) {
-        global $CFG, $DB;
-
-        if (empty($directory) && empty($this->directory)) {
-            $this->directory = $this->get_path();
-        }
-
-        if (is_array($missing_files = $this->has_all_required_files())) {
-            $a = new StdClass();
-            $a->missing_files = implode(', ', $missing_files);
-            $a->directory = $this->directory;
-            print_error('directorynotapreset','data', null, $a); 
-        }
-
-        /* Grab XML */
-        $presetxml = file_get_contents($this->directory.'/preset.xml');
-        $parsedxml = xmlize($presetxml);
-
-        /* First, do settings. Put in user friendly array. */
-        $settingsarray = $parsedxml['preset']['#']['settings'][0]['#'];
-        $settings = new StdClass();
-
-        foreach ($settingsarray as $setting => $value) {
-            $settings->$setting = $value[0]['#'];
-        }
-
-        /* Now work out fields to user friendly array */
-        $fieldsarray = $parsedxml['preset']['#']['field'];
-        $fields = array();
-        foreach ($fieldsarray as $field) {
-            $f = new StdClass();
-            foreach ($field['#'] as $param => $value) {
-                $f->$param = $value[0]['#'];
-            }
-            $f->dataid = $this->data->id;
-            $f->type = clean_param($f->type, PARAM_ALPHA);
-            $fields[] = $f;
-        }
-        
-
-        /* Now add the HTML templates to the settings array so we can update d */
-        $template_files = $this->get_template_files();
-        
-        foreach ($template_files as $var => $file) {
-            $settings->$var = file_get_contents($this->directory . '/' . $file);
-        }
-        
-        $settings->instance = $this->data->id;
-
-        /* Now we look at the current structure (if any) to work out whether we need to clear db
-           or save the data */
-        $currentfields = array();
-        $currentfields = $DB->get_records('data_fields', array('dataid'=>$this->data->id));
-        $currentfields = array_merge($currentfields);
-        return array($settings, $fields, $currentfields);
-    }
-    
-    
-    /**
-    * Import options
-    * TODO document
-    * TODO replace all output by a return value
-    */
-    function get_import_html() {
-        if (!confirm_sesskey()) {
-            print_error("confirmsesskeybad");
-        }
-
-        $strblank = get_string('blank', 'data');
-        $strcontinue = get_string('continue');
-        $strwarning = get_string('mappingwarning', 'data');
-        $strfieldmappings = get_string('fieldmappings', 'data');
-        $strnew = get_string('new');
-
-        $sesskey = sesskey();
-
-        list($settings, $newfields,  $currentfields) = $this->load_from_file();
-
-        $html = '';
-
-        $html .= '<div style="text-align:center"><form action="preset.php" method="post">';
-        $html .= '<fieldset class="invisiblefieldset">';
-        $html .= '<input type="hidden" name="action" value="finishimport" />';
-        $html .= '<input type="hidden" name="sesskey" value="'.sesskey().'" />';
-        $html .= '<input type="hidden" name="d" value="'.$this->data->id.'" />';
-        $html .= '<input type="hidden" name="fullname" value="'.$this->user_id.'/'.$this->shortname.'" />';
-
-        if (!empty($currentfields) && !empty($newfields)) {
-            $html .= "<h3>$strfieldmappings ";
-            helpbutton('fieldmappings', '', 'data');
-            $html .= '</h3><table>';
-
-            foreach ($newfields as $nid => $newfield) {
-                $html .= "<tr><td><label for=\"id_$newfield->name\">$newfield->name</label></td>";
-                $html .= '<td><select name="field_'.$nid.'" id="id_'.$newfield->name.'">';
-
-                $selected = false;
-                foreach ($currentfields as $cid => $currentfield) {
-                    if ($currentfield->type == $newfield->type) {
-                        if ($currentfield->name == $newfield->name) {
-                            $html .= '<option value="'.$cid.'" selected="selected">'.$currentfield->name.'</option>';
-                            $selected=true;
-                        }
-                        else {
-                            $html .= '<option value="'.$cid.'">'.$currentfield->name.'</option>';
-                        }
-                    }
-                }
-
-                if ($selected)
-                    $html .= '<option value="-1">-</option>';
-                else
-                    $html .= '<option value="-1" selected="selected">-</option>';
-                $html .= '</select></td></tr>';
-            }
-            $html .= '</table>';
-            $html .= "<p>$strwarning</p>";
-        }
-        else if (empty($newfields)) {
-            print_error('nodefinedfields', 'data'); 
-        }
-        $html .= '<input type="submit" value="'.$strcontinue.'" /></fieldset></form></div>';
-        return $html; 
-    }
-
-
-    /**
-    * import()
-    * TODO document
-    */
-    function import() {
-        global $CFG, $DB;
-
-        list($settings, $newfields, $currentfields) = $this->load_from_file();
-        $preservedfields = array();
-
-        /* Maps fields and makes new ones */
-        if (!empty($newfields)) {
-            /* We require an injective mapping, and need to know what to protect */
-            foreach ($newfields as $nid => $newfield) {
-                $cid = optional_param("field_$nid", -1, PARAM_INT);
-                if ($cid == -1) continue;
-
-                if (array_key_exists($cid, $preservedfields)) {
-                    print_error('notinjectivemap', 'data'); 
-                } else {
-                    $preservedfields[$cid] = true;
-                }
-            }
-
-            foreach ($newfields as $nid => $newfield) {
-                $cid = optional_param("field_$nid", -1, PARAM_INT);
-                /* A mapping. Just need to change field params. Data kept. */
-                if ($cid != -1 and isset($currentfelds[$cid])) {
-                    $fieldobject = data_get_field_from_id($currentfields[$cid]->id, $this->data);
-                    foreach ($newfield as $param => $value) {
-                        if ($param != "id") {
-                            $fieldobject->field->$param = $value;
-                        }
-                    }
-                    unset($fieldobject->field->similarfield);
-                    $fieldobject->update_field();
-                    unset($fieldobject);
-                }
-                /* Make a new field */
-                else {
-                    include_once("field/$newfield->type/field.class.php");
-
-                    if (!isset($newfield->description)) {
-                        $newfield->description = '';
-                    }
-                    $classname = 'data_field_'.$newfield->type;
-                    $fieldclass = new $classname($newfield, $this->data);
-                    $fieldclass->insert_field();
-                    unset($fieldclass);
-                }
-            }
-        }
-
-        /* Get rid of all old unused data */
-        if (!empty($preservedfields)) {
-            foreach ($currentfields as $cid => $currentfield) {
-                if (!array_key_exists($cid, $preservedfields)) {
-                    /* Data not used anymore so wipe! */
-                    print "Deleting field $currentfield->name<br />";
-                    $id = $currentfield->id;
-                    // Why delete existing data records and related comments/ratings ??
-                    /*
-                    if ($content = $DB->get_records('data_content', array('fieldid'=>$id))) {
-                        foreach ($content as $item) {
-                            $DB->delete_records('data_ratings', array('recordid'=>$item->recordid));
-                            $DB->delete_records('data_comments', array('recordid'=>$item->recordid));
-                            $DB->delete_records('data_records', array('id'=>$item->recordid));
-                        }
-                    }
-                    */
-                    $DB->delete_records('data_content', array('fieldid'=>$id));
-                    $DB->delete_records('data_fields', array('id'=>$id));
-                }
-            }
-        }
-
-        data_update_instance($settings);
-
-        if (strstr($this->directory, '/temp/')) clean_preset($this->directory); /* Removes the temporary files */
-        return true;
-    }
-    
-    /**
-     * Runs the Preset action method that matches the given action string.
-     * @param string $action
-     * @return string html
-     */
-    function process_action($action, $params)
-    {
-        echo $action;
-        if (in_array("action_$action", get_class_methods(get_class($this)))) {
-            return $this->{"action_$action"}($params);
-        } else {
-            print_error('undefinedprocessactionmethod', 'data', null, $action); 
-        }
-    }
-
-////////////////////
-// ACTION METHODS //
-////////////////////
-    
-    function action_base($params) {
-        return null;
-    }
-
-    function action_confirmdelete($params) {
-        global $CFG, $USER;
-        $html = '';
-        $course = $params['course'];
-        $shortname = $params['shortname'];
-
-        if (!confirm_sesskey()) { // GET request ok here
-            print_error('confirmsesskeybad'); 
-        }
-        
-        $this->user_id = $params['userid'];
-
-        if (!$cm = get_coursemodule_from_instance('data', $this->data->id, $course->id)) {
-            print_error('invalidrequest'); 
-        }
-
-        $context = get_context_instance(COURSE_MODULE, $cm->id);
-
-        if ($this->user_id > 0 and ($this->user_id == $USER->id || has_capability('mod/data:manageuserpresets', $context))) {
-           //ok can delete
-        } else {
-            print_error('invalidrequest'); 
-        }
-
-        $path = $this->get_path();
-
-        $strwarning = get_string('deletewarning', 'data').'<br />'.
-                      data_preset_name($shortname, $path);
-
-        $options = new object();
-        $options->fullname = $this->user_id.'/'.$shortname;
-        $options->action   = 'delete';
-        $options->d        = $this->data->id;
-        $options->sesskey  = sesskey();
-
-        $optionsno = new object();
-        $optionsno->d = $this->data->id;
-        notice_yesno($strwarning, 'preset.php', 'preset.php', $options, $optionsno, 'post', 'get');
-        $html .= print_footer($course, null, true); 
-        echo $html;
-        exit();
-    } 
-
-    function action_delete($params) { 
-        global $CFG, $USER;
-
-        $course = $params['course'];
-        $shortname = $params['shortname'];
-        
-        if (!data_submitted() and !confirm_sesskey()) {
-            print_error('invalidrequest');
-        }
-
-        if (!$cm = get_coursemodule_from_instance('data', $this->data->id, $course->id)) {
-            print_error('invalidrequest'); 
-        }
-
-        $context = get_context_instance(COURSE_MODULE, $cm->id);
-
-        if ($this->user_id > 0 and ($this->user_id == $USER->id || has_capability('mod/data:manageuserpresets', $context))) {
-           //ok can delete
-        } else {
-            print_error('invalidrequest');
-        }
-        
-        $this->shortname = $this->best_name($shortname);
-
-        $this->path = $this->get_path();
-        $this->directory = $this->path;
-        
-        if (!$this->clean_files()) {
-            print_error('failedpresetdelete', 'data'); 
-        }
-        rmdir($this->path);
-
-        $strdeleted = get_string('deleted', 'data');
-        notify("$shortname $strdeleted", 'notifysuccess');
-    }
-
-    function action_importpreset($params) { 
-        $course = $params['course'];
-        if (!data_submitted() or !confirm_sesskey()) {
-            print_error('invalidrequest');
-        }
-
-        $this->shortname = $params['shortname'];
-        $this->data = $params['data'];
-        $this->user_id = $params['userid']; 
-        $html = '';
-        $html .= $this->get_import_html();
-
-        $html .= print_footer($course, null, true); 
-        echo $html;
-        exit();
-    }
-
-    function action_importzip($params) {
-        global $CFG, $USER;
-        $course = $params['course'];
-        if (!data_submitted() or !confirm_sesskey()) {
-            print_error('invalid_request');
-        }
-
-        if (!make_upload_directory('temp/data/'.$USER->id)) {
-            print_error('errorcreatingdirectory', null, null, 'temp/data/' . $USER->id); 
-        }
-
-        $this->file = $CFG->dataroot.'/temp/data/'.$USER->id;
-        $this->directory = $this->file;
-        $this->user_id = $USER->id;
-        $this->clean_files($this->file);
-
-        if (!unzip_file($CFG->dataroot."/$USER->id/$file", $this->file, false)) {
-        }
-
-        $html .= $this->get_import_html();
-        $html .= print_footer($course, null, true); 
-        echo $html;
-        exit();
-    }
-
-    function action_finishimport($params) {
-        global $DB;
-
-        if (!data_submitted() or !confirm_sesskey()) {
-            print_error('invalidrequest'); 
-        }
-        $this->shortname = $this->best_name($this->data->name);
-        $this->directory = $this->get_path();
-        $this->import();
-
-        $strimportsuccess = get_string('importsuccess', 'data');
-        $straddentries = get_string('addentries', 'data');
-        $strtodatabase = get_string('todatabase', 'data');
-        if (!$DB->get_records('data_records', array('dataid'=>$this->data->id))) {
-            notify('$strimportsuccess <a href="edit.php?d=' . $this->data->id . "\">$straddentries</a> $strtodatabase", 'notifysuccess');
-        } else {
-            notify("$strimportsuccess", 'notifysuccess');
-        } 
-    }
-
-    function action_export($params) {
-        global $CFG, $USER;
-        $course = $params['course'];
-        $html = '';
-
-        if (!data_submitted() or !confirm_sesskey()) {
-            print_error('invalid_request');
-        }
-
-        $this->shortname = $params['shortname'];
-        $this->data = $params['data'];
-        
-        $html .= '<div style="text-align:center">';
-        $file = $this->export();
-        $html .= get_string('exportedtozip', 'data')."<br />";
-        $permanentfile = $CFG->dataroot.'/' . $course->id . '/moddata/data/' . $this->data->id . '/preset.zip';
-        @unlink($permanentfile);
-        /* is this created elsewhere? sometimes its not present... */
-        make_upload_directory($course->id . '/moddata/data/' . $this->data->id);
-
-        /* now just move the zip into this folder to allow a nice download */
-        if (!rename($file, $permanentfile)) {
-            print_error('movezipfailed', 'data'); 
-        }
-        
-        require_once($CFG->libdir.'/filelib.php');
-        $html .= '<a href="'. get_file_url($course->id .'/moddata/data/'. $this->data->id .'/preset.zip') .'">'. get_string('download', 'data') .'</a>';
-        $html .= '</div>'; 
-        return $html;
-    }
-   
-    /**
-     * First stage of saving a Preset: ask for a name
-     */
-    function action_save1($params) {
-        $html = '';
-        $sesskey = sesskey();
-        $course = $params['course'];
-        if (!data_submitted() or !confirm_sesskey()) {
-            print_error('invalid_request');
-        }
-
-        $strcontinue = get_string('continue');
-        $strwarning = get_string('presetinfo', 'data');
-        $strname = get_string('shortname');
-
-        $html .= '<div style="text-align:center">';
-        $html .= '<p>'.$strwarning.'</p>';
-        $html .= '<form action="preset.php" method="post">';
-        $html .= '<fieldset class="invisiblefieldset">';
-        $html .= '<label for="shortname">'.$strname.'</label> <input type="text" id="shortname" name="name" value="'.$this->best_name($this->data->name).'" />';
-        $html .= '<input type="hidden" name="action" value="save2" />';
-        $html .= '<input type="hidden" name="d" value="'.$this->data->id.'" />';
-        $html .= '<input type="hidden" name="sesskey" value="'.$sesskey.'" />';
-        $html .= '<input type="submit" value="'.$strcontinue.'" /></fieldset></form></div>';
-        $html .= print_footer($course, null, true); 
-        echo $html;
-        exit();
-    }
-
-    /**
-     * Second stage of saving a preset: If the given name already exists, 
-     * suggest to use a different name or offer to overwrite the existing preset.
-     */
-    function action_save2($params) {
-        $course = $params['course'];
-        $this->data = $params['data'];
-
-        global $CFG, $USER;
-        if (!data_submitted() or !confirm_sesskey()) {
-            print_error('invalid_request');
-        }
-
-        $strcontinue = get_string('continue');
-        $stroverwrite = get_string('overwrite', 'data');
-        $strname = get_string('shortname');
-
-        $name = $this->best_name(optional_param('name', $this->data->name, PARAM_FILE));
-        $this->shortname = $name;
-        $sesskey = sesskey();
-
-        if (!is_array($this->has_all_required_files("$CFG->dataroot/data/preset/$USER->id/$name"))) {
-            notify("Preset already exists: Pick another name or overwrite ($CFG->dataroot/data/preset/$USER->id/$name)");
-
-            $html .= '<div style="text-align:center">';
-            $html .= '<form action="preset.php" method="post">';
-            $html .= '<fieldset class="invisiblefieldset">';
-            $html .= '<label for="shortname">'.$strname.'</label> <input id="shortname" type="text" name="name" value="'.$name.'" />';
-            $html .= '<input type="hidden" name="action" value="save2" />';
-            $html .= '<input type="hidden" name="d" value="'.$this->data->id.'" />';
-            $html .= '<input type="hidden" name="sesskey" value="'.$sesskey.'" />';
-            $html .= '<input type="submit" value="'.$strcontinue.'" /></fieldset></form>';
-
-            $html .= '<form action="preset.php" method="post">';
-            $html .= '<div>';
-            $html .= '<input type="hidden" name="name" value="'.$name.'" />';
-            $html .= '<input type="hidden" name="action" value="save3" />';
-            $html .= '<input type="hidden" name="d" value="'.$this->data->id.'" />';
-            $html .= '<input type="hidden" name="sesskey" value="'.$sesskey.'" />';
-            $html .= '<input type="submit" value="'.$stroverwrite.'" /></div></form>';
-            $html .= '</div>';
-            $html .= print_footer($course, null, true); 
-            echo $html;
-            exit();
-        } 
-    }
-
-    /**
-     * Third stage of saving a preset, overwrites an existing preset with the new one.
-     */
-    function action_save3($params) {
-        global $CFG, $USER;
-        if (!data_submitted() or !confirm_sesskey()) {
-            print_error('invalidrequest');
-        }
-
-        $name = $this->best_name(optional_param('name', $this->data->name, PARAM_FILE));
-        $this->directory = "/data/preset/$USER->id/$name";
-        $this->shortname = $name;
-        $this->user_id = $USER->id;
-
-        make_upload_directory($this->directory);
-        $this->clean_files($CFG->dataroot.$this->directory);
-
-        $file = $this->export();
-        if (!unzip_file($file, $CFG->dataroot.$this->directory, false)) {
-            print_error('cannotunzipfile'); 
-        }
-        notify(get_string('savesuccess', 'data'), 'notifysuccess'); 
-    }
-}
-
-?>
diff --git a/mod/data/preset_new.php b/mod/data/preset_new.php
deleted file mode 100755 (executable)
index a5132f7..0000000
+++ /dev/null
@@ -1,172 +0,0 @@
-<?php // $Id$
-/* Preset Menu
- *
- * This is the page that is the menu item in the config database
- * pages.
- */
-
-require_once('../../config.php');
-require_once('lib.php');
-require_once($CFG->libdir.'/uploadlib.php');
-require_once($CFG->libdir.'/xmlize.php');
-require_once('preset_class.php');
-
-$id       = optional_param('id', 0, PARAM_INT);    // course module id
-$d        = optional_param('d', 0, PARAM_INT);     // database activity id
-$action   = optional_param('action', 'base', PARAM_ALPHANUM); // current action
-$fullname = optional_param('fullname', '', PARAM_PATH); // directory the preset is in
-$file     = optional_param('file', '', PARAM_FILE); // uploaded file
-
-// find out preset owner userid and shortname
-$parts = explode('/', $fullname);
-$userid = empty($parts[0]) ? 0 : (int)$parts[0];
-$shortname = empty($parts[1]) ? '' : $parts[1];
-unset($parts);
-unset($fullname);
-
-if ($id) {
-    if (! $cm = get_coursemodule_from_id('data', $id)) {
-        print_error('invalidcoursemodule');
-    }
-    if (! $course = $DB->get_record('course', array('id'=>$cm->course))) {
-        print_error('coursemisconf');
-    }
-    if (! $data = $DB->get_record('data', array('id'=>$cm->instance))) {
-        print_error('invalidid', 'data');
-    }
-} else if ($d) {
-    if (! $data = $DB->get_record('data', array('id'=>$d))) {
-        print_error('invalidid', 'data');
-    }
-    if (! $course = $DB->get_record('course', array('id'=>$data->course))) {
-        print_error('coursemisconf');
-    }
-    if (! $cm = get_coursemodule_from_instance('data', $data->id, $course->id)) {
-        print_error('invalidcoursemodule');
-    }
-} else {
-    print_error('missingparameter');
-}
-
-if (!$context = get_context_instance(CONTEXT_MODULE, $cm->id)) {
-    print_error('cannotfindcontext');
-}
-
-require_login($course->id, false, $cm);
-
-require_capability('mod/data:managetemplates', $context);
-
-if ($userid && ($userid != $USER->id) && !has_capability('mod/data:viewalluserpresets', $context)) {
-    print_error('cannotaccesspresentsother', 'data');
-}
-
-/* Need sesskey security check here for import instruction */
-$sesskey = sesskey();
-
-/********************************************************************/
-/* Output */
-data_print_header($course, $cm, $data, 'presets');
-
-$preset = new Data_Preset($shortname, $data->id, null, $userid);
-echo $preset->process_action($action, compact('shortname', 'fullname', 'data', 'userid', 'file', 'course', 'sesskey'));
-
-$presets = data_get_available_presets($context);
-
-$strimport         = get_string('import');
-$strfromfile       = get_string('fromfile', 'data');
-$strchooseorupload = get_string('chooseorupload', 'data');
-$strusestandard    = get_string('usestandard', 'data');
-$strchoose         = get_string('choose');
-$strexport         = get_string('export', 'data');
-$strexportaszip    = get_string('exportaszip', 'data');
-$strsaveaspreset   = get_string('saveaspreset', 'data');
-$strsave           = get_string('save', 'data');
-$strdelete         = get_string('delete');
-
-echo '<div style="text-align:center">';
-echo '<table class="presets" cellpadding="5">';
-echo '<tr><td valign="top" colspan="2" align="center"><h3>'.$strexport.'</h3></td></tr>';
-
-echo '<tr><td><label>'.$strexportaszip.'</label>';
-helpbutton('exportzip', '', 'data');
-echo '</td><td>';
-$options = new object();
-$options->action = 'export';
-$options->d = $data->id;
-$options->sesskey = sesskey();
-print_single_button('preset.php', $options, $strexport, 'post');
-echo '</td></tr>';
-
-echo '<tr><td><label>'.$strsaveaspreset.'</label>';
-helpbutton('savepreset', '', 'data');
-echo '</td><td>';
-$options = new object();
-$options->action = 'save1';
-$options->d = $data->id;
-$options->sesskey = sesskey();
-print_single_button('preset.php', $options, $strsave, 'post');
-echo '</td></tr>';
-
-
-echo '<tr><td valign="top" colspan="2" align="center"><h3>'.$strimport.'</h3></td></tr>';
-
-echo '<tr><td><label for="fromfile">'.$strfromfile.'</label>';
-helpbutton('importfromfile', '', 'data');
-echo '</td><td>';
-
-echo '<form id="uploadpreset" method="post" action="preset.php">';
-echo '<fieldset class="invisiblefieldset">';
-echo '<input type="hidden" name="d" value="'.$data->id.'" />';
-echo '<input type="hidden" name="action" value="importzip" />';
-echo '<input type="hidden" name="sesskey" value="'.sesskey().'" />';
-echo '<input name="file" size="20" value="" id="fromfile" type="text" /><input name="coursefiles" value="'.$strchooseorupload.'" onclick="return openpopup('."'/files/index.php?id=2&amp;choose=uploadpreset.file', 'coursefiles', 'menubar=0,location=0,scrollbars,resizable,width=750,height=500', 0".');" type="button" />';
-echo '<input type="submit" value="'.$strimport.'" />';
-echo '</fieldset></form>';
-echo '</td></tr>';
-
-
-echo '<tr valign="top"><td><label>'.$strusestandard.'</label>';
-helpbutton('usepreset', '', 'data');
-echo '</td><td>';
-
-echo '<form id="presets" method="post" action="preset.php" >';
-echo '<fieldset class="invisiblefieldset">';
-echo '<input type="hidden" name="d" value="'.$data->id.'" />';
-echo '<input type="hidden" name="action" value="importpreset" />';
-echo '<input type="hidden" name="sesskey" value="'.sesskey().'" />';
-
-$i = 0;
-foreach ($presets as $id => $preset) {
-    $screenshot = '';
-    if (!empty($preset->user_id)) {
-        $user = $DB->get_record('user', array('id'=>$preset->user_id));
-        $desc = $preset->name.' ('.fullname($user, true).')';
-    } else {
-        $desc = $preset->name;
-    }
-
-    if (!empty($preset->screenshot)) {
-        $screenshot = '<img width="150" class="presetscreenshot" src="'.$preset->screenshot.'" alt="'.get_string('screenshot').' '.$desc.'" />&nbsp;';
-    }
-
-    $fullname = $preset->user_id.'/'.$preset->shortname;
-
-    $dellink = '';
-    if ($preset->user_id > 0 and ($preset->user_id == $USER->id || has_capability('mod/data:manageuserpresets', $context))) {
-        $dellink = '&nbsp;<a href="preset.php?d='.$data->id.'&amp;action=confirmdelete&amp;fullname='.$fullname.'&amp;sesskey='.sesskey().'">'.
-                   '<img src="'.$CFG->pixpath.'/t/delete.gif" class="iconsmall" alt="'.$strdelete.' '.$desc.'" /></a>';
-    }
-
-    echo '<input type="radio" name="fullname" id="usepreset'.$i.'" value="'.$fullname.'" /><label for="usepreset'.$i++.'">'.$desc.'</label>'.$dellink.'<br />';
-}
-echo '<br />';
-echo '<input type="submit" value="'.$strchoose.'" />';
-echo '</fieldset></form>';
-echo '</td></tr>';
-echo '</table>';
-echo '</div>';
-
-print_footer($course);
-
-
-?>
index e41acfc6d271833bb4043e07c0563a2047bd665d..dd2a45e14f8aed09321de874a8d1c79ffbdec862 100644 (file)
@@ -5,7 +5,7 @@
 //  This fragment is called by /admin/index.php
 ////////////////////////////////////////////////////////////////////////////////
 
-$module->version  = 2008081401;
+$module->version  = 2008091400;
 $module->requires = 2008080701;  // Requires this Moodle version
 $module->cron     = 60;
 
index c28b1fb8892f3bd2813c7411c49994f009d38f31..63c91f0ef475e1e3cf18877f29d011ad83c0465e 100755 (executable)
         $search = '';
         $vals = array();
         $fields = $DB->get_records('data_fields', array('dataid'=>$data->id));
-        
+
         //Added to ammend paging error. This error would occur when attempting to go from one page of advanced
         //search results to another.  All fields were reset in the page transfer, and there was no way of determining
         //whether or not the user reset them.  This would cause a blank search to execute whenever the user attempted
         //execution falls through to the second condition below, allowing paging to be set to true.
         //Paging remains true and keeps getting passed though the URL until a new search is performed
         //(even if page 0 is revisited).
-        //A false $paging flag generates advanced search results based on the fields input by the user. 
+        //A false $paging flag generates advanced search results based on the fields input by the user.
         //A true $paging flag generates davanced search results from the $SESSION global.
         //(See lines 147-158)
-        
+
         $paging = optional_param('paging', NULL, PARAM_BOOL);
         if($page == 0 && !isset($paging)) {
             $paging = false;
         }
         if (!empty($fields)) {
             foreach($fields as $field) {
-                $searchfield = data_get_field_from_id($field->id, $data);
+                $searchfield = data_get_field_from_id($field, $data);
                 //Get field data to build search sql with.  If paging is false, get from user.
                 //If paging is true, get data from $search_array which is obtained from the $SESSION (see line 116).
                 if(!$paging) {
 
     if ($mode == 'asearch') {
         $maxcount = 0;
-        
+
     } else {
     /// Approve any requested records
         $params = array(); // named params array
 
-        $approvecap = has_capability('mod/data:approve', $context); 
+        $approvecap = has_capability('mod/data:approve', $context);
 
         if ($approve && confirm_sesskey() && $approvecap) {
             if ($approverecord = $DB->get_record('data_records', array('id'=>$approve))) {   // Need to check this is valid
                 }
             }
         }
-    
+
         // Check the number of entries required against the number of entries already made (doesn't apply to teachers)
         $requiredentries_allowed = true;
         $numentries = data_numentries($data);
         }
 
     /// Get the actual records
-        
+
         if (!$records = $DB->get_records_sql($sqlselect, $params, $page * $nowperpage, $nowperpage)) {
             // Nothing to show!
             if ($record) {         // Something was requested so try to show that at least (bug 5132)
                 $a->num = $totalcount;
                 $a->max = $maxcount;
                 $a->reseturl = "view.php?id=$cm->id&amp;mode=$mode&amp;search=&amp;advanced=0";
-                notify(get_string('foundrecords', 'data', $a), 'notifysuccess'); 
+                notify(get_string('foundrecords', 'data', $a), 'notifysuccess');
             }
 
             if ($mode == 'single') {                  // Single template
 
         }
     }
-    
+
     $search = trim($search);
     if (empty($records)) {
         $records = array();