Example #1
0
 } else {
     $approveselect = ' ';
 }
 if ($currentgroup) {
     $groupselect = " AND (r.groupid = :currentgroup OR r.groupid = 0)";
     $params['currentgroup'] = $currentgroup;
 } else {
     $groupselect = ' ';
 }
 // Init some variables to be used by advanced search
 $advsearchselect = '';
 $advwhere = '';
 $advtables = '';
 $advparams = array();
 /// Find the field we are sorting on
 if ($sort <= 0 or !($sortfield = data_get_field_from_id($sort, $data))) {
     switch ($sort) {
         case DATA_LASTNAME:
             $ordering = "u.lastname {$order}, u.firstname {$order}";
             break;
         case DATA_FIRSTNAME:
             $ordering = "u.firstname {$order}, u.lastname {$order}";
             break;
         case DATA_APPROVED:
             $ordering = "r.approved {$order}, r.timecreated {$order}";
             break;
         case DATA_TIMEMODIFIED:
             $ordering = "r.timemodified {$order}";
             break;
         case DATA_TIMEADDED:
         default:
Example #2
0
            //add instance to data_record
            /// Insert a whole lot of empty records to make sure we have them
            $fields = $DB->get_records('data_fields', array('dataid' => $data->id));
            foreach ($fields as $field) {
                $content->recordid = $recordid;
                $content->fieldid = $field->id;
                $DB->insert_record('data_content', $content);
            }
            /// For each field in the add form, add it to the data_content.
            foreach ($datarecord as $name => $value) {
                if (!in_array($name, $ignorenames)) {
                    $namearr = explode('_', $name);
                    // Second one is the field id
                    if (empty($field->field) || $namearr[1] != $field->field->id) {
                        // Try to reuse classes
                        $field = data_get_field_from_id($namearr[1], $data);
                    }
                    if ($field) {
                        $field->update_content($recordid, $value, $name);
                    }
                }
            }
            add_to_log($course->id, 'data', 'add', "view.php?d={$data->id}&amp;rid={$recordid}", $data->id, $cm->id);
            if (!empty($datarecord->saveandview)) {
                redirect($CFG->wwwroot . '/mod/data/view.php?d=' . $data->id . '&rid=' . $recordid);
            }
        }
    }
}
// End of form processing
/// Print the page header
Example #3
0
}
asort($menufield);
//sort in alphabetical order
$PAGE->set_title(get_string('course') . ': ' . $course->fullname);
$PAGE->set_heading($course->fullname);
$PAGE->set_pagetype('mod-data-field-' . $newtype);
if ($mode == 'new' && !empty($newtype) && confirm_sesskey()) {
    ///  Adding a new field
    data_print_header($course, $cm, $data, 'fields');
    $field = data_get_field_new($newtype, $data);
    $field->display_edit_field();
} else {
    if ($mode == 'display' && confirm_sesskey()) {
        /// Display/edit existing field
        data_print_header($course, $cm, $data, 'fields');
        $field = data_get_field_from_id($fid, $data);
        $field->display_edit_field();
    } else {
        /// Display the main listing of all fields
        data_print_header($course, $cm, $data, 'fields');
        if (!$DB->record_exists('data_fields', array('dataid' => $data->id))) {
            echo $OUTPUT->notification(get_string('nofieldindatabase', 'data'));
            // nothing in database
            echo $OUTPUT->notification(get_string('pleaseaddsome', 'data', 'preset.php?id=' . $cm->id));
            // link to presets
        } else {
            //else print quiz style list of fields
            $table = new html_table();
            $table->head = array(get_string('fieldname', 'data'), get_string('type', 'data'), get_string('fielddescription', 'data'), get_string('action', 'data'));
            $table->align = array('left', 'left', 'left', 'center');
            $table->wrap = array(false, false, false, false);
Example #4
0
    /**
     * Import the preset into the given database module
     * @return bool
     */
    function import($overwritesettings) {
        global $DB, $CFG;

        $params = $this->get_preset_settings();
        $settings = $params->settings;
        $newfields = $params->importfields;
        $currentfields = $params->currentfields;
        $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($currentfields[$cid])) {
                    $fieldobject = data_get_field_from_id($currentfields[$cid]->id, $this->module);
                    foreach ($newfield as $param => $value) {
                        if ($param != "id") {
                            $fieldobject->field->$param = $value;
                        }
                    }
                    unset($fieldobject->field->similarfield);
                    $fieldobject->update_field();
                    unset($fieldobject);
                } else {
                    /* Make a new field */
                    include_once("field/$newfield->type/field.class.php");

                    if (!isset($newfield->description)) {
                        $newfield->description = '';
                    }
                    $classname = 'data_field_'.$newfield->type;
                    $fieldclass = new $classname($newfield, $this->module);
                    $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??
                    $DB->delete_records('data_content', array('fieldid'=>$id));
                    $DB->delete_records('data_fields', array('id'=>$id));
                }
            }
        }

        // handle special settings here
        if (!empty($settings->defaultsort)) {
            if (is_numeric($settings->defaultsort)) {
                // old broken value
                $settings->defaultsort = 0;
            } else {
                $settings->defaultsort = (int)$DB->get_field('data_fields', 'id', array('dataid'=>$this->module->id, 'name'=>$settings->defaultsort));
            }
        } else {
            $settings->defaultsort = 0;
        }

        // do we want to overwrite all current database settings?
        if ($overwritesettings) {
            // all supported settings
            $overwrite = array_keys((array)$settings);
        } else {
            // only templates and sorting
            $overwrite = array('singletemplate', 'listtemplate', 'listtemplateheader', 'listtemplatefooter',
                               'addtemplate', 'rsstemplate', 'rsstitletemplate', 'csstemplate', 'jstemplate',
                               'asearchtemplate', 'defaultsortdir', 'defaultsort');
        }

        // now overwrite current data settings
        foreach ($this->module as $prop=>$unused) {
            if (in_array($prop, $overwrite)) {
                $this->module->$prop = $settings->$prop;
            }
        }

        data_update_instance($this->module);

        return $this->cleanup();
    }
