Coding standards
Security in ResourceSpace
Developer reference
Database
Action functions
Admin functions
Ajax functions
Annotation functions
API functions
Collections functions
Comment functions
Config functions
CSV export functions
Dash functions
Debug functions
Encryption functions
Facial recognition functions
File functions
General functions
Language functions
Log functions
Login functions
Message functions
Migration functions
Node functions
PDF functions
Plugin functions
Render functions
Reporting functions
Request functions
Research functions
Slideshow functions
Theme permission functions
User functions
Video functions
Database functions
Metadata functions
Resource functions
Search functions
Map functions
Job functions
Tab functions
Test functions

get_resource_field_data_batch()

Description

get_resource_field_data_batch - Get all resource data for the given resources

Returns a multidimensional array with resource IDs as top level keys, then fields (order determined by $ord_by setting)
IMPORTANT: This differs from get_resource_field_data() in that only fields containing data will be returned.

e.g.
Array
(
[119912] => array
(
[0] => Array
(
[resource] => 119912
[value] => This is the title of resource 119912
[resource_type_field] => 8
[ref] => 8
[name] => title
[title] => Title
[field_constraint] => 0
[type] => 1))
....


"csvexport" (bool) - get data for CSV export (uses \ separator for category tree nodes)
"personal" (bool) - include data in fields marked as personal
"alldata" (bool) - include data in all fields, including technical metadata

Parameters

ColumnTypeDefaultDescription
$resources array (either an array of resource ids or an array returned from search results)
$use_permissions bool true Honour user permissions e.g. field access. TRUE by default
$external_access bool false Only get data permitted to view externally. FALSE by default
$ord_by bool false Use field order_by setting. FALSE by default (order is by resource type first)
$exportoptions mixed array Array of options as below

Return

array Array of resource data organised by resource then metadata field ID

Location

include/resource_functions.php lines 3583 to 3829

Definition

 
function get_resource_field_data_batch($resources,$use_permissions=true,$external_access=false,$ord_by=false$exportoptions = array())
    {
    
# Returns field data and field properties (resource_type_field and resource_data tables)
    # for all the resource references in the array $refs.
    # This will use a single SQL query and is therefore a much more efficient way of gathering
    # resource data for a list of resources (e.g. search result display for a page of resources).
    
if (count($resources)==0) {return array();} # return an empty array if no resources specified (for empty result sets)

    
global $view_title_field$NODE_FIELDS;

    
$restype $allresdata = [];
    
$csvexport = isset($exportoptions["csvexport"]) ? $exportoptions["csvexport"] : false;
    
$personal = isset($exportoptions["personal"]) ? $exportoptions["personal"] : false;
    
$alldata = isset($exportoptions["alldata"]) ? $exportoptions["alldata"] : false;
    
$nontree_field_types array_diff($NODE_FIELDS,array(FIELD_TYPE_CATEGORY_TREE));

    
// Get field_info
    
$tree_fields get_resource_type_fields("","ref","asc",'',array(FIELD_TYPE_CATEGORY_TREE));
    
$field_restypes get_resource_type_field_resource_types();
    
$fields_info ps_query(
        
"SELECT f.ref resource_type_field,
                f.ref AS fref,
                f.required AS frequired, " 
.
                
columns_in("resource_type_field""f") . 
        
" FROM resource_type_field f
        WHERE (f.active=1 AND f.type IN (" 
ps_param_insert(count($nontree_field_types)) . "))
        ORDER BY f.order_by, f.ref"
,
        
ps_param_fill($nontree_field_types'i')
    );

    
# Build arrays of resources
    
$resource_chunks array_chunk($resources,SYSTEM_DATABASE_IDS_CHUNK_SIZE);
    foreach(
$resource_chunks as $resource_chunk)
        {
        if(isset(
$resource_chunk[0]["resource_type"]))
            {
            
// This is an array of search results so we already have the resource types
            
$restype array_column($resource_chunk,"resource_type","ref");
            
$resourceids array_filter(array_column($resource_chunk,"ref"), 'is_int_loose');
            
$getresources $resource_chunk;
            }
        else
            {
            
$resource_chunk array_filter($resource_chunk'is_int_loose');
            if (
$resource_chunk === [])
                {
                break;
                }
            
$resourceids $resource_chunk;
            
$allresourcedata ps_query("SELECT ref, resource_type FROM resource WHERE ref IN (" ps_param_insert(count($resource_chunk)) . ")"ps_param_fill($resource_chunk,"i"));
            foreach(
$allresourcedata as $resourcedata)
                {
                
$restype[$resourcedata["ref"]] = $resourcedata["resource_type"];
                }
            
$getresources = array();
            foreach(
$resource_chunk as $resource)
                {
                
$getresources[]["ref"] = $resource;
                }
            }
    
        
# Fields array is no longer built from direct SQL using group concat
        
$fields=array();

        
# Fetch field values at node level for all resources in chunk ensuring that multiple node values are ordered correctly
        
$field_value_sql 
        
"SELECT rn.resource, n.resource_type_field `field`, rn.node, n.name 
            FROM resource_node rn
        INNER JOIN node n on n.ref = rn.node and rn.resource IN (" 
ps_param_insert(count($resourceids)) . ")
        ORDER BY rn.resource, n.resource_type_field, n.order_by"
;

        
$field_values_allresources ps_query($field_value_sql,ps_param_fill($resourceids,"i"));

        
# Append an ending sentinal
        
$field_values_allresources[]=array('resource'=>null,'field'=>null,'node'=>null,'name'=>null); 

        
$field_node_list=array();
        
$field_ref_list=array();
        
$last_resource=null;
        
$last_field=null;

        
# Assemble comma separated lists of node names and refs to attach to the fields array
        
foreach($field_values_allresources as $field_value) {
            
$this_resource=$field_value['resource'];
            if(
$this_resource===null && $last_resource===null) { break; } # Sentinal reached, nothing to assemble
            
$this_field=$field_value['field'];
            if(
$this_resource===$last_resource) {
                
# Same resource
                
if($this_field===$last_field) {
                    
# Same field so append
                    
$field_node_list[$this_field]['values'] .= (", " $field_value['name']);
                    
$field_ref_list[$this_field]['refs'] .= ("," $field_value['node']);
                }
                else {
                    
# New field so replace
                    
$field_node_list[$this_field]['values'] = $field_value['name'];
                    
$field_ref_list[$this_field]['refs'] = $field_value['node'];
                    
$last_field=$this_field;
                }
            }
            else {
                
# Change of resource
                
if(!is_null($last_resource)) {
                    
# Process the data just assembled for the last resource

                    # Build an array of fields for this resource using the fields_info array
                    
foreach (array_keys($fields_info) as $fikey) {
                        
$this_base_field=$fields_info[$fikey]['resource_type_field'];
                        
# Add base field info for this field
                        
$data_for_this_field=$fields_info[$fikey];
                        
# Now enrich the data for this field for this resource
                        
$data_for_this_field['resource'] = $last_resource;
                        if(isset(
$field_node_list[$this_base_field])) {
                            
$data_for_this_field['value'] = $field_node_list[$this_base_field]['values'];
                            
$data_for_this_field['nodes'] = $field_ref_list[$this_base_field]['refs'];
                            
# The data for this resource field is ready so attach it to the final result array for this chunk
                            
$fields[]=$data_for_this_field;
                        }
                        else {
                            
# Empty fields are not attached
                            
$data_for_this_field['value'] = null;
                            
$data_for_this_field['nodes'] = null;
                        }
                    }

                    
# Clear node list and ref list for new resource
                    
$field_node_list=array();
                    
$field_ref_list=array();
                    
$last_field=null;
                    if(
$this_resource===null) { 
                        break; 
                    } 
# Sentinal reached, assembly is complete
                
}
                
# Attach 
                
if($this_field===$last_field) {
                    
# Same field so append
                    
$field_node_list[$this_field]['values'] .= (", " $field_value['name']);
                    
$field_ref_list[$this_field]['refs'] .= ("," $field_value['node']);
                }
                else {
                    
# New field so replace
                    
$field_node_list[$this_field]['values'] = $field_value['name'];
                    
$field_ref_list[$this_field]['refs'] = $field_value['node'];
                    
$last_field=$this_field;
                }
                
$last_resource=$this_resource;
            }

        } 
# End of allresources for this chunk

        
foreach($tree_fields as $tree_field)
            {
            
// Establish the tree strings for all nodes belonging to the tree field
            
$addfield $tree_field;
            
// Now for each resource, build an array consisting of all of the paths for the selected nodes
            
foreach($getresources as $getresource)
                {
                
$treenodes get_cattree_nodes_ordered($tree_field["ref"], $getresource["ref"], false); # True means get all nodes; False means get selected nodes
                
$treenodenames get_cattree_node_strings($treenodestrue); # True means names are paths to nodes; False means names are node names

                
$valstring $csvexport ? ("\"" implode("\",\"",$treenodenames) . "\"") : implode(",",$treenodenames);

                
$addfield["resource"] = $getresource["ref"];
                
$addfield["value"] = count($treenodenames) > $valstring "";
                
$addfield["resource_type_field"] = $tree_field["ref"];
                
$addfield["fref"] = $tree_field["ref"];
                
$fields[] = $addfield;
                }
            }

        
// Prepare the all resource data array if there is data
        
if (empty($fields))
            {
            return array();
            }

        
// Convert to array with resource ID as index
        
for ($n=0;$n<count($fields);$n++)
            {
            
$rowadded false;
            if (!isset(
$allresdata[$fields[$n]["resource"]]))
                {
                
$allresdata[$fields[$n]["resource"]]=[];
                }

            
// Skip fields which are not applicable
            
if($fields[$n]["global"] != && (!isset($field_restypes[$fields[$n]["ref"]]) || !in_array($restype[$fields[$n]["resource"]],$field_restypes[$fields[$n]["ref"]])))
                {
                
// This resource's resource_type is not associated with this field
                
continue;
                }

            
// Add data to array
            
if  (
                    (!
$use_permissions
                    
||
                    (
$fields[$n]["resource"]<&& checkperm("P" $fields[$n]["fref"])) // Upload only edit access to this field
                    
||                
                    
metadata_field_view_access($fields[$n]["fref"])
                    )
                &&
                    (!(
$external_access && !$fields[$n]["external_user_access"]))
                &&
                    (!
$personal || $fields[$n]["personal_data"])
                &&
                    (
$alldata || $fields[$n]["include_in_csv_export"])
                )
                {
                
$fields[$n]["title"] = lang_or_i18n_get_translated($fields[$n]["title"], "fieldtitle-");
                
$allresdata[$fields[$n]["resource"]][$fields[$n]["ref"]] = $fields[$n];
                
$rowadded true;
                }

            
# Add title field
            
if  (!$rowadded &&
                    
$fields[$n]['ref'] == $view_title_field  #Check field against $title_field for default title reference
                    
&&
                    
metadata_field_view_access($fields[$n]["fref"]) #Check permissions to access title field
                    
)
                {
                
$allresdata[$fields[$n]["resource"]][$fields[$n]["ref"]] = $fields[$n];
                }
            }
        }
    
$fields = array();
    foreach(
$allresdata as $resourceid => $resdata)
        {
        
$fieldorder_by = array();
        
$fieldglobal = array();
        
$fieldref = array();
        foreach(
$resdata as $fkey => $field)
            {
            
$fieldorder_by[$fkey]   = $field["order_by"];
            
$fieldglobal[$fkey]     = $field["global"] == 1;
            
$fieldref[$fkey]        = $field["ref"];
            }
        if(
$ord_by)
            {
            
array_multisort($fieldorder_bySORT_ASC$fieldglobalSORT_ASC$fieldrefSORT_ASC$allresdata[$resourceid]);
            }
        else
            {
            
array_multisort($fieldglobalSORT_ASC$fieldorder_bySORT_ASC$fieldrefSORT_ASC$allresdata[$resourceid]);
            }
        }
    return 
$allresdata;
    }

This article was last updated 4th December 2024 09:05 Europe/London time based on the source file dated 28th November 2024 12:10 Europe/London time.