Collections functions
Encryption functions
General functions
Theme permission functions
Resource functions

update_field()

Description

Updates resource field. Works out the previous value, so this is
not efficient if we already know what this previous value is (hence
it is not used for edit where multiple fields are saved)

Parameters

ColumnTypeDefaultDescription
$resource integer Resource ID
$field integer Field ID
$value string The new value
&$errors array array Any errors that may occur during update
$log true

Return

boolean

Location

include/resource_functions.php lines 2123 to 2358

Definition

 
function update_field($resource$field$value, array &$errors = array(), $log=true)
    {
    global 
$FIXED_LIST_FIELD_TYPES$NODE_FIELDS$category_tree_add_parents$username,$userref;
    
    
$resource_data get_resource_data($resource);
    if (
$resource_data["lock_user"] > && $resource_data["lock_user"] != $userref)
        {
        
$errors[] = get_resource_lock_message($resource_data["lock_user"]);
        return 
false;
        }

    
// accept shortnames in addition to field refs
    
if(!is_numeric($field))
        {
        
$field sql_value("SELECT ref AS `value` FROM resource_type_field WHERE name = '" escape_check($field) . "'"''"schema");
        }

    
// Fetch some information about the field
    
$fieldinfo sql_query("SELECT ref, keywords_index, resource_column, partial_index, type, onchange_macro FROM resource_type_field WHERE ref = '$field'""schema");

    if(
== count($fieldinfo))
        {
        
$errors[] = "No field information about field ID '{$field}'";

        return 
false;
        }
    else
        {
        
$fieldinfo $fieldinfo[0];
        }

    
$fieldoptions get_nodes($fieldnull, ($fieldinfo['type'] == FIELD_TYPE_CATEGORY_TREE));
    
$newvalues    trim_array(explode(','$value));

    
// Set up arrays of node ids to add/remove. 
    
if(in_array($fieldinfo['type'], $NODE_FIELDS))
        {
        
$errors[] = "WARNING: Updates for fixed list fields should not use update_field. Use add_resource_nodes or add_resource_nodes_multi instead. Field: '{$field}'";
        
$nodes_to_add    = array();
        
$nodes_to_remove = array();
        }
        
    
# If this is a date range field we need to add values to the field options
    
if($fieldinfo['type'] == FIELD_TYPE_DATE_RANGE)
        {
        
$newvalues array_map('trim'explode('/'$value));
        
$currentoptions = array();

        foreach(
$newvalues as $newvalue)
            {
            
# Check if each new value exists in current options list
            
if('' != $newvalue && !in_array($newvalue$currentoptions))
                {
                
# Append the option and update the field
                
$newnode          set_node(null$fieldescape_check(trim($newvalue)), nullnulltrue);
                
$nodes_to_add[]   = $newnode;
                
$currentoptions[] = trim($newvalue);

                
debug("update_field: field option added: '" trim($newvalue) . "'<br />");
                }
            }
        }
    elseif(
$fieldinfo['type'] == FIELD_TYPE_DYNAMIC_KEYWORDS_LIST && !checkperm('bdk' $field))
        {
        
# If this is a dynamic keyword we need to add it to the field options
        
$currentoptions = array();
        foreach(
$fieldoptions as $fieldoption)
            {
            
$fieldoptiontranslations explode('~'$fieldoption['name']);
            
            if(
count($fieldoptiontranslations) < 2)
                {
                
$currentoptions[]=trim($fieldoption['name']); # Not a translatable field
                
debug("update_field: current field option: '" trim($fieldoption['name']) . "'<br />");
                }
            else
                {
                
$default="";
                for (
$n=1;$n<count($fieldoptiontranslations);$n++)
                    {
                    
# Not a translated string, return as-is
                    
if (substr($fieldoptiontranslations[$n],2,1)!=":" && substr($fieldoptiontranslations[$n],5,1)!=":" && substr($fieldoptiontranslations[$n],0,1)!=":")
                        {
                        
$currentoptions[]=trim($fieldoption['name']);
                        
debug("update_field: current field option: '" $fieldoption['name'] . "'<br />");
                        }
                    else
                        {
                        
# Support both 2 character and 5 character language codes (for example en, en-US).
                        
$p=strpos($fieldoptiontranslations[$n],':');                         
                        
$currentoptions[]=trim(substr($fieldoptiontranslations[$n],$p+1));
                        
debug("update_field: current field option: '" trim(substr($fieldoptiontranslations[$n],$p+1)) . "'<br />");
                        }
                    }
                }
            }

        foreach(
$newvalues as $newvalue)
            {
            
# Check if each new value exists in current options list
            
if('' != $newvalue && !in_array($newvalue$currentoptions))
                {
                
# Append the option and update the field
                
$newnode          set_node(null$fieldescape_check(trim($newvalue)), nullnulltrue);
                
$nodes_to_add[]   = $newnode;
                
$currentoptions[] = trim($newvalue);

                
debug("update_field: field option added: '" trim($newvalue) . "'<br />");
                }
            }
        }

    
# Fetch previous value
    
$existing sql_value("select value from resource_data where resource='$resource' and resource_type_field='$field'","");

    if (
in_array($fieldinfo['type'], $NODE_FIELDS))
        {
        
$newvalues = array();
        foreach(
$fieldoptions as $nodedata)
            {
            
$newvalues_translated $newvalues;
            
$translate_newvalues array_walk(
                
$newvalues_translated,
                function (&
$value$index)
                    {
                    
$value i18n_get_translated($value);
                    }
            );
            
// Add to array of nodes, unless it has been added to array already as a parent for a previous node
            
if (in_array(i18n_get_translated($nodedata["name"]), $newvalues_translated) && !in_array($nodedata["ref"], $nodes_to_add)) 
                {
                
$nodes_to_add[] = $nodedata["ref"];
                
// We need to add all parent nodes for category trees
                
if($fieldinfo['type']==FIELD_TYPE_CATEGORY_TREE && $category_tree_add_parents
                    {
                    
$parent_nodes=get_parent_nodes($nodedata["ref"]);
                    foreach(
$parent_nodes as $parent_node_ref=>$parent_node_name)
                        {
                        
$nodes_to_add[]=$parent_node_ref;
                        if (!
in_array(i18n_get_translated($parent_node_name), $newvalues_translated))
                            {
                            
$value $parent_node_name "," $value;    
                            }
                        }
                    }
                }
            else
                {
                
$nodes_to_remove[] = $nodedata["ref"];
                }
            
$newvalues[] = $value;
            }

        
# Update resource_node table
        
db_begin_transaction("update_field_{$field}");
        if(
count($nodes_to_remove)>0)
            {
            
delete_resource_nodes($resource,$nodes_to_removefalse);
            }

        if(
count($nodes_to_add)>0)
            {
            
add_resource_nodes($resource,$nodes_to_addfalsefalse);
            }

        
log_node_changes($resource,$nodes_to_add,$nodes_to_remove);

        
db_end_transaction("update_field_{$field}");
        
$value implode(",",$newvalues);
        }
    else
        {
        if (
$fieldinfo["keywords_index"])
            {
            
$is_html=($fieldinfo["type"]==8);    
            
# If there's a previous value, remove the index for those keywords
            
$existing=sql_value("select value from resource_data where resource='$resource' and resource_type_field='$field'","");
            if (
strlen($existing)>0)
                {
                
remove_keyword_mappings($resource,i18n_get_indexable($existing),$field,$fieldinfo["partial_index"],false,'','',$is_html);
                }

            
// Index the new value
            
add_keyword_mappings($resource,i18n_get_indexable($value),$field,$fieldinfo["partial_index"],false,'','',$is_html);
            }

        
# Delete the old value (if any) and add a new value.
        
sql_query("delete from resource_data where resource='$resource' and resource_type_field='$field'");

        
$value escape_check($value);

        
# write to resource_data if not an empty value
        
if($value !== '')
            {
            
sql_query("insert into resource_data(resource,resource_type_field,value) values ('$resource','$field','$value')");
            }
        }

    
# If this is a 'joined' field we need to add it to the resource column
    
$joins get_resource_table_joins();

   if(
in_array($fieldinfo['ref'],$joins))
        {
        if (
$value!="null")
            {
            global 
$resource_field_column_limit;
            
$truncated_value truncate_join_field_value($value);
            
// Remove backslashes from the end of the truncated value
            
if(substr($truncated_value, -1) === '\\')
                {
                
$truncated_value substr($truncated_value0strlen($truncated_value) - 1);
                }
            }
        else
            {
            
$truncated_value="null";
            }        
        
sql_query("update resource set field".$field."=" . (($value=="")?"NULL":"'" $truncated_value "'") ." where ref='$resource'");
        }            
    
    
# Add any onchange code
    
if($fieldinfo["onchange_macro"]!="")
        {
        eval(
$fieldinfo["onchange_macro"]);    
        }
    
    
// Log this update
    
if ($log && $value != $existing)
        {
        
resource_log($resource,LOG_CODE_EDITED,$field,"",$existing,unescape($value));
        }
    
    
# Allow plugins to perform additional actions.
    
hook("update_field","",array($resource,$field,$value,$existing));
    return 
true;
    }

This article was last updated 15th July 2020 02:05 Europe/London time based on the source file dated 13th July 2020 14:40 Europe/London time.