Example #5
0
function data_presets_export($course, $cm, $data)
{
    global $CFG;
    $presetname = clean_filename($data->name) . '-preset-' . gmdate("Ymd_Hi");
    $exportsubdir = "{$course->id}/moddata/data/{$data->id}/{$presetname}";
    make_upload_directory($exportsubdir);
    $exportdir = "{$CFG->dataroot}/{$exportsubdir}";
    // Assemble "preset.xml":
    $presetxmldata = "<preset>\n\n";
    // Raw settings are not preprocessed during saving of presets
    $raw_settings = array('intro', 'comments', 'requiredentries', 'requiredentriestoview', 'maxentries', 'rssarticles', 'approval', 'defaultsortdir');
    $presetxmldata .= "<settings>\n";
    // First, settings that do not require any conversion
    foreach ($raw_settings as $setting) {
        $presetxmldata .= "<{$setting}>" . htmlspecialchars($data->{$setting}) . "</{$setting}>\n";
    }
    // Now specific settings
    if ($data->defaultsort > 0 && ($sortfield = data_get_field_from_id($data->defaultsort, $data))) {
        $presetxmldata .= '<defaultsort>' . htmlspecialchars($sortfield->field->name) . "</defaultsort>\n";
    } else {
        $presetxmldata .= "<defaultsort>0</defaultsort>\n";
    }
    $presetxmldata .= "</settings>\n\n";
    // Now for the fields. Grab all that are non-empty
    $fields = get_records('data_fields', 'dataid', $data->id);
    ksort($fields);
    if (!empty($fields)) {
        foreach ($fields as $field) {
            $presetxmldata .= "<field>\n";
            foreach ($field as $key => $value) {
                if ($value != '' && $key != 'id' && $key != 'dataid') {
                    $presetxmldata .= "<{$key}>" . htmlspecialchars($value) . "</{$key}>\n";
                }
            }
            $presetxmldata .= "</field>\n\n";
        }
    }
    $presetxmldata .= '</preset>';
    // After opening a file in write mode, close it asap
    $presetxmlfile = fopen($exportdir . '/preset.xml', 'w');
    fwrite($presetxmlfile, $presetxmldata);
    fclose($presetxmlfile);
    // Now write the template files
    $singletemplate = fopen($exportdir . '/singletemplate.html', 'w');
    fwrite($singletemplate, $data->singletemplate);
    fclose($singletemplate);
    $listtemplateheader = fopen($exportdir . '/listtemplateheader.html', 'w');
    fwrite($listtemplateheader, $data->listtemplateheader);
    fclose($listtemplateheader);
    $listtemplate = fopen($exportdir . '/listtemplate.html', 'w');
    fwrite($listtemplate, $data->listtemplate);
    fclose($listtemplate);
    $listtemplatefooter = fopen($exportdir . '/listtemplatefooter.html', 'w');
    fwrite($listtemplatefooter, $data->listtemplatefooter);
    fclose($listtemplatefooter);
    $addtemplate = fopen($exportdir . '/addtemplate.html', 'w');
    fwrite($addtemplate, $data->addtemplate);
    fclose($addtemplate);
    $rsstemplate = fopen($exportdir . '/rsstemplate.html', 'w');
    fwrite($rsstemplate, $data->rsstemplate);
    fclose($rsstemplate);
    $rsstitletemplate = fopen($exportdir . '/rsstitletemplate.html', 'w');
    fwrite($rsstitletemplate, $data->rsstitletemplate);
    fclose($rsstitletemplate);
    $csstemplate = fopen($exportdir . '/csstemplate.css', 'w');
    fwrite($csstemplate, $data->csstemplate);
    fclose($csstemplate);
    $jstemplate = fopen($exportdir . '/jstemplate.js', 'w');
    fwrite($jstemplate, $data->jstemplate);
    fclose($jstemplate);
    $asearchtemplate = fopen($exportdir . '/asearchtemplate.html', 'w');
    fwrite($asearchtemplate, $data->asearchtemplate);
    fclose($asearchtemplate);
    // Check if all files have been generated
    if (!is_directory_a_preset($exportdir)) {
        error('Not all files generated!');
        // should be migrated to print_error()
    }
    $filelist = array('preset.xml', 'singletemplate.html', 'listtemplateheader.html', 'listtemplate.html', 'listtemplatefooter.html', 'addtemplate.html', 'rsstemplate.html', 'rsstitletemplate.html', 'csstemplate.css', 'jstemplate.js', 'asearchtemplate.html');
    foreach ($filelist as $key => $file) {
        $filelist[$key] = $exportdir . '/' . $filelist[$key];
    }
    $exportfile = "{$CFG->dataroot}/{$course->id}/moddata/data/{$data->id}/{$presetname}.zip";
    file_exists($exportfile) && unlink($exportfile);
    $status = zip_files($filelist, $exportfile);
    // ToDo: status check
    foreach ($filelist as $file) {
        unlink($file);
    }
    rmdir($exportdir);
    // Return the full path to the exported preset file:
    return $exportfile;
}
Example #6
0
 function import()
 {
     global $CFG;
     list($settings, $newfields, $currentfields) = $this->get_settings();
     $preservedfields = array();
     $overwritesettings = optional_param('overwritesettings', 0, PARAM_BOOL);
     /* 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)) {
                 error("Not an injective map");
             } 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($currentfields[$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);
             } 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 = get_records('data_content', 'fieldid', $id)) {
                                         foreach ($content as $item) {
                                             delete_records('data_ratings', 'recordid', $item->recordid);
                                             delete_records('data_comments', 'recordid', $item->recordid);
                                             delete_records('data_records', 'id', $item->recordid);
                                         }
                                     }*/
                 delete_records('data_content', 'fieldid', $id);
                 delete_records('data_fields', 'id', $id);
             }
         }
     }
     // handle special settings here
     if (!empty($settings->defaultsort)) {
         if (is_numeric($settings->defaultsort)) {
             // old broken value
             $settings->defaultsort = 0;
         } else {
             $settings->defaultsort = (int) get_field('data_fields', 'id', 'dataid', $this->data->id, 'name', addslashes($settings->defaultsort));
         }
     } else {
         $settings->defaultsort = 0;
     }
     // do we want to overwrite all current database settings?
     if ($overwritesettings) {
         // all supported settings
         $overwrite = array_keys((array) $settings);
     } else {
         // only templates and sorting
         $overwrite = array('singletemplate', 'listtemplate', 'listtemplateheader', 'listtemplatefooter', 'addtemplate', 'rsstemplate', 'rsstitletemplate', 'csstemplate', 'jstemplate', 'asearchtemplate', 'defaultsortdir', 'defaultsort');
     }
     // now overwrite current data settings
     foreach ($this->data as $prop => $unused) {
         if (in_array($prop, $overwrite)) {
             $this->data->{$prop} = $settings->{$prop};
         }
     }
     data_update_instance(addslashes_object($this->data));
     if (strstr($this->folder, '/temp/')) {
         // Removes the temporary files
         clean_preset($this->folder);
     }
     return true;
 }
