예제 #1
0
 /**
  * Sets the custom field data for a specified context and field.
  *
  * @param object $context
  * @param object $field
  * @param mixed $data a single value or an array depending on whether
  *        $field is multivalued or not
  * @param string $plugin
  * @return boolean whether or not the data was modified
  */
 static function set_for_context_and_field($context, $field, $data)
 {
     global $CURMAN;
     if ($context) {
         $contextid = $context->id;
     } else {
         $contextid = NULL;
     }
     $data_table = $field->data_table();
     // FIXME: check exclude, unique, etc
     if ($field->multivalued) {
         $records = field_data::get_for_context_and_field($context, $field);
         $records = $records ? $records : array();
         $todelete = array();
         $toadd = array();
         $existing = array();
         foreach ($records as $rec) {
             if (in_array($rec->data, $data)) {
                 $existing[] = $rec->data;
             } else {
                 $todelete[] = $rec;
             }
         }
         if (is_array($data)) {
             $toadd = array_diff($data, $existing);
         }
         foreach ($todelete as $rec) {
             $CURMAN->db->delete_records($data_table, 'id', $rec->id);
         }
         foreach ($toadd as $value) {
             $rec = new field_data(false, $field->data_type());
             $rec->contextid = $contextid;
             $rec->fieldid = $field->id;
             $rec->data = $value;
             $rec->data_insert_record();
         }
         return !empty($toadd) || !empty($todelete);
     } else {
         if ($rec = $CURMAN->db->get_record($data_table, 'contextid', $contextid, 'fieldid', $field->id)) {
             $fielddata = new field_data($rec, $field->data_type());
             if ($data === NULL) {
                 $fielddata->delete();
                 return true;
             }
             if (addslashes($fielddata->data) == $data) {
                 return false;
             }
             $fielddata->contextid = $contextid;
             // needed, or else NULL becomes 0
             $fielddata->data = $data;
             $fielddata->update();
             return true;
         } elseif ($data !== NULL) {
             $rec = new field_data(false, $field->data_type());
             $rec->contextid = $contextid;
             $rec->fieldid = $field->id;
             $rec->data = $data;
             $rec->add();
             return true;
         }
     }
 }