Example #7
0
    /**
     * Set up function. In this instance we are setting up database
     * records to be used in the unit tests.
     */
    protected function setUp() {
        global $DB, $CFG;
        parent::setUp();

        $this->resetAfterTest(true);


        // we already have 2 users, we need 98 more - let's ignore the fact that guest can not post anywhere
        for($i=3;$i<=100;$i++) {
            $this->getDataGenerator()->create_user();
        }

        // create database module - there should be more of these I guess
        $course = $this->getDataGenerator()->create_course();
        $data = $this->getDataGenerator()->create_module('data', array('course'=>$course->id));
        $this->recorddata = $data;

        // Set up data for the test database.
        $files = array(
            'data_fields'  => __DIR__.'/fixtures/test_data_fields.csv',
            'data_records' => __DIR__.'/fixtures/test_data_records.csv',
            'data_content' => __DIR__.'/fixtures/test_data_content.csv',
        );
        $this->loadDataSet($this->createCsvDataSet($files));

        // Create the search array which contains our advanced search criteria.
        $fieldinfo = array('0' => new stdClass(),
            '1' => new stdClass(),
            '2' => new stdClass(),
            '3' => new stdClass(),
            '4' => new stdClass());
        $fieldinfo['0']->id = 1;
        $fieldinfo['0']->data = '3.721,46.6126';
        $fieldinfo['1']->id = 2;
        $fieldinfo['1']->data = 'Hahn Premium';
        $fieldinfo['2']->id = 5;
        $fieldinfo['2']->data = 'Female';
        $fieldinfo['3']->id = 7;
        $fieldinfo['3']->data = 'kel';
        $fieldinfo['4']->id = 9;
        $fieldinfo['4']->data = 'VIC';

        foreach($fieldinfo as $field) {
            $searchfield = data_get_field_from_id($field->id, $data);
            if ($field->id == 2) {
                $searchfield->field->param1 = 'Hahn Premium';
                $val = array();
                $val['selected'] = array('0' => 'Hahn Premium');
                $val['allrequired'] = 0;
            } else {
                $val = $field->data;
            }
            $search_array[$field->id] = new stdClass();
            list($search_array[$field->id]->sql, $search_array[$field->id]->params) = $searchfield->generate_sql('c' . $field->id, $val);
        }

        $this->recordsearcharray = $search_array;

        // Setting up the comparison stdClass for the last test.
        $user = $DB->get_record('user', array('id'=>6));
        $this->finalrecord[6] = new stdClass();
        $this->finalrecord[6]->id = 6;
        $this->finalrecord[6]->approved = 1;
        $this->finalrecord[6]->timecreated = 1234567891;
        $this->finalrecord[6]->timemodified = 1234567892;
        $this->finalrecord[6]->userid = 6;
        $this->finalrecord[6]->firstname = $user->firstname;
        $this->finalrecord[6]->lastname = $user->lastname;
    }
Example #8
0
 /**
  * Creates a field for a mod_data instance.
  * Currently, the field types in the ignoredfieldtypes array aren't supported.
  * The developers using the generator must adhere to the following format :
  *
  *   Syntax : $contents[ fieldid ] = fieldvalue
  *   $contents['checkbox'] = array('val1', 'val2', 'val3' .....)
  *   $contents['data'] = 'dd-mm-yyyy'
  *   $contents['menu'] = 'value';
  *   $contents['multimenu'] =  array('val1', 'val2', 'val3' .....)
  *   $contents['number'] = 'numeric value'
  *   $contents['radiobuton'] = 'value'
  *   $contents['text'] = 'text'
  *   $contents['textarea'] = 'text'
  *   $contents['url'] = 'example.url' or array('example.url', 'urlname')
  *
  * @param mod_data $data
  * @param array $contents
  * @return data_field_{type}
  */
 public function create_entry($data, array $contents)
 {
     global $DB;
     $this->databaserecordcount++;
     $recordid = data_add_record($data);
     $fields = $DB->get_records('data_fields', array('dataid' => $data->id));
     // Validating whether required field are filled.
     foreach ($fields as $field) {
         $fieldhascontent = true;
         if (in_array($field->type, $this->ignoredfieldtypes)) {
             continue;
         }
         $field = data_get_field($field, $data);
         $fieldid = $field->field->id;
         if ($field->type === 'date') {
             $values = array();
             $temp = explode('-', $contents[$fieldid], 3);
             $values['field_' . $fieldid . '_day'] = (int) trim($temp[0]);
             $values['field_' . $fieldid . '_month'] = (int) trim($temp[1]);
             $values['field_' . $fieldid . '_year'] = (int) trim($temp[2]);
             // Year should be less than 2038, so it can be handled by 32 bit windows.
             if ($values['field_' . $fieldid . '_year'] > 2038) {
                 throw new coding_exception('DateTime::getTimestamp resturns false on 32 bit win for year beyond ' . '2038. Please use year less than 2038.');
             }
             $contents[$fieldid] = $values;
             foreach ($values as $fieldname => $value) {
                 if (!$field->notemptyfield($value, $fieldname)) {
                     $fieldhascontent = false;
                 }
             }
         } else {
             if ($field->type === 'textarea') {
                 $values = array();
                 $values['field_' . $fieldid] = $contents[$fieldid];
                 $values['field_' . $fieldid . '_content1'] = 1;
                 $contents[$fieldid] = $values;
                 foreach ($values as $fieldname => $value) {
                     if (!$field->notemptyfield($value, $fieldname)) {
                         $fieldhascontent = false;
                     }
                 }
             } else {
                 if ($field->type === 'url') {
                     $values = array();
                     if (is_array($contents[$fieldid])) {
                         foreach ($contents[$fieldid] as $key => $value) {
                             $values['field_' . $fieldid . '_' . $key] = $value;
                         }
                     } else {
                         $values['field_' . $fieldid . '_0'] = $contents[$fieldid];
                     }
                     $contents[$fieldid] = $values;
                     foreach ($values as $fieldname => $value) {
                         if (!$field->notemptyfield($value, $fieldname)) {
                             $fieldhascontent = false;
                         }
                     }
                 } else {
                     if ($field->notemptyfield($contents[$fieldid], 'field_' . $fieldid . '_0')) {
                         continue;
                     }
                 }
             }
         }
         if ($field->field->required && !$fieldhascontent) {
             return false;
         }
     }
     foreach ($contents as $fieldid => $content) {
         $field = data_get_field_from_id($fieldid, $data);
         if (is_array($content)) {
             foreach ($content as $fieldname => $value) {
                 $field->update_content($recordid, $value, $fieldname);
             }
         } else {
             $field->update_content($recordid, $content);
         }
     }
     return $recordid;
 }
Example #9
0
if (!has_capability('mod/data:managetemplates', $context) && $data->approval) {
    if (isloggedin()) {
        $approveselect = ' AND (r.approved=1 OR r.userid=' . $USER->id . ') ';
    } else {
        $approveselect = ' AND r.approved=1 ';
    }
} else {
    $approveselect = ' ';
}
if ($currentgroup) {
    $groupselect = " AND (r.groupid = '{$currentgroup}' OR r.groupid = 0)";
} else {
    $groupselect = ' ';
}
/// Find the field we are sorting on
if ($sort and $sortfield = data_get_field_from_id($sort, $data)) {
    $sortcontent = $sortfield->get_sort_field();
    $sortcontentfull = $sortfield->get_sort_sql('c.' . $sortcontent);
    $what = ' DISTINCT r.id, r.approved, r.userid, u.firstname, u.lastname, c.' . $sortcontent . ', ' . $sortcontentfull . ' AS _order ';
    $count = ' COUNT(DISTINCT c.recordid) ';
    $tables = $CFG->prefix . 'data_content c,' . $CFG->prefix . 'data_records r,' . $CFG->prefix . 'data_content c1, ' . $CFG->prefix . 'user u ';
    $where = 'WHERE c.recordid = r.id
                     AND c.fieldid = ' . $sort . '
                     AND r.dataid = ' . $data->id . '
                     AND r.userid = u.id
                     AND c1.recordid = r.id ';
    $sortorder = ' ORDER BY _order ' . $order . ' , r.id ASC ';
    // If requiredentries is not reached, only show current user's entries
    if (!$requiredentries_allowed) {
        $where .= ' AND u.id = ' . $USER->id;
    }
Example #10
0
 /**
  * import()
  * TODO document
  */
 function import()
 {
     global $CFG;
     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);
             } 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 = get_records('data_content', 'fieldid', $id)) {
                     foreach ($content as $item) {
                         delete_records('data_ratings', 'recordid', $item->recordid);
                         delete_records('data_comments', 'recordid', $item->recordid);
                         delete_records('data_records', 'id', $item->recordid);
                     }
                 }
                 */
                 delete_records('data_content', 'fieldid', $id);
                 delete_records('data_fields', 'id', $id);
             }
         }
     }
     data_update_instance(addslashes_object($settings));
     if (strstr($this->directory, '/temp/')) {
         clean_preset($this->directory);
     }
     /* Removes the temporary files */
     return true;
 }
    /**
     * Set up function. In this instance we are setting up database
     * records to be used in the unit tests.
     * @todo MDL-32271 use a class for creating safe core moodle tables. This isn't
     * possible at the moment.
     */

    public function setUp() {
        global $DB, $CFG;

        // Set up test database and appropriate tables.
        parent::setUp();
        $this->create_test_tables(array('data', 'data_fields', 'data_records', 'data_content'), 'mod/data');
        $this->create_test_tables(array('user', 'modules', 'course_modules','context'), 'lib');
        $this->switch_to_test_db();

        // Set up data for the test database.
        $tablename = array('0' => 'user',
                           '1' => 'data_fields',
                           '2' => 'data_records',
                           '3' => 'data_content',
                           '4' => 'modules',
                           '5' => 'course_modules',
                           '6' => 'context');

        for ($i = 0; $i < 7; $i++) {
            $filename = $CFG->dirroot . '/mod/data/simpletest/test_' . $tablename[$i] . '.csv';
            if (file_exists($filename)) {
                $file = file_get_contents($filename);
            }
            $this->insert_data_from_csv($file, $tablename[$i]);
        }

        // Set up a data record.
        $datarecord = new stdClass();
        $datarecord->course = '99999';
        $datarecord->name = 'test database';
        $datarecord->intro = 'Test Database for unit testing';
        $datarecord->introformat = '1';
        $DB->insert_record('data', $datarecord, false);
        $data = $DB->get_record('data', array('id'=> '1'));
        $this->recorddata = $data;

        // Create the search array which contains our advanced search criteria.

        $fieldinfo = array('0' => new stdClass(),
                           '1' => new stdClass(),
                           '2' => new stdClass(),
                           '3' => new stdClass(),
                           '4' => new stdClass());
        $fieldinfo['0']->id = 1;
        $fieldinfo['0']->data = '3.721,46.6126';
        $fieldinfo['1']->id = 2;
        $fieldinfo['1']->data = 'Hahn Premium';
        $fieldinfo['2']->id = 5;
        $fieldinfo['2']->data = 'Female';
        $fieldinfo['3']->id = 7;
        $fieldinfo['3']->data = 'kel';
        $fieldinfo['4']->id = 9;
        $fieldinfo['4']->data = 'VIC';

        foreach($fieldinfo as $field) {
            $searchfield = data_get_field_from_id($field->id, $data);
            if ($field->id == 2) {
                $searchfield->field->param1 = 'Hahn Premium';
                $val = array();
                $val['selected'] = array('0' => 'Hahn Premium');
                $val['allrequired'] = 0;
            } else {
                $val = $field->data;
            }
            $search_array[$field->id] = new stdClass();
            list($search_array[$field->id]->sql, $search_array[$field->id]->params) = $searchfield->generate_sql('c' . $field->id, $val);
        }

        $this->recordsearcharray = $search_array;

        // Setting up the comparison stdClass for the last test.
        $this->finalrecord[6] = new stdClass();
        $this->finalrecord[6]->id = 6;
        $this->finalrecord[6]->approved = 1;
        $this->finalrecord[6]->timecreated = 1234567891;
        $this->finalrecord[6]->timemodified = 1234567892;
        $this->finalrecord[6]->userid = 6;
        $this->finalrecord[6]->firstname = 'Benedict';
        $this->finalrecord[6]->lastname = 'Horn';
    }
Example #12
0
 /**
  * Set up function. In this instance we are setting up database
  * records to be used in the unit tests.
  */
 protected function setUp()
 {
     global $DB, $CFG;
     parent::setUp();
     $this->resetAfterTest(true);
     // we already have 2 users, we need 98 more - let's ignore the fact that guest can not post anywhere
     // We reset the user sequence here to ensure we get the expected numbers.
     // TODO: Invent a better way for managing data file input against database sequence id's.
     $DB->get_manager()->reset_sequence('user');
     for ($i = 3; $i <= 100; $i++) {
         $this->getDataGenerator()->create_user();
     }
     // create database module - there should be more of these I guess
     $course = $this->getDataGenerator()->create_course();
     $data = $this->getDataGenerator()->create_module('data', array('course' => $course->id));
     $this->recorddata = $data;
     // Set up data for the test database.
     $files = array('data_fields' => __DIR__ . '/fixtures/test_data_fields.csv', 'data_records' => __DIR__ . '/fixtures/test_data_records.csv', 'data_content' => __DIR__ . '/fixtures/test_data_content.csv');
     $this->loadDataSet($this->createCsvDataSet($files));
     // Set dataid to the correct value now the data has been inserted by csv file.
     $DB->execute('UPDATE {data_fields} SET dataid = ?', array($data->id));
     $DB->execute('UPDATE {data_records} SET dataid = ?', array($data->id));
     // Create the search array which contains our advanced search criteria.
     $fieldinfo = array('0' => new stdClass(), '1' => new stdClass(), '2' => new stdClass(), '3' => new stdClass(), '4' => new stdClass());
     $fieldinfo['0']->id = 1;
     $fieldinfo['0']->data = '3.721,46.6126';
     $fieldinfo['1']->id = 2;
     $fieldinfo['1']->data = 'Hahn Premium';
     $fieldinfo['2']->id = 5;
     $fieldinfo['2']->data = 'Female';
     $fieldinfo['3']->id = 7;
     $fieldinfo['3']->data = 'kel';
     $fieldinfo['4']->id = 9;
     $fieldinfo['4']->data = 'VIC';
     foreach ($fieldinfo as $field) {
         $searchfield = data_get_field_from_id($field->id, $data);
         if ($field->id == 2) {
             $searchfield->field->param1 = 'Hahn Premium';
             $val = array();
             $val['selected'] = array('0' => 'Hahn Premium');
             $val['allrequired'] = 0;
         } else {
             $val = $field->data;
         }
         $search_array[$field->id] = new stdClass();
         list($search_array[$field->id]->sql, $search_array[$field->id]->params) = $searchfield->generate_sql('c' . $field->id, $val);
     }
     $this->recordsearcharray = $search_array;
     // Setting up the comparison stdClass for the last test.
     $user = $DB->get_record('user', array('id' => 6));
     $this->finalrecord[6] = new stdClass();
     $this->finalrecord[6]->id = 6;
     $this->finalrecord[6]->approved = 1;
     $this->finalrecord[6]->timecreated = 1234567891;
     $this->finalrecord[6]->timemodified = 1234567892;
     $this->finalrecord[6]->userid = 6;
     $this->finalrecord[6]->firstname = $user->firstname;
     $this->finalrecord[6]->lastname = $user->lastname;
     $this->finalrecord[6]->firstnamephonetic = $user->firstnamephonetic;
     $this->finalrecord[6]->lastnamephonetic = $user->lastnamephonetic;
     $this->finalrecord[6]->middlename = $user->middlename;
     $this->finalrecord[6]->alternatename = $user->alternatename;
     $this->finalrecord[6]->picture = $user->picture;
     $this->finalrecord[6]->imagealt = $user->imagealt;
     $this->finalrecord[6]->email = $user->email;
 }
Example #13
0
 /**
  * Test 1: The function data_get_all_recordids.
  *
  * Test 2: This tests the data_get_advance_search_ids() function. The function takes a set
  * of all the record IDs in the database and then with the search details ($this->recordsearcharray)
  * returns a comma seperated string of record IDs that match the search criteria.
  *
  * Test 3: This function tests data_get_recordids(). This is the function that is nested in the last
  * function (see data_get_advance_search_ids). This function takes a couple of
  * extra parameters. $alias is the field alias used in the sql query and $commaid
  * is a comma seperated string of record IDs.
  *
  * Test 3.1: This tests that if no recordids are provided (In a situation where a search is done on an empty database)
  * That an empty array is returned.
  *
  * Test 4: data_get_advanced_search_sql provides an array which contains an sql string to be used for displaying records
  * to the user when they use the advanced search criteria and the parameters that go with the sql statement. This test
  * takes that information and does a search on the database, returning a record.
  *
  * Test 5: Returning to data_get_all_recordids(). Here we are ensuring that the total amount of record ids is reduced to
  * match the group conditions that are provided. There are 25 entries which relate to group 2. They are removed
  * from the total so we should only have 75 records total.
  *
  * Test 6: data_get_all_recordids() again. This time we are testing approved database records. We only want to
  * display the records that have been approved. In this record set we have 89 approved records.
  */
 public function test_advanced_search_sql_section()
 {
     global $DB;
     // we already have 2 users, we need 98 more - let's ignore the fact that guest can not post anywhere
     // We reset the user sequence here to ensure we get the expected numbers.
     // TODO: Invent a better way for managing data file input against database sequence id's.
     $DB->get_manager()->reset_sequence('user');
     for ($i = 3; $i <= 100; $i++) {
         $this->getDataGenerator()->create_user();
     }
     // create database module - there should be more of these I guess
     $course = $this->getDataGenerator()->create_course();
     $data = $this->getDataGenerator()->create_module('data', array('course' => $course->id));
     $this->recorddata = $data;
     // Set up data for the test database.
     $files = array('data_fields' => __DIR__ . '/fixtures/test_data_fields.csv', 'data_records' => __DIR__ . '/fixtures/test_data_records.csv', 'data_content' => __DIR__ . '/fixtures/test_data_content.csv');
     $this->loadDataSet($this->createCsvDataSet($files));
     // Set dataid to the correct value now the data has been inserted by csv file.
     $DB->execute('UPDATE {data_fields} SET dataid = ?', array($data->id));
     $DB->execute('UPDATE {data_records} SET dataid = ?', array($data->id));
     // Create the search array which contains our advanced search criteria.
     $fieldinfo = array('0' => new stdClass(), '1' => new stdClass(), '2' => new stdClass(), '3' => new stdClass(), '4' => new stdClass());
     $fieldinfo['0']->id = 1;
     $fieldinfo['0']->data = '3.721,46.6126';
     $fieldinfo['1']->id = 2;
     $fieldinfo['1']->data = 'Hahn Premium';
     $fieldinfo['2']->id = 5;
     $fieldinfo['2']->data = 'Female';
     $fieldinfo['3']->id = 7;
     $fieldinfo['3']->data = 'kel';
     $fieldinfo['4']->id = 9;
     $fieldinfo['4']->data = 'VIC';
     foreach ($fieldinfo as $field) {
         $searchfield = data_get_field_from_id($field->id, $data);
         if ($field->id == 2) {
             $searchfield->field->param1 = 'Hahn Premium';
             $val = array();
             $val['selected'] = array('0' => 'Hahn Premium');
             $val['allrequired'] = 0;
         } else {
             $val = $field->data;
         }
         $search_array[$field->id] = new stdClass();
         list($search_array[$field->id]->sql, $search_array[$field->id]->params) = $searchfield->generate_sql('c' . $field->id, $val);
     }
     $this->recordsearcharray = $search_array;
     // Setting up the comparison stdClass for the last test.
     $user = $DB->get_record('user', array('id' => 6));
     $this->finalrecord[6] = new stdClass();
     $this->finalrecord[6]->id = 6;
     $this->finalrecord[6]->approved = 1;
     $this->finalrecord[6]->timecreated = 1234567891;
     $this->finalrecord[6]->timemodified = 1234567892;
     $this->finalrecord[6]->userid = 6;
     $this->finalrecord[6]->firstname = $user->firstname;
     $this->finalrecord[6]->lastname = $user->lastname;
     $this->finalrecord[6]->firstnamephonetic = $user->firstnamephonetic;
     $this->finalrecord[6]->lastnamephonetic = $user->lastnamephonetic;
     $this->finalrecord[6]->middlename = $user->middlename;
     $this->finalrecord[6]->alternatename = $user->alternatename;
     $this->finalrecord[6]->picture = $user->picture;
     $this->finalrecord[6]->imagealt = $user->imagealt;
     $this->finalrecord[6]->email = $user->email;
     // Test 1
     $recordids = data_get_all_recordids($this->recorddata->id);
     $this->assertEquals(count($recordids), $this->datarecordcount);
     // Test 2
     $key = array_keys($this->recordsearcharray);
     $alias = $key[0];
     $newrecordids = data_get_recordids($alias, $this->recordsearcharray, $this->recorddata->id, $recordids);
     $this->assertEquals($this->datarecordset, $newrecordids);
     // Test 3
     $newrecordids = data_get_advance_search_ids($recordids, $this->recordsearcharray, $this->recorddata->id);
     $this->assertEquals($this->datarecordset, $newrecordids);
     // Test 3.1
     $resultrecordids = data_get_advance_search_ids(array(), $this->recordsearcharray, $this->recorddata->id);
     $this->assertEmpty($resultrecordids);
     // Test 4
     $sortorder = 'ORDER BY r.timecreated ASC , r.id ASC';
     $html = data_get_advanced_search_sql('0', $this->recorddata, $newrecordids, '', $sortorder);
     $allparams = array_merge($html['params'], array('dataid' => $this->recorddata->id));
     $records = $DB->get_records_sql($html['sql'], $allparams);
     $this->assertEquals($records, $this->finalrecord);
     // Test 5
     $groupsql = " AND (r.groupid = :currentgroup OR r.groupid = 0)";
     $params = array('currentgroup' => 1);
     $recordids = data_get_all_recordids($this->recorddata->id, $groupsql, $params);
     $this->assertEquals($this->groupdatarecordcount, count($recordids));
     // Test 6
     $approvesql = ' AND r.approved=1 ';
     $recordids = data_get_all_recordids($this->recorddata->id, $approvesql, $params);
     $this->assertEquals($this->approvedatarecordcount, count($recordids));
 }