public function testInterstitialTemplateProcessing()
 {
     // should only be one
     $vn_relation_id = $this->opt_object_left->get('ca_objects_x_objects.relation_id');
     $this->assertTrue(is_numeric($vn_relation_id));
     $va_opts = array('resolveLinksUsing' => 'ca_objects', 'primaryIDs' => array('ca_objects' => array($this->opt_object_left->getPrimaryKey())));
     // we're reading from the left side, so the right side pop up
     $this->assertEquals('Test Dataset', caProcessTemplateForIDs('^ca_objects.preferred_labels', 'ca_objects_x_objects', array($vn_relation_id), $va_opts));
     $this->assertEquals('is related to', caProcessTemplateForIDs('^relationship_typename', 'ca_objects_x_objects', array($vn_relation_id), $va_opts));
     $this->assertEquals('is related to', caProcessTemplateForIDs('<unit relativeTo="ca_objects_x_objects">^relationship_typename</unit>', 'ca_objects', array($this->opt_object_left->getPrimaryKey()), $va_opts));
 }
 public function testInterstitialTemplateProcessing()
 {
     // should only be one
     $vn_relation_id = $this->opt_homer->get('ca_entities_x_entities.relation_id');
     $this->assertTrue(is_numeric($vn_relation_id));
     $va_opts = array('resolveLinksUsing' => 'ca_entities', 'primaryIDs' => array('ca_entities' => array($this->opt_bart->getPrimaryKey())));
     // we're reading from Bart, so Homer should pop up
     $this->assertEquals('Homer J. Simpson', caProcessTemplateForIDs('^ca_entities.preferred_labels', 'ca_entities_x_entities', array($vn_relation_id), $va_opts));
     // Try getting the rel type from the relationship record
     // We don't need $va_opts to do that, by the way!
     $this->assertEquals('is related to', caProcessTemplateForIDs('^relationship_typename', 'ca_entities_x_entities', array($vn_relation_id)));
     // Try getting the rel type from the Homer record
     // We don't need $va_opts to do that either
     $this->assertEquals('is related to', caProcessTemplateForIDs('<unit relativeTo="ca_entities_x_entities">^relationship_typename</unit>', 'ca_entities', array($this->opt_homer->getPrimaryKey())));
 }
 public function testGets()
 {
     $vm_ret = $this->opt_loan_in->get('ca_loans.related');
     $this->assertEquals('New Loan Out', $vm_ret);
     $va_items = $this->opt_loan_in->getRelatedItems('ca_loans');
     $vn_relation_id = array_shift(caExtractArrayValuesFromArrayOfArrays($va_items, 'relation_id'));
     // The relationship we created is Loan Out <-> Loan In, so evaluating with loan in as primary ID should give us the loan out
     $va_opts = array('resolveLinksUsing' => 'ca_loans', 'primaryIDs' => array('ca_loans' => array($this->opt_loan_in->getPrimaryKey())));
     $vm_ret = caProcessTemplateForIDs("^ca_loans.preferred_labels", 'ca_loans_x_loans', array($vn_relation_id), $va_opts);
     $this->assertEquals('New Loan Out', $vm_ret);
     // Now for the other side ...
     $va_opts = array('resolveLinksUsing' => 'ca_loans', 'primaryIDs' => array('ca_loans' => array($this->opt_loan_out->getPrimaryKey())));
     $vm_ret = caProcessTemplateForIDs("^ca_loans.preferred_labels", 'ca_loans_x_loans', array($vn_relation_id), $va_opts);
     $this->assertEquals('New Loan In', $vm_ret);
 }
 /**
  * 
  *
  * @param array Optional array of options. Support options are:
  *			template = 
  *			includeID = 
  *			idsOnly = 
  * @return string The value
  */
 public function getDisplayValue($pa_options = null)
 {
     $o_config = Configuration::load();
     if (is_array($va_lookup_template = $o_config->getList('ca_entities_lookup_settings'))) {
         $vs_default_template = join($o_config->get('ca_entities_lookup_delimiter'), $va_lookup_template);
     } else {
         $vs_default_template = "^ca_entities.preferred_labels.displayname";
     }
     $ps_template = (string) caGetOption('template', $pa_options, $vs_default_template);
     $vb_include_id = (bool) caGetOption('includeID', $pa_options, false);
     $vb_ids_only = (bool) caGetOption('idsOnly', $pa_options, false);
     if ($vb_ids_only) {
         return $this->opn_entity_id;
     }
     return caProcessTemplateForIDs($ps_template, 'ca_entities', array($this->opn_entity_id), array()) . ($vb_include_id ? " [" . $this->opn_entity_id . "]" : '');
 }
示例#5
0
 /**
  * 
  * 
  * @param string $ps_template 
  * @param array $pa_options Any options supported by BaseModel::getHierarchyAsList() and caProcessTemplateForIDs() as well as:
  *		sort = An array or semicolon delimited list of elements to sort on. [Default is null]
  * 		sortDirection = Direction to sorting, either 'asc' (ascending) or 'desc' (descending). [Default is asc]
  * @return array
  */
 public function hierarchyWithTemplate($ps_template, $pa_options = null)
 {
     if (!$this->isHierarchical()) {
         return null;
     }
     if (!is_array($pa_options)) {
         $pa_options = array();
     }
     $vs_pk = $this->primaryKey();
     $pn_id = caGetOption($vs_pk, $pa_options, null);
     $va_hier = $this->getHierarchyAsList($pn_id, array_merge($pa_options, array('idsOnly' => false)));
     $va_levels = $va_ids = $va_parent_ids = array();
     if (!is_array($va_hier)) {
         return array();
     }
     foreach ($va_hier as $vn_i => $va_item) {
         $va_levels[$vn_i] = $va_item['LEVEL'];
         $va_ids[$vn_i] = $vn_id = $va_item['NODE'][$vs_pk];
         $va_parent_ids[$vn_id] = $va_item['NODE']['parent_id'];
     }
     $va_hierarchy_data = array();
     $va_vals = caProcessTemplateForIDs($ps_template, $this->tableName(), $va_ids, array_merge($pa_options, array('includeBlankValuesInArray' => true, 'returnAsArray' => true)));
     $pa_sort = caGetOption('sort', $pa_options, null);
     if (!is_array($pa_sort) && $pa_sort) {
         $pa_sort = explode(";", $pa_sort);
     }
     $ps_sort_direction = strtolower(caGetOption('sortDirection', $pa_options, 'asc'));
     if (!in_array($ps_sort_direction, array('asc', 'desc'))) {
         $ps_sort_direction = 'asc';
     }
     if (is_array($pa_sort) && sizeof($pa_sort) && sizeof($va_ids)) {
         $va_sort_keys = array();
         $qr_sort_res = caMakeSearchResult($this->tableName(), $va_ids);
         $vn_i = 0;
         while ($qr_sort_res->nextHit()) {
             $va_key = array();
             foreach ($pa_sort as $vs_sort) {
                 $va_key[] = $qr_sort_res->get($vs_sort);
             }
             $va_sort_keys[$vn_i] = join("_", $va_key) . "_{$vn_i}";
             $vn_i++;
         }
         foreach ($va_vals as $vn_i => $vs_val) {
             $va_hierarchy_data[$va_parent_ids[$va_ids[$vn_i]]][$va_sort_keys[$vn_i]] = array('level' => $va_levels[$vn_i], 'id' => $va_ids[$vn_i], 'parent_id' => $va_parent_ids[$va_ids[$vn_i]], 'display' => $vs_val);
         }
         $va_hierarchy_flattened = array();
         foreach ($va_hierarchy_data as $vn_parent_id => $va_level_content) {
             ksort($va_hierarchy_data[$vn_parent_id]);
         }
         return $this->_getFlattenedHierarchyArray($va_hierarchy_data, $va_parent_ids[$pn_id] ? $va_parent_ids[$pn_id] : null, $ps_sort_direction);
     } else {
         foreach ($va_vals as $vn_i => $vs_val) {
             $va_hierarchy_data[] = array('level' => $va_levels[$vn_i], 'id' => $va_ids[$vn_i], 'display' => $vs_val);
         }
     }
     return $va_hierarchy_data;
 }
示例#6
0
function caProcessRelationshipLookupLabel($qr_rel_items, $pt_rel, $pa_options = null)
{
    global $ca_relationship_lookup_parse_cache;
    $va_initial_values = array();
    $vb_is_hierarchical = $pt_rel->isHierarchical();
    $vs_hier_parent_id_fld = $pt_rel->getProperty('HIERARCHY_PARENT_ID_FLD');
    $vs_hier_fld = $pt_rel->getProperty('HIERARCHY_ID_FLD');
    $vs_idno_fld = $pt_rel->getProperty('ID_NUMBERING_ID_FIELD');
    $vs_idno_sort_fld = $pt_rel->getProperty('ID_NUMBERING_SORT_FIELD');
    $vs_rel_pk = caGetOption('primaryKey', $pa_options, $pt_rel->primaryKey());
    $vs_rel_table = caGetOption('table', $pa_options, $pt_rel->tableName());
    if (!isset($pa_options['config']) || !is_object($pa_options['config'])) {
        $o_config = Configuration::load();
    } else {
        $o_config = $pa_options['config'];
    }
    $pn_limit = caGetOption('limit', $pa_options, null);
    $ps_inline_create_message = caGetOption('inlineCreateMessage', $pa_options, null);
    $ps_inline_create_does_not_exist_message = caGetOption('inlineCreateMessageDoesNotExist', $pa_options, null);
    $ps_inline_create_query = caGetOption('inlineCreateQuery', $pa_options, null);
    $ps_inline_create_query_lc = mb_strtolower($ps_inline_create_query);
    $ps_empty_result_message = caGetOption('emptyResultMessage', $pa_options, null);
    $ps_empty_result_query = caGetOption('emptyResultQuery', $pa_options, null);
    $vs_template = caGetOption('template', $pa_options, null);
    $vs_cache_key = md5($vs_template);
    $va_exclude = caGetOption('exclude', $pa_options, array(), array('castTo' => 'array'));
    //
    // Originally the lookup display setting was a string with embedded tokens prefixed with carets. We still have to support this
    // in case someone is using an old config file, but the preferred configuration format is now to pass an array of bundles (still prefixed
    // with a caret because the bundles may have HTML formatting around them) and a separate delimiter. We then join all non-blank values together
    //
    $vb_use_new_display_format = false;
    $va_bundles = array();
    $vs_display_delimiter = '';
    if (isset($ca_relationship_lookup_parse_cache[$vs_rel_table][$vs_cache_key])) {
        $va_bundles = $ca_relationship_lookup_parse_cache[$vs_rel_table][$vs_cache_key]['bundles'];
        $va_display_format = $ca_relationship_lookup_parse_cache[$vs_rel_table][$vs_cache_key]['display_format'];
        $vs_display_delimiter = $ca_relationship_lookup_parse_cache[$vs_rel_table][$vs_cache_key]['delimiter'];
        $vb_use_new_display_format = true;
    } else {
        if (($vs_display_format = $o_config->get("{$vs_rel_table}_lookup_settings")) && !is_array($vs_display_format)) {
            if ($vs_display_format && is_string($vs_display_format) && !preg_match_all('!\\^{1}([A-Za-z0-9\\._]+)!', $vs_display_format, $va_matches)) {
                $vs_display_format = '^' . $vs_rel_table . '.preferred_labels';
                $va_bundles = array($vs_rel_table . '.preferred_labels');
            } else {
                $va_bundles = $va_matches[1];
            }
        } else {
            if (is_array($va_display_format = $o_config->getList("{$vs_rel_table}_lookup_settings"))) {
                $vb_use_new_display_format = true;
                if (!($vs_display_delimiter = $o_config->get("{$vs_rel_table}_lookup_delimiter"))) {
                    $vs_display_delimiter = ' ';
                } else {
                    $vs_display_delimiter = " {$vs_display_delimiter} ";
                }
                foreach ($va_display_format as $vs_display_element) {
                    if (preg_match_all('!\\^{1}([A-Za-z0-9\\._]+)!', $vs_display_element, $va_matches)) {
                        $va_bundles = array_merge($va_bundles, $va_matches[1]);
                    }
                }
            }
        }
        $ca_relationship_lookup_parse_cache[$vs_rel_table][$vs_cache_key] = array('bundles' => $va_bundles, 'display_format' => $va_display_format, 'delimiter' => $vs_display_delimiter);
    }
    $va_related_item_info = $va_parent_ids = $va_hierarchy_ids = array();
    $va_items = array();
    $o_dm = Datamodel::load();
    $t_rel = $o_dm->getInstanceByTableName($vs_rel_table, true);
    $vs_type_id_fld = method_exists($t_rel, 'getTypeFieldName') ? $t_rel->getTypeFieldName() : null;
    $vn_c = 0;
    $vb_include_inline_add_does_not_exist_message = $vb_include_empty_result_message = false;
    $vb_include_inline_add_message = true;
    if (is_object($qr_rel_items)) {
        if (!$qr_rel_items->numHits()) {
            if ($ps_inline_create_message) {
                $vb_include_inline_add_does_not_exist_message = true;
            } else {
                if ($ps_empty_result_message) {
                    $vb_include_empty_result_message = true;
                }
            }
        } else {
            $vs_table = $qr_rel_items->tableName();
            $vs_pk = $qr_rel_items->primaryKey();
            $va_primary_ids = method_exists($pt_rel, "isSelfRelationship") && ($vb_is_self_rel = $pt_rel->isSelfRelationship()) ? caGetOption("primaryIDs", $pa_options, null) : null;
            while ($qr_rel_items->nextHit()) {
                $vn_id = $qr_rel_items->get("{$vs_rel_table}.{$vs_rel_pk}");
                if (in_array($vn_id, $va_exclude)) {
                    continue;
                }
                $va_item = array('id' => $vn_id, $vs_rel_pk => $vn_id);
                if ($vs_type_id_fld) {
                    $va_item['type_id'] = $qr_rel_items->get("{$vs_rel_table}.{$vs_type_id_fld}");
                }
                if ($vb_use_new_display_format) {
                    $va_display_value = $va_display_format;
                } else {
                    $vs_display_value = $vs_display_format;
                }
                foreach ($va_bundles as $vs_bundle_name) {
                    if (in_array($vs_bundle_name, array('_parent', '_hierarchy'))) {
                        continue;
                    }
                    if (!($vs_value = trim($qr_rel_items->get($vs_bundle_name, array('delimiter' => $vs_display_delimiter, 'convertCodesToDisplayText' => true))))) {
                        if ((!isset($pa_options['stripTags']) || !$pa_options['stripTags']) && sizeof($va_tmp = explode('.', $vs_bundle_name)) == 3) {
                            // is tag media?
                            $vs_value = trim($qr_rel_items->getMediaTag($va_tmp[0] . '.' . $va_tmp[1], $va_tmp[2]));
                        }
                    }
                    if ($vb_use_new_display_format) {
                        foreach ($va_display_value as $vn_x => $vs_display_element) {
                            $va_display_value[$vn_x] = str_replace("^{$vs_bundle_name}", $vs_value, $vs_display_element);
                        }
                    } else {
                        if ($vs_display_format) {
                            $vs_display_value = str_replace("^{$vs_bundle_name}", htmlspecialchars($vs_value), $vs_display_value);
                        } else {
                            $vs_display_value .= $vs_value . ' ';
                        }
                    }
                }
                if ($t_rel->isHierarchical()) {
                    if ($vn_parent_id = $qr_rel_items->get("{$vs_rel_table}.{$vs_hier_parent_id_fld}")) {
                        $va_parent_ids[$vn_id] = $vn_parent_id;
                    } else {
                        if ($pt_rel->getHierarchyType() != __CA_HIER_TYPE_ADHOC_MONO__) {
                            // don't show root for hierarchies unless it's adhoc (where the root is a valid record)
                            continue;
                        }
                    }
                    if ($vs_hier_fld) {
                        $va_hierarchy_ids[$vn_id] = $qr_rel_items->get("{$vs_rel_table}.{$vs_hier_fld}");
                    }
                }
                if ($vs_rel_table == 'ca_users') {
                    $va_item['fname'] = $qr_rel_items->get('ca_users.fname');
                    $va_item['lname'] = $qr_rel_items->get('ca_users.lname');
                    $va_item['email'] = $qr_rel_items->get('ca_users.email');
                }
                if ($vb_use_new_display_format) {
                    $va_related_item_info[$vn_id] = $va_display_value;
                } else {
                    $va_related_item_info[$vn_id] = $vs_display_value;
                }
                if ($vs_template) {
                    $va_item['_display'] = caProcessTemplateForIDs($vs_template, $vs_table, array($qr_rel_items->get("{$vs_table}.{$vs_pk}")), array('returnAsArray' => false, 'returnAsLink' => true, 'delimiter' => caGetOption('delimiter', $pa_options, $vs_display_delimiter), 'resolveLinksUsing' => $vs_rel_table, 'primaryIDs' => $va_primary_ids));
                }
                $va_item['_l'] = mb_strtolower($qr_rel_items->get("{$vs_table}.preferred_labels"));
                $va_items[$vn_id] = $va_item;
                $vn_c++;
                if ($pn_limit && $pn_limit <= $vn_c) {
                    break;
                }
            }
        }
    }
    $va_hierarchies = method_exists($t_rel, "getHierarchyList") ? $t_rel->getHierarchyList() : array();
    // Get root entries for hierarchies and remove from labels (we don't want to show the root labels – they are not meant for display)
    if (is_array($va_hierarchies)) {
        foreach ($va_hierarchies as $vn_root_id => $va_hier_info) {
            foreach ($va_parent_ids as $vn_item_id => $vn_parent_id) {
                if ($vn_parent_id == $va_hier_info[$vs_rel_pk]) {
                    unset($va_parent_ids[$vn_item_id]);
                }
            }
        }
    }
    if (method_exists($t_rel, "getPreferredDisplayLabelsForIDs")) {
        $va_parent_labels = $t_rel->getPreferredDisplayLabelsForIDs($va_parent_ids);
    } else {
        $va_parent_labels = array();
    }
    if (isset($pa_options['relatedItems']) && is_array($pa_options['relatedItems']) && sizeof($pa_options['relatedItems'])) {
        $va_tmp = array();
        foreach ($pa_options['relatedItems'] as $vn_relation_id => $va_relation) {
            $va_items[$va_relation[$vs_rel_pk]]['relation_id'] = $va_relation['relation_id'];
            $va_items[$va_relation[$vs_rel_pk]]['relationship_type_id'] = $va_items[$va_relation[$vs_rel_pk]]['type_id'] = $va_relation['direction'] ? $va_relation['direction'] . '_' . $va_relation['relationship_type_id'] : $va_relation['relationship_type_id'];
            $va_items[$va_relation[$vs_rel_pk]]['rel_type_id'] = $va_relation['relationship_type_id'];
            $va_items[$va_relation[$vs_rel_pk]]['relationship_typename'] = $va_relation['relationship_typename'];
            $va_items[$va_relation[$vs_rel_pk]]['idno'] = $va_relation[$vs_idno_fld];
            $va_items[$va_relation[$vs_rel_pk]]['idno_sort'] = $va_relation[$vs_idno_sort_fld];
            $va_items[$va_relation[$vs_rel_pk]]['label'] = $va_relation['label'];
            $va_items[$va_relation[$vs_rel_pk]]['direction'] = $va_relation['direction'];
            $va_items[$va_relation[$vs_rel_pk]]['effective_date'] = $va_relation['effective_date'];
            if (isset($va_relation['surname'])) {
                // pass forename and surname entity label fields to support proper sorting by name
                $va_items[$va_relation[$vs_rel_pk]]['surname'] = $va_relation['surname'];
                $va_items[$va_relation[$vs_rel_pk]]['forename'] = $va_relation['forename'];
            }
            if (!isset($va_items[$va_relation[$vs_rel_pk]][$vs_rel_pk]) || !$va_items[$va_relation[$vs_rel_pk]][$vs_rel_pk]) {
                $va_items[$va_relation[$vs_rel_pk]][$vs_rel_pk] = $va_items[$va_relation[$vs_rel_pk]]['id'] = $va_relation[$vs_rel_pk];
            }
            if ($vs_template) {
                $va_items[$va_relation[$vs_rel_pk]]['_display'] = caProcessTemplateForIDs($vs_template, $vs_rel_table, array($va_relation[$vs_rel_pk]), array('returnAsArray' => false, 'returnAsLink' => true, 'delimiter' => caGetOption('delimiter', $pa_options, $vs_display_delimiter), 'resolveLinksUsing' => $vs_rel_table));
            } else {
                $va_items[$va_relation[$vs_rel_pk]]['_display'] = $va_items[$va_relation[$vs_rel_pk]]['label'];
            }
            $va_tmp[$vn_relation_id] = $va_items[$va_relation[$vs_rel_pk]];
        }
        $va_items = $va_tmp;
        unset($va_tmp);
    }
    foreach ($va_items as $va_item) {
        $vn_id = $va_item[$vs_rel_pk];
        if (in_array($vn_id, $va_exclude)) {
            continue;
        }
        $va_tmp = $va_related_item_info;
        if ($vb_use_new_display_format) {
            $vs_parent = $va_parent_labels[$va_parent_ids[$vn_id]];
            $vs_hier = $va_hierarchies[$va_hierarchy_ids[$vn_id]]['name_plural'] ? $va_hierarchies[$va_hierarchy_ids[$vn_id]]['name_plural'] : $va_hierarchies[$va_hierarchy_ids[$vn_id]]['name'];
            if (is_array($va_related_item_info[$vn_id])) {
                foreach ($va_related_item_info[$vn_id] as $vn_x => $vs_display_value) {
                    $vs_display_value = str_replace("^_parent", $vs_parent, $vs_display_value);
                    $va_tmp[$vn_id][$vn_x] = str_replace("^_hierarchy", $vs_hier, $vs_display_value);
                    if (!strlen(trim($va_tmp[$vn_id][$vn_x]))) {
                        unset($va_tmp[$vn_id][$vn_x]);
                    }
                }
            }
            if (is_array($va_tmp[$vn_id])) {
                $va_tmp[$vn_id] = join($vs_display_delimiter, $va_tmp[$vn_id]);
            }
        } else {
            $va_tmp[$vn_id] = str_replace('^_parent', $va_parent_labels[$va_parent_ids[$vn_id]], $va_tmp[$vn_id]);
            $va_tmp[$vn_id] = str_replace('^_hierarchy', $va_hierarchies[$va_hierarchy_ids[$vn_id]]['name_plural'] ? $va_hierarchies[$va_hierarchy_ids[$vn_id]]['name_plural'] : $va_hierarchies[$va_hierarchy_ids[$vn_id]]['name'], $va_tmp[$vn_id]);
        }
        $vs_display = trim(preg_replace("![\n\r]+!", " ", $va_tmp[$vn_id]));
        if (isset($pa_options['stripTags']) && $pa_options['stripTags']) {
            if (preg_match('!(<[A-Za-z0-9]+[ ]+[A-Za-z0-9 ,;\\&\\-_]*>)!', $vs_display, $va_matches)) {
                // convert text in <> to non-tags if the text has only letters, numbers and spaces in it
                array_shift($va_matches);
                foreach ($va_matches as $vs_match) {
                    $vs_display = str_replace($vs_match, htmlspecialchars($vs_match), $vs_display);
                }
            }
            $vs_display = trim(strip_tags($vs_display));
            $vs_label = $va_item['label'];
            if (preg_match('!(<[A-Za-z0-9]+[ ]+[A-Za-z0-9 ,;\\&\\-_]*>)!', $vs_label, $va_matches)) {
                // convert text in <> to non-tags if the text has only letters, numbers and spaces in it
                array_shift($va_matches);
                foreach ($va_matches as $vs_match) {
                    $vs_label = str_replace($vs_match, htmlspecialchars($vs_match), $vs_label);
                }
            }
            $va_item['label'] = trim(strip_tags($vs_label));
        }
        $vs_display_lc = mb_strtolower($vs_display);
        if ($vs_display_lc == $ps_inline_create_query_lc || isset($va_item['_l']) && $va_item['_l'] == $ps_inline_create_query_lc) {
            $vb_include_inline_add_message = false;
        }
        unset($va_item['_l']);
        $po_request = caGetOption('request', $pa_options);
        if ($po_request && ca_editor_uis::loadDefaultUI($pt_rel->tableName(), $po_request, $va_item['rel_type_id'])) {
            $va_item['hasInterstitialUI'] = true;
        } else {
            $va_item['hasInterstitialUI'] = false;
        }
        $va_initial_values[$va_item['relation_id'] ? (int) $va_item['relation_id'] : $va_item[$vs_rel_pk]] = array_merge($va_item, array('label' => $vs_display));
    }
    if ($vb_include_inline_add_message && $ps_inline_create_message) {
        array_push($va_initial_values, array('label' => $ps_inline_create_message, 'id' => 0, $vs_rel_pk => 0, '_query' => $ps_inline_create_query));
    } elseif ($vb_include_inline_add_does_not_exist_message && $ps_inline_create_does_not_exist_message) {
        array_push($va_initial_values, array('label' => $ps_inline_create_does_not_exist_message, 'id' => 0, $vs_rel_pk => 0, '_query' => $ps_inline_create_query));
    } elseif ($vb_include_empty_result_message) {
        array_push($va_initial_values, array('label' => $ps_empty_result_message, 'id' => -1, $vs_rel_pk => -1, '_query' => $ps_empty_result_query));
    }
    return $va_initial_values;
}
 /**
  *
  *
  * @param $ps_field -
  * @param $pa_options -
  *		returnAsArray - 
  * 		delimiter -
  *		template -
  *		locale -
  *		returnAllLocales - Returns requested value in all locales for which it is defined. Default is false. Note that this is not supported for hierarchy specifications (eg. ca_objects.hierarchy).
  *		direction - For hierarchy specifications (eg. ca_objects.hierarchy) this determines the order in which the hierarchy is returned. ASC will return the hierarchy root first while DESC will return it with the lowest node first. Default is ASC.
  *		top - For hierarchy specifications (eg. ca_objects.hierarchy) this option, if set, will limit the returned hierarchy to the first X nodes from the root down. Default is to not limit.
  *		bottom - For hierarchy specifications (eg. ca_objects.hierarchy) this option, if set, will limit the returned hierarchy to the first X nodes from the lowest node up. Default is to not limit.
  * 		hierarchicalDelimiter - Text to place between items in a hierarchy for a hierarchical specification (eg. ca_objects.hierarchy) when returning as a string
  *		removeFirstItems - If set to a non-zero value, the specified number of items at the top of the hierarchy will be omitted. For example, if set to 2, the root and first child of the hierarchy will be omitted. Default is zero (don't delete anything).
  *		checkAccess = array of access values to filter results by; if defined only items with the specified access code(s) are returned. Only supported for <table_name>.hierarchy.preferred_labels and <table_name>.children.preferred_labels because these returns sets of items. For <table_name>.parent.preferred_labels, which returns a single row at most, you should do access checking yourself. (Everything here applies equally to nonpreferred_labels)
  *		sort = optional bundles to sort returned values on. Only supported for <table_name>.children.preferred_labels. The bundle specifiers are fields with or without tablename.
  *		sort_direction = direction to sort results by, either 'asc' for ascending order or 'desc' for descending order; default is 'asc'
  *		convertCodesToDisplayText = if true then non-preferred label type_ids are automatically converted to display text in the current locale; default is false (return non-preferred label type_id raw)
  */
 public function get($ps_field, $pa_options = null)
 {
     $vs_template = isset($pa_options['template']) ? $pa_options['template'] : null;
     $vb_return_as_array = isset($pa_options['returnAsArray']) ? (bool) $pa_options['returnAsArray'] : false;
     $vb_return_all_locales = isset($pa_options['returnAllLocales']) ? (bool) $pa_options['returnAllLocales'] : false;
     $vs_delimiter = isset($pa_options['delimiter']) ? $pa_options['delimiter'] : ' ';
     $vb_convert_codes_to_display_text = isset($pa_options['convertCodesToDisplayText']) ? (bool) $pa_options['convertCodesToDisplayText'] : false;
     if ($vb_return_all_locales && !$vb_return_as_array) {
         $vb_return_as_array = true;
     }
     // if desired try to return values in a preferred language/locale
     $va_preferred_locales = null;
     if (isset($pa_options['locale']) && $pa_options['locale']) {
         $va_preferred_locales = array($pa_options['locale']);
     }
     // does get refer to an attribute?
     $va_tmp = explode('.', $ps_field);
     if ($va_tmp[1] == 'hierarchy' && sizeof($va_tmp) == 2) {
         $va_tmp[2] = 'preferred_labels';
         $ps_field = join('.', $va_tmp);
     }
     $t_label = $this->getLabelTableInstance();
     $t_instance = $this;
     if (sizeof($va_tmp) >= 3 && ($va_tmp[2] == 'preferred_labels' && (!$va_tmp[3] || $t_label->hasField($va_tmp[3]))) || $va_tmp[1] == 'hierarchy') {
         switch ($va_tmp[1]) {
             case 'parent':
                 if ($this->isHierarchical() && ($vn_parent_id = $this->get($this->getProperty('HIERARCHY_PARENT_ID_FLD')))) {
                     $t_instance = $this->getAppDatamodel()->getInstanceByTableNum($this->tableNum());
                     if (!$t_instance->load($vn_parent_id)) {
                         $t_instance = $this;
                     } else {
                         unset($va_tmp[1]);
                         $va_tmp = array_values($va_tmp);
                     }
                 }
                 break;
             case 'children':
                 if ($this->isHierarchical()) {
                     unset($va_tmp[1]);
                     // remove 'children' from field path
                     $va_tmp = array_values($va_tmp);
                     $vs_childless_path = join('.', $va_tmp);
                     $va_data = array();
                     $va_children_ids = $this->getHierarchyChildren(null, array('idsOnly' => true));
                     if (is_array($va_children_ids) && sizeof($va_children_ids)) {
                         $t_instance = $this->getAppDatamodel()->getInstanceByTableNum($this->tableNum());
                         $vb_check_access = is_array($pa_options['checkAccess']) && $t_instance->hasField('access');
                         $va_sort = isset($pa_options['sort']) ? $pa_options['sort'] : null;
                         if (!is_array($va_sort) && $va_sort) {
                             $va_sort = array($va_sort);
                         }
                         if (!is_array($va_sort)) {
                             $va_sort = array();
                         }
                         $vs_sort_direction = isset($pa_options['sort_direction']) && in_array(strtolower($pa_options['sort_direction']), array('asc', 'desc')) ? strtolower($pa_options['sort_direction']) : 'asc';
                         $qr_children = $this->makeSearchResult($this->tableName(), $va_children_ids);
                         $vs_table = $this->tableName();
                         while ($qr_children->nextHit()) {
                             if ($vb_check_access && !in_array($qr_children->get("{$vs_table}.access"), $pa_options['checkAccess'])) {
                                 continue;
                             }
                             $vs_sort_key = '';
                             foreach ($va_sort as $vs_sort) {
                                 $vs_sort_key .= $vs_sort ? $qr_children->get($vs_sort) : 0;
                             }
                             if (!is_array($va_data[$vs_sort_key])) {
                                 $va_data[$vs_sort_key] = array();
                             }
                             $va_data[$vs_sort_key] = array_merge($va_data[$vs_sort_key], $qr_children->get($vs_childless_path, array_merge($pa_options, array('returnAsArray' => true))));
                         }
                         ksort($va_data);
                         if ($vs_sort_direction && $vs_sort_direction == 'desc') {
                             $va_data = array_reverse($va_data);
                         }
                         $va_sorted_data = array();
                         foreach ($va_data as $vs_sort_key => $va_items) {
                             foreach ($va_items as $vs_k => $vs_v) {
                                 $va_sorted_data[] = $vs_v;
                             }
                         }
                         $va_data = $va_sorted_data;
                     }
                     if ($vb_return_as_array) {
                         return $va_data;
                     } else {
                         return join($vs_delimiter, $va_data);
                     }
                 }
                 break;
             case 'hierarchy':
                 $vs_direction = isset($pa_options['direction']) ? strtoupper($pa_options['direction']) : null;
                 if (!in_array($vs_direction, array('ASC', 'DESC'))) {
                     $vs_direction = 'ASC';
                 }
                 $vn_top = (int) isset($pa_options['top']) ? strtoupper($pa_options['top']) : 0;
                 if ($vn_top < 0) {
                     $vn_top = 0;
                 }
                 $vn_bottom = (int) isset($pa_options['bottom']) ? strtoupper($pa_options['bottom']) : 0;
                 if ($vn_bottom < 0) {
                     $vn_bottom = 0;
                 }
                 $vs_pk = $this->primaryKey();
                 $vs_label_table_name = $this->getLabelTableName();
                 $t_label_instance = $this->getLabelTableInstance();
                 if (!$vs_template && ($vs_display_field = $t_label_instance->hasField($va_tmp[2]) ? $t_label_instance->tableName() . "." . $va_tmp[2] : ($this->hasField($va_tmp[2]) ? $this->tableName() . "." . $va_tmp[2] : null))) {
                     $vs_template = "^{$vs_display_field}";
                 }
                 $vn_top_id = null;
                 if (!($va_ancestor_list = $this->getHierarchyAncestors(null, array('idsOnly' => true, 'includeSelf' => true)))) {
                     $va_ancestor_list = array();
                 }
                 // TODO: this should really be in a model subclass
                 if ($this->tableName() == 'ca_objects' && $this->getAppConfig()->get('ca_objects_x_collections_hierarchy_enabled') && ($vs_coll_rel_type = $this->getAppConfig()->get('ca_objects_x_collections_hierarchy_relationship_type'))) {
                     require_once __CA_MODELS_DIR__ . '/ca_objects.php';
                     if ($this->getPrimaryKey() == $vn_top_id) {
                         $t_object = $this;
                     } else {
                         $t_object = new ca_objects($vn_top_id);
                     }
                     if (is_array($va_collections = $t_object->getRelatedItems('ca_collections', array('restrictToRelationshipTypes' => $vs_coll_rel_type)))) {
                         require_once __CA_MODELS_DIR__ . '/ca_collections.php';
                         $t_collection = new ca_collections();
                         foreach ($va_collections as $vn_i => $va_collection) {
                             if ($va_collections_ancestor_list = $t_collection->getHierarchyAncestors($va_collection['collection_id'], array('idsOnly' => true, 'includeSelf' => true))) {
                                 $va_ancestor_list = array_merge($va_ancestor_list, $va_collections_ancestor_list);
                             }
                             break;
                             // for now only process first collection (no polyhierarchies)
                         }
                     }
                 }
                 // remove root and children if so desired
                 if (isset($pa_options['removeFirstItems']) && (int) $pa_options['removeFirstItems'] > 0) {
                     for ($vn_i = 0; $vn_i < (int) $pa_options['removeFirstItems']; $vn_i++) {
                         array_pop($va_ancestor_list);
                     }
                 }
                 if ($vs_display_field != $va_tmp[2]) {
                     if ($this->hasField($va_tmp[2])) {
                         $vs_display_field = $va_tmp[2];
                     }
                 }
                 $vb_check_access = is_array($pa_options['checkAccess']) && $this->hasField('access');
                 if ($vb_check_access) {
                     $va_access_values = $this->getFieldValuesForIDs($va_ancestor_list, array('access'));
                     $va_ancestor_list = array();
                     foreach ($va_access_values as $vn_ancestor_id => $vn_access_value) {
                         if (in_array($vn_access_value, $pa_options['checkAccess'])) {
                             $va_ancestor_list[] = $vn_ancestor_id;
                         }
                     }
                 }
                 if ($vs_template) {
                     $va_tmp = caProcessTemplateForIDs($vs_template, $this->tableName(), $va_ancestor_list, array('returnAsArray' => true));
                 } else {
                     $va_tmp = $this->getPreferredDisplayLabelsForIDs($va_ancestor_list, array('returnAsArray' => true, 'returnAllLocales' => $vb_return_all_locales));
                 }
                 if ($vn_top > 0) {
                     $va_tmp = array_slice($va_tmp, sizeof($va_tmp) - $vn_top, $vn_top, true);
                 } else {
                     if ($vn_bottom > 0) {
                         $va_tmp = array_slice($va_tmp, 0, $vn_bottom, true);
                     }
                 }
                 if ($vs_direction == 'ASC') {
                     $va_tmp = array_reverse($va_tmp, true);
                 }
                 if (caGetOption('returnAsLink', $pa_options, false)) {
                     $va_tmp = caCreateLinksFromText(array_values($va_tmp), $this->tableName(), array_keys($va_tmp));
                 }
                 if ($vb_return_as_array) {
                     return $va_tmp;
                 } else {
                     $vs_hier_delimiter = isset($pa_options['hierarchicalDelimiter']) ? $pa_options['hierarchicalDelimiter'] : $pa_options['delimiter'];
                     return join($vs_hier_delimiter, $va_tmp);
                 }
                 break;
         }
     }
     switch (sizeof($va_tmp)) {
         case 1:
             switch ($va_tmp[0]) {
                 # ---------------------------------------------
                 case 'preferred_labels':
                     if (!$vb_return_as_array) {
                         $va_labels = caExtractValuesByUserLocale($t_instance->getPreferredLabels(), null, $va_preferred_locales);
                         $vs_disp_field = $this->getLabelDisplayField();
                         $va_values = array();
                         foreach ($va_labels as $vn_row_id => $va_label_list) {
                             foreach ($va_label_list as $vn_i => $va_label) {
                                 if ($vs_template) {
                                     $va_values[] = caProcessTemplate($vs_template, $va_label, array('removePrefix' => 'preferred_labels.'));
                                 } else {
                                     $va_values[] = $va_label[$vs_disp_field];
                                 }
                             }
                         }
                         return join($vs_delimiter, $va_values);
                     } else {
                         $va_labels = $t_instance->getPreferredLabels(null, false);
                         if ($vb_return_all_locales) {
                             return $va_labels;
                         } else {
                             // Simplify array by getting rid of third level array which is unnecessary since
                             // there is only ever one preferred label for a locale
                             $va_labels = caExtractValuesByUserLocale($va_labels, null, $va_preferred_locales);
                             $va_processed_labels = array();
                             foreach ($va_labels as $vn_label_id => $va_label_list) {
                                 $va_processed_labels[$vn_label_id] = $va_label_list[0];
                             }
                             return $va_processed_labels;
                         }
                     }
                     break;
                     # ---------------------------------------------
                 # ---------------------------------------------
                 case 'nonpreferred_labels':
                     if (!$vb_return_as_array) {
                         $vs_disp_field = $this->getLabelDisplayField();
                         $va_labels = caExtractValuesByUserLocale($t_instance->getNonPreferredLabels(), null, $va_preferred_locales);
                         $t_list = new ca_lists();
                         if ($vb_convert_codes_to_display_text) {
                             $va_types = $t_list->getItemsForList($this->getLabelTableInstance()->getFieldInfo('type_id', 'LIST_CODE'), array('extractValuesByUserLocale' => true));
                         }
                         $va_values = array();
                         foreach ($va_labels as $vn_row_id => $va_label_list) {
                             foreach ($va_label_list as $vn_i => $va_label) {
                                 if ($vs_template) {
                                     $va_label_values = $va_label;
                                     $va_label_values['typename_singular'] = $va_types[$va_label['type_id']]['name_singular'];
                                     $va_label_values['typename_plural'] = $va_types[$va_label['type_id']]['name_plural'];
                                     if ($vb_convert_codes_to_display_text) {
                                         $va_label_values['type_id'] = $va_types[$va_label['type_id']]['name_singular'];
                                     }
                                     $va_values[] = caProcessTemplate($vs_template, $va_label_values, array('removePrefix' => 'nonpreferred_labels.'));
                                 } else {
                                     if ($vb_convert_codes_to_display_text && $vs_disp_field == 'type_id') {
                                         $va_values[] = $va_types[$va_label[$vs_disp_field]]['name_singular'];
                                     } else {
                                         $va_values[] = $va_label[$vs_disp_field];
                                     }
                                 }
                             }
                         }
                         return join($vs_delimiter, $va_values);
                         $va_labels = caExtractValuesByUserLocale($t_instance->getNonPreferredLabels(null, false));
                         $vs_disp_field = $this->getLabelDisplayField();
                         $va_processed_labels = array();
                         foreach ($va_labels as $vn_label_id => $va_label_list) {
                             foreach ($va_label_list as $vn_i => $va_label) {
                                 $va_processed_labels[] = $va_label[$vs_disp_field];
                             }
                         }
                         return join($vs_delimiter, $va_processed_labels);
                     } else {
                         $va_labels = $t_instance->getNonPreferredLabels(null, false);
                         if ($vb_return_all_locales) {
                             return $va_labels;
                         } else {
                             return caExtractValuesByUserLocale($va_labels, null, $va_preferred_locales);
                         }
                     }
                     break;
                     # ---------------------------------------------
             }
             break;
         case 2:
         case 3:
             if ($va_tmp[0] === $t_instance->tableName()) {
                 switch ($va_tmp[1]) {
                     # ---------------------------------------------
                     case 'preferred_labels':
                         if (!$vb_return_as_array) {
                             if (isset($va_tmp[2]) && $va_tmp[2]) {
                                 $vs_disp_field = $va_tmp[2];
                             } else {
                                 $vs_disp_field = $this->getLabelDisplayField();
                             }
                             $va_labels = caExtractValuesByUserLocale($t_instance->getPreferredLabels(), null, $va_preferred_locales);
                             $va_values = array();
                             foreach ($va_labels as $vn_row_id => $va_label_list) {
                                 foreach ($va_label_list as $vn_i => $va_label) {
                                     if ($vs_template) {
                                         $va_values[] = caProcessTemplate($vs_template, $va_label, array('removePrefix' => 'preferred_labels.'));
                                     } else {
                                         $va_values[] = $va_label[$vs_disp_field];
                                     }
                                 }
                             }
                             return join($vs_delimiter, $va_values);
                         } else {
                             $va_labels = $t_instance->getPreferredLabels(null, false);
                             if (!$vb_return_all_locales) {
                                 // Simplify array by getting rid of third level array which is unnecessary since
                                 // there is only ever one preferred label for a locale
                                 $va_labels = caExtractValuesByUserLocale($va_labels, null, $va_preferred_locales);
                                 $va_processed_labels = array();
                                 foreach ($va_labels as $vn_label_id => $va_label_list) {
                                     $va_processed_labels[$vn_label_id] = $va_label_list[0];
                                 }
                                 $va_labels = $va_processed_labels;
                             }
                             if (isset($va_tmp[2]) && $va_tmp[2]) {
                                 // specific field
                                 if ($vb_return_all_locales) {
                                     foreach ($va_labels as $vn_label_id => $va_labels_by_locale) {
                                         foreach ($va_labels_by_locale as $vn_locale_id => $va_label_list) {
                                             foreach ($va_label_list as $vn_i => $va_label) {
                                                 $va_labels[$vn_label_id][$vn_locale_id][$vn_i] = $va_label[$va_tmp[2]];
                                             }
                                         }
                                     }
                                 } else {
                                     // get specified field value
                                     foreach ($va_labels as $vn_label_id => $va_label_info) {
                                         $va_labels[$vn_label_id] = $va_label_info[$va_tmp[2]];
                                     }
                                 }
                             }
                             return $va_labels;
                         }
                         break;
                         # ---------------------------------------------
                     # ---------------------------------------------
                     case 'nonpreferred_labels':
                         if (!$vb_return_as_array) {
                             if (isset($va_tmp[2]) && $va_tmp[2]) {
                                 $vs_disp_field = $va_tmp[2];
                             } else {
                                 $vs_disp_field = $this->getLabelDisplayField();
                             }
                             $va_labels = caExtractValuesByUserLocale($t_instance->getNonPreferredLabels(), null, $va_preferred_locales);
                             $t_list = new ca_lists();
                             if ($vb_convert_codes_to_display_text) {
                                 $va_types = $t_list->getItemsForList($this->getLabelTableInstance()->getFieldInfo('type_id', 'LIST_CODE'), array('extractValuesByUserLocale' => true));
                             }
                             $va_values = array();
                             foreach ($va_labels as $vn_row_id => $va_label_list) {
                                 foreach ($va_label_list as $vn_i => $va_label) {
                                     if ($vs_template) {
                                         $va_label_values = $va_label;
                                         $va_label_values['typename_singular'] = $va_types[$va_label['type_id']]['name_singular'];
                                         $va_label_values['typename_plural'] = $va_types[$va_label['type_id']]['name_plural'];
                                         if ($vb_convert_codes_to_display_text) {
                                             $va_label_values['type_id'] = $va_types[$va_label['type_id']]['name_singular'];
                                         }
                                         $va_values[] = caProcessTemplate($vs_template, $va_label_values, array('removePrefix' => 'nonpreferred_labels.'));
                                     } else {
                                         if ($vb_convert_codes_to_display_text && $vs_disp_field == 'type_id') {
                                             $va_values[] = $va_types[$va_label[$vs_disp_field]]['name_singular'];
                                         } else {
                                             $va_values[] = $va_label[$vs_disp_field];
                                         }
                                     }
                                 }
                             }
                             return join($vs_delimiter, $va_values);
                         } else {
                             $va_labels = $t_instance->getNonPreferredLabels(null, false);
                             if (!$vb_return_all_locales) {
                                 $va_labels = caExtractValuesByUserLocale($va_labels, null, $va_preferred_locales);
                             }
                             if (isset($va_tmp[2]) && $va_tmp[2]) {
                                 // specific field
                                 if ($vb_return_all_locales) {
                                     foreach ($va_labels as $vn_label_id => $va_labels_by_locale) {
                                         foreach ($va_labels_by_locale as $vn_locale_id => $va_label_list) {
                                             foreach ($va_label_list as $vn_i => $va_label) {
                                                 $va_labels[$vn_label_id][$vn_locale_id][$vn_i] = $va_label[$va_tmp[2]];
                                             }
                                         }
                                     }
                                 } else {
                                     // get specified field value
                                     foreach ($va_labels as $vn_label_id => $va_label_info) {
                                         foreach ($va_label_info as $vn_id => $va_label) {
                                             $va_labels[$vn_label_id] = $va_label[$va_tmp[2]];
                                         }
                                     }
                                 }
                             }
                             return $va_labels;
                         }
                         break;
                         # ---------------------------------------------
                 }
             }
             break;
     }
     return parent::get($ps_field, $pa_options);
 }
 /**
  * 
  *
  * @param array Optional array of options. Support options are:
  *			template = 
  *			includeID = 
  *			idsOnly = 
  * @return string The value
  */
 public function getDisplayValue($pa_options = null)
 {
     if (!is_array($pa_options)) {
         $pa_options = array();
     }
     $o_config = Configuration::load();
     if (is_array($va_lookup_template = $o_config->getList($this->ops_table_name . '_lookup_settings'))) {
         $vs_default_template = join($o_config->get($this->ops_table_name . '_lookup_delimiter'), $va_lookup_template);
     } else {
         $vs_default_template = "^" . $this->ops_table_name . ".preferred_labels";
     }
     $ps_template = (string) caGetOption('template', $pa_options, $vs_default_template);
     $vb_include_id = (bool) caGetOption('includeID', $pa_options, false);
     $vb_ids_only = (bool) caGetOption('idsOnly', $pa_options, false);
     if ($vb_ids_only) {
         return $this->opn_id;
     }
     return $this->opn_id ? caProcessTemplateForIDs($ps_template, $this->ops_table_name, array($this->opn_id), array_merge($pa_options, array('returnAsArray' => false, 'returnAllLocales' => false))) . ($vb_include_id ? " [" . $this->opn_id . "]" : '') : "";
 }
示例#9
0
 /**
  * Return array containing information about all hierarchies, including their root_id's
  * For non-adhoc hierarchies such as places, this call returns the contents of the place_hierarchies list
  * with some extra information such as the # of top-level items in each hierarchy.
  *
  * For an ad-hoc hierarchy like that of an object, there is only ever one hierarchy to display - that of the current object.
  * So for adhoc hierarchies we just return a single entry corresponding to the root of the current object hierarchy
  */
 public function getHierarchyList($pb_dummy = false)
 {
     $vn_pk = $this->getPrimaryKey();
     $vs_template = $this->getAppConfig()->get('ca_objects_hierarchy_browser_display_settings');
     if (!$vn_pk) {
         $o_db = new Db();
         if (is_array($va_type_ids = caMergeTypeRestrictionLists($this, array())) && sizeof($va_type_ids)) {
             $qr_res = $o_db->query("\n\t\t\t\t\tSELECT o.object_id, count(*) c\n\t\t\t\t\tFROM ca_objects o\n\t\t\t\t\tINNER JOIN ca_objects AS p ON p.parent_id = o.object_id\n\t\t\t\t\tWHERE o.parent_id IS NULL AND o.type_id IN (?)\n\t\t\t\t\tGROUP BY o.object_id\n\t\t\t\t", array($va_type_ids));
         } else {
             $qr_res = $o_db->query("\n\t\t\t\t\tSELECT o.object_id, count(*) c\n\t\t\t\t\tFROM ca_objects o\n\t\t\t\t\tINNER JOIN ca_objects AS p ON p.parent_id = o.object_id\n\t\t\t\t\tWHERE o.parent_id IS NULL\n\t\t\t\t\tGROUP BY o.object_id\n\t\t\t\t");
         }
         $va_hiers = array();
         $va_object_ids = $qr_res->getAllFieldValues('object_id');
         $qr_res->seek(0);
         $va_labels = $this->getPreferredDisplayLabelsForIDs($va_object_ids);
         while ($qr_res->nextRow()) {
             $va_hiers[$vn_object_id = $qr_res->get('object_id')] = array('object_id' => $vn_object_id, 'item_id' => $vn_object_id, 'name' => caProcessTemplateForIDs($vs_template, 'ca_objects', array($vn_object_id)), 'hierarchy_id' => $vn_object_id, 'children' => (int) $qr_res->get('c'));
         }
         return $va_hiers;
     } else {
         // return specific object as root of hierarchy
         $vs_label = $this->getLabelForDisplay(false);
         $vs_hier_fld = $this->getProperty('HIERARCHY_ID_FLD');
         $vs_parent_fld = $this->getProperty('PARENT_ID_FLD');
         $vn_hier_id = $this->get($vs_hier_fld);
         if ($this->get($vs_parent_fld)) {
             // currently loaded row is not the root so get the root
             $va_ancestors = $this->getHierarchyAncestors();
             if (!is_array($va_ancestors) || sizeof($va_ancestors) == 0) {
                 return null;
             }
             $t_object = new ca_objects($va_ancestors[0]);
         } else {
             $t_object =& $this;
         }
         $va_children = $t_object->getHierarchyChildren(null, array('idsOnly' => true));
         $va_object_hierarchy_root = array($t_object->get($vs_hier_fld) => array('object_id' => $vn_pk, 'item_id' => $vn_pk, 'name' => $vs_name = caProcessTemplateForIDs($vs_template, 'ca_objects', array($vn_pk)), 'hierarchy_id' => $vn_hier_id, 'children' => sizeof($va_children)));
         return $va_object_hierarchy_root;
     }
 }
					</td>
<?php 
    print "<td style='width:5%;'>" . caEditorLink($this->request, caNavIcon($this->request, __CA_NAV_BUTTON_EDIT__), '', 'ca_objects', $vn_object_id, array(), array()) . "</td>";
    ?>
					<td style="padding-left: 5px; padding-right: 5px;">
						<?php 
    print $va_relation_id_map[$vn_object_id]['relationship_typename'];
    ?>
					</td>
<?php 
    foreach ($va_display_list as $vn_placement_id => $va_info) {
        print "<td><span class=\"read-more\">";
        // if there's a template, evaluate template against relationship
        if ($vs_template = $va_info['settings']['format']) {
            $va_opts = array_merge($va_info, array('resolveLinksUsing' => $vs_primary_table, 'primaryIDs' => array($vs_primary_table => array($vn_primary_id))));
            print caProcessTemplateForIDs($vs_template, $vs_rel_table, array($vn_relation_id), $va_opts);
        } else {
            print $t_display->getDisplayValue($vo_result, $vn_placement_id, array_merge(array('request' => $this->request), is_array($va_info['settings']) ? $va_info['settings'] : array()));
        }
        print "</span></td>";
    }
    ?>
	
				</tr>
<?php 
    $i++;
    $vn_item_count++;
}
?>
			</tbody>
<?php 
示例#11
0
 /**
  *
  *
  * @param array $pa_options Array of options:
  *		template =
  */
 public function getLocationHistory($pa_options = null)
 {
     $pn_object = caGetOption('object_id', $pa_options, null);
     if (!($vn_object_id = $pn_object_id > 0 ? $pn_object_id : $this->getPrimaryKey())) {
         return null;
     }
     $ps_display_template = caGetOption('template', $pa_options, '^ca_objects_x_storage_locations.relation_id');
     $va_current_date = caDateToHistoricTimestamps(_t('now'));
     $vn_current_date = $va_current_date['start'];
     //
     // Directly query the date field for performance
     //
     $o_db = $this->getDb();
     $qr_res = $o_db->query("\n \t\t\tSELECT csl.relation_id, csl.location_id, csl.object_id, csl.sdatetime, csl.edatetime\n \t\t\tFROM ca_objects_x_storage_locations csl\n \t\t\tINNER JOIN ca_storage_locations AS sl ON sl.location_id = csl.location_id\n \t\t\tWHERE\n \t\t\t\t(csl.object_id = ?) AND \n \t\t\t\t(sl.deleted = 0)\n \t\t\tORDER BY\n \t\t\t\t csl.sdatetime DESC, csl.relation_id DESC\n \t\t", array($vn_object_id));
     $va_relation_ids = $qr_res->getAllFieldValues('relation_id');
     $va_displays = caProcessTemplateForIDs($ps_display_template, 'ca_objects_x_storage_locations', $va_relation_ids, array('returnAsArray' => true));
     $qr_res->seek(0);
     $va_items = array();
     $vb_have_seen_the_present = false;
     while ($qr_res->nextRow()) {
         $va_row = $qr_res->getRow();
         $vn_relation_id = $va_row['relation_id'];
         if ($va_row['sdatetime'] > $vn_current_date) {
             $vs_status = 'FUTURE';
         } else {
             $vs_status = $vb_have_seen_the_present ? 'PAST' : 'PRESENT';
             $vb_have_seen_the_present = true;
         }
         $va_items[$vn_relation_id] = array('object_id' => $va_row['object_id'], 'location_id' => $va_row['location_id'], 'display' => array_shift($va_displays), 'status' => $vs_status);
     }
     return $va_items;
 }
 /**
  * Returns text of attributes in the user's currently selected locale, or else falls back to
  * whatever locale is available
  *
  * Supported options
  *	delimiter = text to use between attribute values; default is a single space
  *	convertLineBreaks = if true will convert line breaks to HTML <br/> tags for display in a web browser; default is false
  *	dontUseElementTemplate = By default any display template set in the metadata element is used if the $ps_template parameter is blank or null. Set this option to prevent the metadata element template from being used in any event. [Default is false]
  */
 public function getAttributesForDisplay($pm_element_code_or_id, $ps_template = null, $pa_options = null)
 {
     if (!($vn_row_id = $this->getPrimaryKey())) {
         if (!($vn_row_id = $pa_options['row_id'])) {
             return null;
         }
     }
     if (!$pm_element_code_or_id || !($t_element = $this->_getElementInstance($pm_element_code_or_id))) {
         return null;
     }
     if (!is_array($pa_options)) {
         $pa_options = array();
     }
     if (!isset($pa_options['convertCodesToDisplayText'])) {
         $pa_options['convertCodesToDisplayText'] = true;
     }
     $va_tmp = $this->getAttributeDisplayValues($pm_element_code_or_id, $vn_row_id, array_merge($pa_options, array('returnAllLocales' => false)));
     if (!$ps_template && ($vs_template_tmp = $t_element->getSetting('displayTemplate', true)) && !caGetOption('dontUseElementTemplate', $pa_options, false)) {
         // grab template from metadata element if none is passed in $ps_template
         $ps_template = $vs_template_tmp;
     }
     $vs_delimiter = $t_element->getSetting('displayDelimiter', true);
     if (isset($pa_options['delimiter'])) {
         $vs_delimiter = $pa_options['delimiter'];
     }
     if ($ps_template) {
         unset($pa_options['template']);
         return caProcessTemplateForIDs($ps_template, $this->tableNum(), array($vn_row_id), array_merge($pa_options, array('requireLinkTags' => true, 'placeholderPrefix' => $t_element->get('element_code'))));
     } else {
         // no template
         $va_attribute_list = array();
         foreach ($va_tmp as $vn_id => $va_value_list) {
             foreach ($va_value_list as $va_value) {
                 foreach ($va_value as $vs_element_code => $vs_value) {
                     if (strlen($vs_value)) {
                         $va_attribute_list[] = $vs_value;
                     }
                 }
             }
         }
         //Allow getAttributesForDisplay to return an array value (for "special" returns such as coordinates or raw dates)
         // if the value returns only a single value and it's an array. This is useful for getting "specials" via SearchResult::get()
         if (sizeof($va_attribute_list) === 1 && is_array($va_attribute_list[0])) {
             return $va_attribute_list[0];
         }
         $vs_text = join($vs_delimiter, $va_attribute_list);
         if (isset($pa_options['convertLineBreaks']) && $pa_options['convertLineBreaks']) {
             $vs_text = caConvertLineBreaks($vs_text);
         }
         return $vs_text;
     }
 }
示例#13
0
 /**
  * Generate SIMILE timeline output in specified format
  *
  * @param array $pa_viz_settings Array of visualization settings taken from visualization.conf
  * @param string $ps_format Specifies format to generate output in. Currently only 'HTML' is supported.
  * @param array $pa_options Array of options to use when rendering output. Supported options are:
  *		width =
  *		height =
  *		request = current request; required for generation of editor links
  */
 public function render($pa_viz_settings, $ps_format = 'HTML', $pa_options = null)
 {
     if (!($vo_data = $this->getData())) {
         return null;
     }
     $this->opn_num_items_rendered = 0;
     $po_request = isset($pa_options['request']) && $pa_options['request'] ? $pa_options['request'] : null;
     list($vs_width, $vs_height) = $this->_parseDimensions(caGetOption('width', $pa_options, 500), caGetOption('height', $pa_options, 500));
     $o_dm = Datamodel::load();
     // generate events
     $va_events = array();
     $va_sources = $pa_viz_settings['sources'];
     $vs_table = $vo_data->tableName();
     $vs_pk = $o_dm->getTablePrimaryKeyName($vs_table);
     $vs_first_date = $vn_first_date = null;
     $vs_last_date = $vn_last_date = null;
     $va_dates = array();
     while ($vo_data->nextHit()) {
         foreach ($va_sources as $vs_source_code => $va_source_info) {
             $vs_start = trim($vo_data->get($va_source_info['data'], array('start_as_iso8601' => true, 'dateFormat' => 'iso8601')));
             $vs_end = trim($vo_data->get($va_source_info['data'], array('end_as_iso8601' => true, 'dateFormat' => 'iso8601')));
             $vn_start = $vo_data->get($va_source_info['data'], array('startHistoricTimestamp' => true));
             $vn_end = $vo_data->get($va_source_info['data'], array('endHistoricTimestamp' => true));
             if ($vn_start < 0 || $vn_end < 0) {
                 continue;
             }
             // TODO: negative numbers mean "BC" which apparently cannot be plotted
             if ($vn_end >= 2000000) {
                 $va_iso = caGetISODates(_t("today"));
                 $vs_end = $va_iso['end'];
                 $va_historic = caDateToHistoricTimestamps(_t("today"));
                 $vn_end = $va_historic['end'];
             }
             if (!$vs_start || !$vs_end) {
                 continue;
             }
             if ($vs_start == _t('undated') || $vs_end == _t('undated')) {
                 continue;
             }
             if (is_null($vn_first_date) || $vn_first_date > $vn_start) {
                 $vn_first_date = $vn_start;
                 $vs_first_date = $vs_start;
             }
             if (is_null($vn_last_date) || $vn_last_date < $vn_end) {
                 $vn_last_date = $vn_end;
                 $vs_last_date = $vs_end;
             }
             $va_dates[] = $vs_start;
             $va_events[] = array('id' => $vs_table . '_' . ($vn_id = $vo_data->get("{$vs_table}.{$vs_pk}")), 'start' => $vs_start, 'end' => $vs_end, 'isDuration' => (int) $vn_start != (int) $vn_end ? true : false, 'title' => caProcessTemplateForIDs(strip_tags($va_source_info['display']['title_template']), $vs_table, array($vn_id)), 'description' => caProcessTemplateForIDs($va_source_info['display']['description_template'], $vs_table, array($vn_id)), 'link' => $po_request ? caEditorUrl($po_request, $vo_data->tableName(), $vn_id) : null, 'image' => $va_source_info['display']['image'] ? $vo_data->getWithTemplate($va_source_info['display']['image'], array('returnURL' => true)) : null, 'icon' => $va_source_info['display']['icon'] ? $vo_data->getWithTemplate($va_source_info['display']['icon'], array('returnURL' => true)) : null);
         }
     }
     $this->opn_num_items_rendered = sizeof($va_events);
     // Find median date - timeline will open there (as good a place as any, no?)
     $vs_default_date = $va_dates[floor((sizeof($va_dates) - 1) / 2)];
     // Derive scale for timeline bands
     $vn_span = $vn_last_date - $vn_first_date;
     if ($vn_span > 1000) {
         // millennia
         $vs_detail_band_scale = " Timeline.DateTime.CENTURY";
         $vs_overview_band_scale = " Timeline.DateTime.MILLENNIUM";
     } elseif ($vn_span > 100) {
         // centuries
         $vs_detail_band_scale = " Timeline.DateTime.DECADE";
         $vs_overview_band_scale = " Timeline.DateTime.CENTURY";
     } elseif ($vn_span > 10) {
         // decades
         $vs_detail_band_scale = " Timeline.DateTime.YEAR";
         $vs_overview_band_scale = " Timeline.DateTime.DECADE";
     } elseif ($vn_span > 1) {
         // years
         $vs_detail_band_scale = " Timeline.DateTime.MONTH";
         $vs_overview_band_scale = " Timeline.DateTime.YEAR";
     } elseif ($vn_span > 0.1) {
         // months
         $vs_detail_band_scale = " Timeline.DateTime.DAY";
         $vs_overview_band_scale = " Timeline.DateTime.MONTH";
     } else {
         // days
         $vs_detail_band_scale = " Timeline.DateTime.HOUR";
         $vs_overview_band_scale = " Timeline.DateTime.DAY";
     }
     $va_highlight_spans = array();
     $vs_highlight_span = '';
     if (isset($pa_options['highlightSpans']) && is_array($pa_options['highlightSpans'])) {
         foreach ($pa_options['highlightSpans'] as $vs_span_name => $va_span_info) {
             $va_range = caGetISODates($va_span_info['range']);
             $vs_span_color = isset($va_span_info['color']) && $va_span_info['color'] ? $va_span_info['color'] : '#FFC080';
             $vs_start_label = isset($va_span_info['startLabel']) && $va_span_info['startLabel'] ? $va_span_info['startLabel'] : '';
             $vs_end_label = isset($va_span_info['endLabel']) && $va_span_info['endLabel'] ? $va_span_info['endLabel'] : '';
             $vs_span_css_class = isset($va_span_info['class']) && $va_span_info['class'] ? $va_span_info['class'] : 't-highlight1';
             $va_highlight_spans[] = "new Timeline.SpanHighlightDecorator({\n\t\t\t\t\t\tdateTimeFormat: 'iso8601',\n                        startDate:  '" . $va_range['start'] . "',\n                        endDate:    '" . $va_range['end'] . "',\n                        color:      '{$vs_span_color}', \n                        opacity:    50,\n                        startLabel: '{$vs_start_label}', \n                        endLabel:   '{$vs_end_label}',\n                        cssClass: '{$vs_span_css_class}'\n                    })";
         }
         $vs_highlight_span = "caTimelineBands[0].decorators = [" . join(",\n", $va_highlight_spans) . "];";
     }
     $vs_buf = "\n\t<div id='caResultTimeline' style='width: {$vs_width}; height: {$vs_height}; border: 1px solid #aaa'></div>\n<script type='text/javascript'>\n\tvar caTimelineEventSource = new Timeline.DefaultEventSource();\n\tvar caTimelineEventJson = {\n\t\t\"dateTimeFormat\": \"iso8601\", \n\t\t\"events\" : " . json_encode($va_events) . "\n\t}; \n\tcaTimelineEventSource.loadJSON(caTimelineEventJson, '');\n\t\n\tvar theme = Timeline.ClassicTheme.create();\n\t\n\tvar caTimelineBands = [\n     Timeline.createBandInfo({\n\t\t\teventPainter:   Timeline.CompactEventPainter,\n\t\t\teventPainterParams: {\n\t\t\t\ticonLabelGap:     5,\n\t\t\t\tlabelRightMargin: 20,\n\n\t\t\t\ticonWidth:        72,\n\t\t\t\ticonHeight:       72,\n\n\t\t\t\tstackConcurrentPreciseInstantEvents: {\n\t\t\t\t\tlimit: 5,\n\t\t\t\t\tmoreMessageTemplate:    '%0 More',\n\t\t\t\t\ticon:                   null,\n\t\t\t\t\ticonWidth:              72,\n\t\t\t\t\ticonHeight:             72\n\t\t\t\t}\n\t\t\t},\n\t\t\teventSource:\t caTimelineEventSource,\n\t\t\tdate:\t\t\t'{$vs_default_date}',\n\t\t\twidth:          '85%', \n\t\t\tintervalUnit:  \t{$vs_detail_band_scale}, \n\t\t\tintervalPixels: 100,\n\t\t\ttheme: \t\t\ttheme\n\t}),\n     Timeline.createBandInfo({\n     \t eventSource:\t caTimelineEventSource,\n     \t date:\t\t\t'{$vs_default_date}',\n         width:          '10%', \n         intervalUnit:   {$vs_overview_band_scale}, \n         intervalPixels: 200,\n         layout: \t\t'overview',\n     \t theme: \t\t theme\n     })\n   ];\n\tcaTimelineBands[1].syncWith = 0;\n\tcaTimelineBands[1].highlight = true;\n\t\n\t{$vs_highlight_span}\n\t\n\tvar caTimeline = Timeline.create(document.getElementById('caResultTimeline'), caTimelineBands);\n</script>\t\n";
     return $vs_buf;
 }
示例#14
0
 /**
  * Return array containing information about all hierarchies, including their root_id's
  * For non-adhoc hierarchies such as places, this call returns the contents of the place_hierarchies list
  * with some extra information such as the # of top-level items in each hierarchy.
  *
  * For an ad-hoc hierarchy like that of an entity, there is only ever one hierarchy to display - that of the current entity.
  * So for adhoc hierarchies we just return a single entry corresponding to the root of the current entity hierarchy
  */
 public function getHierarchyList($pb_dummy = false)
 {
     $vn_pk = $this->getPrimaryKey();
     if (!$vn_pk) {
         return null;
     }
     // have to load a row first
     $vs_template = $this->getAppConfig()->get('ca_entities_hierarchy_browser_display_settings');
     $vs_label = $this->getLabelForDisplay(false);
     $vs_hier_fld = $this->getProperty('HIERARCHY_ID_FLD');
     $vs_parent_fld = $this->getProperty('PARENT_ID_FLD');
     $vn_hier_id = $this->get($vs_hier_fld);
     if ($this->get($vs_parent_fld)) {
         // currently loaded row is not the root so get the root
         $va_ancestors = $this->getHierarchyAncestors();
         if (!is_array($va_ancestors) || sizeof($va_ancestors) == 0) {
             return null;
         }
         $t_entity = new ca_entities($va_ancestors[0]);
     } else {
         $t_entity =& $this;
     }
     $va_children = $t_entity->getHierarchyChildren(null, array('idsOnly' => true));
     $va_entity_hierarchy_root = array($t_entity->get($vs_hier_fld) => array('entity_id' => $vn_pk, 'name' => $vs_name = caProcessTemplateForIDs($vs_template, 'ca_entities', array($vn_pk)), 'hierarchy_id' => $vn_hier_id, 'children' => sizeof($va_children)));
     return $va_entity_hierarchy_root;
 }
示例#15
0
 /**
  * Given a item_id (request parameter 'id') returns a list of direct children for use in the hierarchy browser
  * Returned data is JSON format
  */
 public function GetHierarchyLevel()
 {
     $ps_bundle = (string) $this->request->getParameter('bundle', pString);
     $pa_ids = explode(";", $ps_ids = $this->request->getParameter('id', pString));
     if (!sizeof($pa_ids)) {
         $pa_ids = array(null);
     }
     $t_item = $this->opo_item_instance;
     $vs_template = $t_item->getAppConfig()->get('ca_list_items_hierarchy_browser_display_settings');
     $va_lists = array();
     if ($ps_lists = $this->request->getParameter('lists', pString)) {
         $va_lists = explode(";", $ps_lists);
     }
     if (($vn_max_items_per_page = $this->request->getParameter('max', pInteger)) < 1 || $vn_max_items_per_page > 1000) {
         $vn_max_items_per_page = 100;
     }
     $va_level_data = array();
     foreach ($pa_ids as $pn_id) {
         $va_tmp = explode(":", $pn_id);
         $vn_id = $va_tmp[0];
         $vn_start = (int) $va_tmp[1];
         if ($vn_start < 0) {
             $vn_start = 0;
         }
         if (!$vn_id && method_exists($t_item, "getHierarchyList")) {
             if (!($pn_list_id = $this->request->getParameter('list_id', pInteger))) {
                 // no id so by default return list of available hierarchies
                 $va_list_items = $t_item->getHierarchyList();
                 if (sizeof($va_lists)) {
                     // filter out lists that weren't specified
                     foreach ($va_list_items as $vn_list_id => $va_list) {
                         if (!in_array($vn_list_id, $va_lists) && !in_array($va_list['list_code'], $va_lists)) {
                             unset($va_list_items[$vn_list_id]);
                         }
                     }
                 } else {
                     if ($this->request->getParameter('voc', pInteger)) {
                         // Only show vocabularies
                         foreach ($va_list_items as $vn_list_id => $va_list) {
                             if (!$va_list['use_as_vocabulary']) {
                                 unset($va_list_items[$vn_list_id]);
                             }
                         }
                     }
                 }
             }
         } else {
             if ($t_item->load($vn_id)) {
                 // id is the id of the parent for the level we're going to return
                 $t_list = new ca_lists($vn_list_id = $t_item->get('list_id'));
                 $vs_label_table_name = $this->opo_item_instance->getLabelTableName();
                 $vs_label_display_field_name = $this->opo_item_instance->getLabelDisplayField();
                 $va_list_items = $t_list->getItemsForList($vn_list_id, array('returnHierarchyLevels' => false, 'item_id' => $vn_id, 'extractValuesByUserLocale' => true, 'sort' => $t_list->get('sort_type'), 'directChildrenOnly' => true, 'limit' => $vn_max_items_per_page, 'start' => $vn_start));
                 // output
                 $va_display_values = caProcessTemplateForIDs($vs_template, 'ca_list_items', array_keys($va_list_items), array('requireLinkTags' => true, 'returnAsArray' => true));
                 $vn_c = 0;
                 foreach ($va_list_items as $vn_item_id => $va_item) {
                     unset($va_item['description']);
                     unset($va_item['icon']);
                     if (!$va_item[$vs_label_display_field_name]) {
                         $va_item[$vs_label_display_field_name] = $va_item['idno'];
                     }
                     if (!$va_item[$vs_label_display_field_name]) {
                         $va_item[$vs_label_display_field_name] = '???';
                     }
                     $va_item['name'] = $va_display_values[$vn_c];
                     if (!$va_item['name']) {
                         $va_item['name'] = '??? ' . $vn_item_id;
                     }
                     $va_item['table'] = 'ca_list_items';
                     // Child count is only valid if has_children is not null
                     $va_item['children'] = 0;
                     $va_list_items[$vn_item_id] = $va_item;
                     $vn_c++;
                 }
                 if (sizeof($va_list_items)) {
                     $o_db = new Db();
                     $qr_res = $o_db->query("\n\t\t\t\t\t\t\t\tSELECT count(*) c, parent_id\n\t\t\t\t\t\t\t\tFROM ca_list_items\n\t\t\t\t\t\t\t\tWHERE \n\t\t\t\t\t\t\t\t\tparent_id IN (" . join(",", array_keys($va_list_items)) . ") AND deleted = 0\n\t\t\t\t\t\t\t\tGROUP BY parent_id\n\t\t\t\t\t\t\t");
                     while ($qr_res->nextRow()) {
                         $va_list_items[$qr_res->get('parent_id')]['children'] = $qr_res->get('c');
                     }
                 }
             }
         }
         $va_list_items['_sortOrder'] = array_keys($va_list_items);
         $va_list_items['_primaryKey'] = $t_item->primaryKey();
         // pass the name of the primary key so the hierbrowser knows where to look for item_id's
         $va_list_items['_itemCount'] = $t_list ? $t_list->numItemsInList() : ($qr_res ? $qr_res->numRows() : 0);
         $va_level_data[$pn_id] = $va_list_items;
     }
     if (!$this->request->getParameter('init', pInteger)) {
         // only set remember "last viewed" if the load is done interactively
         // if the GetHierarchyLevel() call is part of the initialization of the hierarchy browser
         // then all levels are loaded, sometimes out-of-order; if we record these initialization loads
         // as the 'last viewed' we can end up losing the true 'last viewed' value
         //
         // ... so the hierbrowser passes an extra 'init' parameters set to 1 if the GetHierarchyLevel() call
         // is part of a browser initialization
         $this->request->session->setVar($this->ops_table_name . '_' . $ps_bundle . '_browse_last_id', $pn_id);
     }
     $this->view->setVar('dontShowSymbols', (bool) $this->request->getParameter('noSymbols', pString));
     $this->view->setVar('list_item_list', $va_level_data);
     return $this->render('list_item_hierarchy_level_json.php');
 }
 /**
  * Return array containing information about all hierarchies, including their root_id's
  * For non-adhoc hierarchies such as places, this call returns the contents of the place_hierarchies list
  * with some extra information such as the # of top-level items in each hierarchy.
  *
  * For an ad-hoc hierarchy like that of an collection, there is only ever one hierarchy to display - that of the current collection.
  * So for adhoc hierarchies we just return a single entry corresponding to the root of the current collection hierarchy
  */
 public function getHierarchyList($pb_dummy = false)
 {
     $vs_hier_fld = $this->getProperty('HIERARCHY_ID_FLD');
     $vs_parent_fld = $this->getProperty('HIERARCHY_PARENT_ID_FLD');
     if (!$vs_parent_fld) {
         return;
     }
     $o_dm = Datamodel::load();
     $vs_pk = $this->primaryKey();
     $vn_id = $this->getPrimaryKey();
     $vs_table = $this->tableName();
     $vs_template = $this->getAppConfig()->get($vs_table . '_hierarchy_browser_display_settings');
     $va_type_ids = caMergeTypeRestrictionLists($this, array());
     $va_source_ids = caMergeSourceRestrictionLists($this, array());
     $vs_type_fld = $this->getTypeFieldName();
     $vs_source_fld = $this->getSourceFieldName();
     if (!$vn_id) {
         $o_db = $this->getDb();
         $va_wheres = array("(o.{$vs_parent_fld} IS NULL)");
         $va_params = array();
         if (is_array($va_type_ids) && sizeof($va_type_ids)) {
             $va_params[] = $va_type_ids;
             $va_wheres[] = "(o.{$vs_type_fld} IN (?)" . ($this->getFieldInfo($vs_type_fld, 'IS_NULL') ? " OR o.{$vs_type_fld} IS NULL" : "") . ")";
         }
         if (is_array($va_source_ids) && sizeof($va_source_ids)) {
             $va_params[] = $va_source_ids;
             $va_wheres[] = "(o.{$vs_source_fld} IN (?))";
         }
         $qr_res = $o_db->query("\n\t\t\t\tSELECT o.{$vs_pk}, count(*) c\n\t\t\t\tFROM {$vs_table} o\n\t\t\t\tINNER JOIN {$vs_table} AS p ON p.{$vs_parent_fld} = o.{$vs_pk}\n\t\t\t\tWHERE " . join(" AND ", $va_wheres) . "\n\t\t\t\tGROUP BY o.{$vs_pk}\n\t\t\t", $va_params);
         $va_hiers = array();
         $va_ids = $qr_res->getAllFieldValues($vs_pk);
         $qr_res->seek(0);
         $va_labels = $this->getPreferredDisplayLabelsForIDs($va_ids);
         while ($qr_res->nextRow()) {
             $va_hiers[$vn_id = $qr_res->get($vs_pk)] = array('item_id' => $vn_id, $vs_pk => $vn_id, 'name' => caProcessTemplateForIDs($vs_template, $vs_table, array($vn_id)), 'hierarchy_id' => $vn_id, 'children' => (int) $qr_res->get('c'));
         }
         return $va_hiers;
     } else {
         // return specific collection as root of hierarchy
         $vs_label = $this->getLabelForDisplay(false);
         $vn_hier_id = $this->get($vs_hier_fld);
         if ($this->get($vs_parent_fld)) {
             // currently loaded row is not the root so get the root
             $va_ancestors = $this->getHierarchyAncestors();
             if (!is_array($va_ancestors) || sizeof($va_ancestors) == 0) {
                 return null;
             }
             $t_instance = $o_dm->getInstanceByTableName($va_ancestors[0], true);
         } else {
             $t_instance =& $this;
         }
         $va_children = $t_instance->getHierarchyChildren(null, array('idsOnly' => true));
         $va_hierarchy_root = array($t_instance->get($vs_hier_fld) => array('item_id' => $vn_id, $vs_pk => $vn_id, 'name' => caProcessTemplateForIDs($vs_template, $vs_table, array($vn_id)), 'hierarchy_id' => $vn_hier_id, 'children' => sizeof($va_children)));
         return $va_hierarchy_root;
     }
 }
示例#17
0
 /**
  * Return array containing information about all lists, including their root_id's
  */
 public function getHierarchyList($pb_vocabularies = false)
 {
     $t_list = new ca_lists();
     $va_hierarchies = caExtractValuesByUserLocale($t_list->getListOfLists());
     $vs_template = $this->getAppConfig()->get('ca_list_items_hierarchy_browser_display_settings');
     $o_db = $this->getDb();
     $va_hierarchy_ids = array();
     foreach ($va_hierarchies as $vn_list_id => $va_list_info) {
         $va_hierarchy_ids[] = intval($vn_list_id);
     }
     if (!sizeof($va_hierarchy_ids)) {
         return array();
     }
     // get root for each hierarchy
     $qr_res = $o_db->query("\n\t\t\tSELECT cli.item_id, cli.list_id, count(*) children\n\t\t\tFROM ca_list_items cli\n\t\t\tLEFT JOIN ca_list_items AS cli2 ON cli.item_id = cli2.parent_id\n\t\t\tINNER JOIN ca_lists AS l ON l.list_id = cli.list_id\n\t\t\tWHERE \n\t\t\t\tcli.parent_id IS NULL and cli.list_id IN (" . join(',', $va_hierarchy_ids) . ") " . ($pb_vocabularies ? " AND (l.use_as_vocabulary = 1)" : "") . "\n\t\t\tGROUP BY\n\t\t\t\tcli.item_id\n\t\t");
     $vs_template = $this->getAppConfig()->get('ca_list_hierarchy_browser_display_settings');
     while ($qr_res->nextRow()) {
         $vn_hierarchy_id = $qr_res->get('list_id');
         $va_hierarchies[$vn_hierarchy_id]['list_id'] = $qr_res->get('list_id');
         // when we need to edit the list
         $va_hierarchies[$vn_hierarchy_id]['item_id'] = $qr_res->get('item_id');
         $qr_children = $o_db->query("\n\t\t\t\tSELECT count(*) children\n\t\t\t\tFROM ca_list_items cli\n\t\t\t\tWHERE \n\t\t\t\t\tcli.parent_id = ?\n\t\t\t", (int) $qr_res->get('item_id'));
         $vn_children_count = 0;
         if ($qr_children->nextRow()) {
             $vn_children_count = $qr_children->get('children');
         }
         $va_hierarchies[$vn_hierarchy_id]['name'] = caProcessTemplateForIDs($vs_template, 'ca_lists', array($vn_hierarchy_id), array('requireLinkTags' => true));
         $va_hierarchies[$vn_hierarchy_id]['children'] = intval($vn_children_count);
         $va_hierarchies[$vn_hierarchy_id]['has_children'] = $vn_children_count > 0 ? 1 : 0;
     }
     // sort by label
     $va_hierarchies_indexed_by_label = array();
     foreach ($va_hierarchies as $vs_k => $va_v) {
         $va_hierarchies_indexed_by_label[$va_v['name']][$vs_k] = $va_v;
     }
     ksort($va_hierarchies_indexed_by_label);
     $va_sorted_hierarchies = array();
     foreach ($va_hierarchies_indexed_by_label as $vs_l => $va_v) {
         foreach ($va_v as $vs_k => $va_hier) {
             $va_sorted_hierarchies[$vs_k] = $va_hier;
         }
     }
     return $va_sorted_hierarchies;
 }
                print $vs_ref_table_name;
                ?>
" class="authorityReferenceListTab">	
<?php 
                print "<ul class='authorityReferenceList'>\n";
                if (!($vs_template = caGetOption("{$vs_ref_table_name}_displayTemplate", $va_settings, null))) {
                    if (is_array($vs_template = $t_instance->getAppConfig()->getList("{$vs_ref_table_name}_lookup_settings"))) {
                        $vs_template = join($t_instance->getAppConfig()->get("{$vs_ref_table_name}_lookup_delimiter"), $vs_template);
                    } elseif (!($vs_template = $t_instance->getAppConfig()->get("{$vs_ref_table_name}_lookup_settings"))) {
                        $vs_template = "<l>^{$vs_ref_table_name}.preferred_labels</l>";
                    }
                }
                if (strpos($vs_template, "<l>") === false) {
                    $vs_template = "<l>{$vs_template}</l>";
                }
                $va_items = caProcessTemplateForIDs($vs_template, $t_ref_instance->tableName(), array_keys($va_rows), array('returnAsArray' => true));
                $vn_c = 0;
                foreach ($va_items as $vs_item) {
                    if ($vn_c >= $vn_max_items) {
                        break;
                    }
                    print "<li class='authorityReferenceList'>{$vs_item}</li>\n";
                    $vn_c++;
                }
                if (sizeof($va_items) >= $vn_max_items && is_array($va_search_strings[$vs_ref_table_name])) {
                    print "<li>" . caSearchLink($this->request, _t('... and %1 more', sizeof($va_items) - $vn_max_items), '', $vs_ref_table_name, join(" OR ", $va_search_strings[$vs_ref_table_name])) . "</li>\n";
                }
                print "</ul>\n";
                ?>
				
				</div>
 /**
  *
  *
  */
 protected function GetHierarchyLevelData($pa_ids)
 {
     $vo_dm = Datamodel::load();
     $o_config = Configuration::load();
     $t_object = new ca_objects();
     $va_level_data = array();
     foreach ($pa_ids as $pn_id) {
         $va_params = $this->getItemIDComponents($pn_id);
         $vs_table = $va_params['table'];
         $vn_id = $va_params['id'];
         $vn_start = $va_params['start'];
         $vn_item_count = 0;
         $t_item = $vo_dm->getInstanceByTableName($vs_table, true);
         $vs_label_table_name = $t_item->getLabelTableName();
         $vs_label_display_field_name = $t_item->getLabelDisplayField();
         $vs_pk = $t_item->primaryKey();
         if ($vn_start < 0) {
             $vn_start = 0;
         }
         $va_items_for_locale = array();
         if (!$vn_id && method_exists($t_item, "getHierarchyList")) {
             $vn_id = $this->request->getParameter('root_item_id', pString);
             $va_params = $this->getItemIDComponents($vn_id);
             $vs_table = $va_params['table'];
             $vn_id = $va_params['id'];
             $vn_start = $va_params['start'];
             $t_item = $vo_dm->getInstanceByTableName($vs_table, true);
             $vs_label_table_name = $t_item->getLabelTableName();
             $vs_label_display_field_name = $t_item->getLabelDisplayField();
             $vs_pk = $t_item->primaryKey();
             $t_item->load($vn_id);
             $va_tmp = array($vs_pk => $vn_id = $t_item->get($vs_table . '.' . $vs_pk), 'item_id' => $vs_table . '-' . $vn_id, 'parent_id' => $t_item->get($vs_table . '.parent_id'), 'idno' => $t_item->get($vs_table . '.idno'), $vs_label_display_field_name => $t_item->get($vs_table . '.preferred_labels.' . $vs_label_display_field_name), 'locale_id' => $t_item->get($vs_table . '.' . 'locale_id'));
             if (!$va_tmp[$vs_label_display_field_name]) {
                 $va_tmp[$vs_label_display_field_name] = $va_tmp['idno'];
             }
             if (!$va_tmp[$vs_label_display_field_name]) {
                 $va_tmp[$vs_label_display_field_name] = '???';
             }
             if (!($vs_item_template = trim($o_config->get("{$vs_table}_hierarchy_browser_display_settings")))) {
                 $vs_item_template = "^{$vs_table}.preferred_labels.{$vs_label_display_field_name}";
             }
             $va_tmp['name'] = caProcessTemplateForIDs($vs_item_template, $vs_table, array($va_tmp[$vs_pk]));
             // Child count is only valid if has_children is not null
             $va_tmp['children'] = $t_item->get('has_children') ? (int) $t_item->get('child_count') : 1;
             // TODO: fix
             $va_items[$va_tmp[$vs_pk]][$va_tmp['locale_id']] = $va_tmp;
             $va_items_for_locale = caExtractValuesByUserLocale($va_items);
         } else {
             if ($t_item->load($vn_id)) {
                 // id is the id of the parent for the level we're going to return
                 $va_additional_wheres = array();
                 $t_label_instance = $t_item->getLabelTableInstance();
                 if ($t_label_instance && $t_label_instance->hasField('is_preferred')) {
                     $va_additional_wheres[] = "(({$vs_label_table_name}.is_preferred = 1) OR ({$vs_label_table_name}.is_preferred IS NULL))";
                 }
                 if (!is_array($va_sorts = $o_config->getList($vs_table . '_hierarchy_browser_sort_values')) || !sizeof($va_sorts)) {
                     $va_sorts = null;
                 }
                 foreach ($va_sorts as $vn_i => $vs_sort_fld) {
                     $va_tmp = explode(".", $vs_sort_fld);
                     if ($va_tmp[1] == 'preferred_labels') {
                         $va_tmp[0] = $vs_label_table_name;
                         if (!($va_tmp[1] = $va_tmp[2])) {
                             $va_tmp[1] = $vs_label_display_field_name;
                         }
                         unset($va_tmp[2]);
                         $va_sorts[$vn_i] = join(".", $va_tmp);
                     }
                 }
                 if (!in_array($vs_sort_dir = strtolower($o_config->get($vs_table . '_hierarchy_browser_sort_direction')), array('asc', 'desc'))) {
                     $vs_sort_dir = 'asc';
                 }
                 $qr_children = $t_item->getHierarchyChildrenAsQuery($t_item->getPrimaryKey(), array('additionalTableToJoin' => $vs_label_table_name, 'additionalTableJoinType' => 'LEFT', 'additionalTableSelectFields' => array($vs_label_display_field_name, 'locale_id'), 'additionalTableWheres' => $va_additional_wheres, 'returnChildCounts' => true, 'sort' => $va_sorts, 'sortDirection' => $vs_sort_dir));
                 $va_items = array();
                 if (!($vs_item_template = trim($o_config->get("{$vs_table}_hierarchy_browser_display_settings")))) {
                     $vs_item_template = "^{$vs_table}.preferred_labels.{$vs_label_display_field_name}";
                 }
                 $va_child_counts = array();
                 if (($vn_max_items_per_page = $this->request->getParameter('max', pInteger)) < 1 || $vn_max_items_per_page > 1000) {
                     $vn_max_items_per_page = null;
                 }
                 $vn_c = 0;
                 $vn_item_count = $qr_children->numRows();
                 $qr_children->seek($vn_start);
                 while ($qr_children->nextRow()) {
                     $va_tmp = array($vs_pk => $vn_id = $qr_children->get($vs_table . '.' . $vs_pk), 'item_id' => $vs_table . '-' . $vn_id, 'parent_id' => $qr_children->get($vs_table . '.parent_id'), 'idno' => $qr_children->get($vs_table . '.idno'), 'locale_id' => $qr_children->get($vs_table . '.' . 'locale_id'));
                     if (!$va_tmp[$vs_label_display_field_name]) {
                         $va_tmp[$vs_label_display_field_name] = $va_tmp['idno'];
                     }
                     if (!$va_tmp[$vs_label_display_field_name]) {
                         $va_tmp[$vs_label_display_field_name] = '???';
                     }
                     $va_tmp['name'] = caProcessTemplateForIDs($vs_item_template, $vs_table, array($va_tmp[$vs_pk]));
                     // Child count is only valid if has_children is not null
                     $va_tmp['children'] = $qr_children->get('has_children') ? (int) $qr_children->get('child_count') : 0;
                     if (is_array($va_sorts)) {
                         $vs_sort_acc = array();
                         foreach ($va_sorts as $vs_sort) {
                             $vs_sort_acc[] = $qr_children->get($vs_sort);
                         }
                         $va_tmp['sort'] = join(";", $vs_sort_acc);
                     }
                     $va_items[$va_tmp['item_id']][$va_tmp['locale_id']] = $va_tmp;
                     $vn_c++;
                     if (!is_null($vn_max_items_per_page) && $vn_c >= $vn_max_items_per_page) {
                         break;
                     }
                 }
                 if ($t_item->tableName() == 'ca_collections') {
                     $va_cross_table_items = $t_item->getRelatedItems('ca_objects');
                     $vn_item_count += sizeof($va_cross_table_items);
                     $va_ids = array();
                     foreach ($va_cross_table_items as $vn_x_item_id => $va_x_item) {
                         $va_items['ca_objects-' . $vn_x_item_id][$va_x_item['locale_id']] = $va_x_item;
                         //$va_x_item_extracted = caExtractValuesByUserLocale(array(0 => $va_x_item['labels']));
                         //$va_items[$va_x_item['object_id']][$va_x_item['locale_id']]['name'] = $va_x_item_extracted[0];
                         $va_items['ca_objects-' . $va_x_item['object_id']][$va_x_item['locale_id']]['item_id'] = 'ca_objects-' . $va_x_item['object_id'];
                         $va_items['ca_objects-' . $va_x_item['object_id']][$va_x_item['locale_id']]['parent_id'] = $vn_id;
                         unset($va_items['ca_objects-' . $vn_x_item_id][$va_x_item['locale_id']]['labels']);
                         $va_items['ca_objects-' . $va_x_item['object_id']][$va_x_item['locale_id']]['children'] = 0;
                         $va_ids[] = $va_x_item['object_id'];
                     }
                     if (!($vs_item_template = trim($o_config->get("ca_objects_hierarchy_browser_display_settings")))) {
                         $vs_item_template = "^ca_objects.preferred_labels.name";
                     }
                     if (sizeof($va_ids)) {
                         $va_child_counts = $t_object->getHierarchyChildCountsForIDs($va_ids);
                         $va_templates = caProcessTemplateForIDs($vs_item_template, 'ca_objects', $va_ids, array('returnAsArray' => true));
                         foreach ($va_child_counts as $vn_id => $vn_c) {
                             $va_items['ca_objects-' . $vn_id][$va_x_item['locale_id']]['children'] = $vn_c;
                         }
                         foreach ($va_ids as $vn_i => $vn_id) {
                             $va_items['ca_objects-' . $vn_id][$va_x_item['locale_id']]['name'] = $va_templates[$vn_i];
                         }
                     }
                 }
                 $va_items_for_locale = caExtractValuesByUserLocale($va_items);
                 $vs_rank_fld = $t_item->getProperty('RANK');
                 $va_sorted_items = array();
                 foreach ($va_items_for_locale as $vn_id => $va_node) {
                     $vs_key = preg_replace('![^A-Za-z0-9]!', '_', $va_node['name']);
                     if (isset($va_node['sort']) && $va_node['sort']) {
                         $va_sorted_items[$va_node['sort']][$vs_key] = $va_node;
                     } else {
                         if ($vs_rank_fld && ($vs_rank = (int) sprintf("%08d", $va_node[$vs_rank_fld]))) {
                             $va_sorted_items[$vs_rank][$vs_key] = $va_node;
                         } else {
                             $va_sorted_items[$vs_key][$vs_key] = $va_node;
                         }
                     }
                 }
                 ksort($va_sorted_items);
                 if ($vs_sort_dir == 'desc') {
                     $va_sorted_items = array_reverse($va_sorted_items);
                 }
                 $va_items_for_locale = array();
                 foreach ($va_sorted_items as $vs_k => $va_v) {
                     ksort($va_v);
                     if ($vs_sort_dir == 'desc') {
                         $va_v = array_reverse($va_v);
                     }
                     $va_items_for_locale = array_merge($va_items_for_locale, $va_v);
                 }
             }
         }
         $va_items_for_locale['_sortOrder'] = array_keys($va_items_for_locale);
         $va_items_for_locale['_primaryKey'] = $t_item->primaryKey();
         // pass the name of the primary key so the hierbrowser knows where to look for item_id's
         $va_items_for_locale['_itemCount'] = $vn_item_count;
         //$qr_children ? $qr_children->numRows() : 0;
         $va_level_data[$pn_id] = $va_items_for_locale;
     }
     return $va_level_data;
 }
示例#20
0
 /**
  * Returns information on items in current set
  *
  * @param array $pa_options Optional array of options. Supported options are:
  *			user_id = user_id of the current user; used to determine what may be shown
  *			thumbnailVersions = A list of of a media versions to return with each item. Only used if the set content type is ca_objects.
  *			thumbnailVersion = Same as 'thumbnailVersions' except it is a single value. (Maintained for compatibility with older code.)
  *			limit = Limits the total number of records to be returned
  *			checkAccess = An array of row-level access values to check set members for, often produced by the caGetUserAccessValues() helper. Set members with access values not in the list will be omitted. If this option is not set or left null no access checking is done.
  *			returnRowIdsOnly = If true a simple array of row_ids (keys of the set members) for members of the set is returned rather than full item-level info for each set member. IDs are keys in the returned array.
  *			returnItemIdsOnly = If true a simple array of item_ids (keys for the ca_set_items rows themselves) is returned rather than full item-level info for each set member.
  *			returnItemAttributes = A list of attribute element codes for the ca_set_item record to return values for.
  *			idsOnly = Return a simple numerically indexed array of row_ids
  * 			template =
  *
  * @return array An array of items. The format varies depending upon the options set. If returnRowIdsOnly or returnItemIdsOnly are set then the returned array is a 
  *			simple list of ids. The full return array is key'ed on ca_set_items.item_id and then on locale_id. The values are arrays with keys set to a number of fields including:
  *			set_id, item_id, row_id, rank, label_id, locale_id, caption (from the ca_set_items label), all instrinsic field content from the row_id, the display label of the row
  *			as 'set_item_label'. 
  *			If 'thumbnailVersion' is set then additional keys will be available for the selected media version:
  *				representation_tag, representation_url, representation_width and representation_height (the HTML tag, URL, pixel width and pixel height of the representation respectively)
  *			If 'thumbnailVersions' is set then additional keys will be available for the selected media versions:
  *				representation_tag_<version_name>, representation_url_<version_name>, representation_width_<version_name> and representation_height_<version_name> (the HTML tag, URL, pixel width and pixel height of the representation respectively)
  *			If 'returnItemAttributes' is set then there will be an additional key for each element_code prefixed with 'ca_attribute_' to ensure it doesn't conflict with any other key in the array.		
  *			
  */
 public function getItems($pa_options = null)
 {
     if (!($vn_set_id = $this->getPrimaryKey())) {
         return null;
     }
     if (!is_array($pa_options)) {
         $pa_options = array();
     }
     if ($pa_options['user_id'] && !$this->haveAccessToSet($pa_options['user_id'], __CA_SET_READ_ACCESS__)) {
         return false;
     }
     $o_db = $this->getDb();
     $o_dm = $this->getAppDatamodel();
     $t_rel_label_table = null;
     if (!($t_rel_table = $o_dm->getInstanceByTableNum($this->get('table_num'), true))) {
         return null;
     }
     if (method_exists($t_rel_table, 'getLabelTableName')) {
         if ($vs_label_table_name = $t_rel_table->getLabelTableName()) {
             $t_rel_label_table = $o_dm->getInstanceByTableName($vs_label_table_name, true);
         }
     }
     $vs_label_join_sql = '';
     if ($t_rel_label_table) {
         if ($t_rel_label_table->hasField("is_preferred")) {
             $vs_preferred_sql = " AND rel_label.is_preferred = 1 ";
         }
         $vs_label_join_sql = "LEFT JOIN " . $t_rel_label_table->tableName() . " AS rel_label ON rel." . $t_rel_table->primaryKey() . " = rel_label." . $t_rel_table->primaryKey() . " {$vs_preferred_sql}\n";
     }
     $vs_limit_sql = '';
     if (isset($pa_options['limit']) && $pa_options['limit'] > 0) {
         $vs_limit_sql = "LIMIT " . $pa_options['limit'];
     }
     // get set items
     $vs_access_sql = '';
     if (isset($pa_options['checkAccess']) && is_array($pa_options['checkAccess']) && sizeof($pa_options['checkAccess']) && $t_rel_table->hasField('access')) {
         $vs_access_sql = ' AND rel.access IN (' . join(',', $pa_options['checkAccess']) . ')';
     }
     $vs_deleted_sql = '';
     if ($t_rel_table->hasField('deleted')) {
         $vs_deleted_sql = ' AND rel.deleted = 0';
     }
     $va_representation_counts = array();
     $vs_rep_join_sql = $vs_rep_where_sql = $vs_rep_select = '';
     if ($t_rel_table->tableName() === 'ca_objects' && (isset($pa_options['thumbnailVersion']) || isset($pa_options['thumbnailVersions']))) {
         $vs_rep_join_sql = "LEFT JOIN ca_objects_x_object_representations AS coxor ON rel.object_id = coxor.object_id\nLEFT JOIN ca_object_representations AS cor ON coxor.representation_id = cor.representation_id\n";
         $vs_rep_where_sql = " AND (coxor.is_primary = 1 OR coxor.is_primary IS NULL)";
         $vs_rep_select = ', coxor.*, cor.media, cor.access rep_access';
         // get representation counts
         $qr_rep_counts = $o_db->query("\n\t\t\t\tSELECT \n\t\t\t\t\trel.object_id, count(*) c\n\t\t\t\tFROM ca_set_items casi\n\t\t\t\tINNER JOIN ca_objects AS rel ON rel.object_id = casi.row_id\n\t\t\t\tINNER JOIN ca_objects_x_object_representations AS coxor ON coxor.object_id = rel.object_id\n\t\t\t\tWHERE\n\t\t\t\t\tcasi.set_id = ? {$vs_access_sql} {$vs_deleted_sql}\n\t\t\t\tGROUP BY\n\t\t\t\t\trel.object_id\n\t\t\t", (int) $vn_set_id);
         while ($qr_rep_counts->nextRow()) {
             $va_representation_counts[(int) $qr_rep_counts->get('object_id')] = (int) $qr_rep_counts->get('c');
         }
     }
     // get row labels
     $qr_res = $o_db->query("\n\t\t\tSELECT \n\t\t\t\tcasi.set_id, casi.item_id, casi.row_id, casi.rank,\n\t\t\t\trel_label." . $t_rel_label_table->getDisplayField() . ", rel_label.locale_id\n\t\t\tFROM ca_set_items casi\n\t\t\tINNER JOIN " . $t_rel_table->tableName() . " AS rel ON rel." . $t_rel_table->primaryKey() . " = casi.row_id\n\t\t\t{$vs_label_join_sql}\n\t\t\tWHERE\n\t\t\t\tcasi.set_id = ? {$vs_access_sql} {$vs_deleted_sql}\n\t\t\tORDER BY \n\t\t\t\tcasi.rank ASC\n\t\t\t{$vs_limit_sql}\n\t\t", (int) $vn_set_id);
     $va_labels = array();
     while ($qr_res->nextRow()) {
         $va_labels[$qr_res->get('item_id')][$qr_res->get('locale_id')] = $qr_res->getRow();
     }
     $va_labels = caExtractValuesByUserLocale($va_labels);
     // get set items
     $vs_access_sql = '';
     if (isset($pa_options['checkAccess']) && is_array($pa_options['checkAccess']) && sizeof($pa_options['checkAccess']) && $t_rel_table->hasField('access')) {
         $vs_access_sql = ' AND rel.access IN (' . join(',', $pa_options['checkAccess']) . ')';
     }
     // list items happen to have the same primary key name as set items, which leads to weird side-effects
     // in the code below. so instead of getting rel.* we explicitly list the fields for ca_list_items and
     // rename cli.item_id to list_item_id so that any get('item_id') calls below refer to the set item id
     if ($t_rel_table->tableName() === 'ca_list_items') {
         $va_rel_field_list = array();
         foreach ($t_rel_table->getFields() as $vs_rel_field) {
             if ($vs_rel_field == $t_rel_table->primaryKey()) {
                 $va_rel_field_list[] = "rel.{$vs_rel_field} as list_{$vs_rel_field}";
             } else {
                 $va_rel_field_list[] = "rel.{$vs_rel_field}";
             }
         }
         $vs_rel_field_list_sql = join(', ', $va_rel_field_list);
     } else {
         $vs_rel_field_list_sql = 'rel.*';
     }
     $qr_res = $o_db->query("\n\t\t\tSELECT \n\t\t\t\tcasi.set_id, casi.item_id, casi.row_id, casi.rank, casi.vars,\n\t\t\t\tcasil.label_id, casil.caption, casil.locale_id set_item_label_locale_id,\n\t\t\t\t{$vs_rel_field_list_sql}, rel_label." . $t_rel_label_table->getDisplayField() . " set_item_label, rel_label.locale_id rel_locale_id\n\t\t\t\t{$vs_rep_select}\n\t\t\tFROM ca_set_items casi\n\t\t\tLEFT JOIN ca_set_item_labels AS casil ON casi.item_id = casil.item_id\n\t\t\tINNER JOIN " . $t_rel_table->tableName() . " AS rel ON rel." . $t_rel_table->primaryKey() . " = casi.row_id\n\t\t\t{$vs_label_join_sql}\n\t\t\t{$vs_rep_join_sql}\n\t\t\tWHERE\n\t\t\t\tcasi.set_id = ? {$vs_rep_where_sql} {$vs_access_sql} {$vs_deleted_sql}\n\t\t\tORDER BY \n\t\t\t\tcasi.rank ASC\n\t\t\t{$vs_limit_sql}\n\t\t", (int) $vn_set_id);
     if ($ps_template = caGetOption('template', $pa_options, null)) {
         $qr_ids = $o_db->query("SELECT row_id FROM ca_set_items WHERE set_id = ? ORDER BY rank ASC", $this->getPrimaryKey());
         $va_processed_templates = caProcessTemplateForIDs($ps_template, $t_rel_table->tableName(), $qr_ids->getAllFieldValues('row_id'), array('returnAsArray' => true));
     }
     $va_items = array();
     while ($qr_res->nextRow()) {
         $va_row = $qr_res->getRow();
         unset($va_row['media']);
         if (isset($pa_options['returnRowIdsOnly']) && $pa_options['returnRowIdsOnly'] || isset($pa_options['idsOnly']) && $pa_options['idsOnly']) {
             $va_items[$qr_res->get('row_id')] = true;
             continue;
         }
         if (isset($pa_options['returnItemIdsOnly']) && $pa_options['returnItemIdsOnly']) {
             $va_items[$qr_res->get('item_id')] = true;
             continue;
         }
         $va_vars = caUnserializeForDatabase($va_row['vars']);
         $vb_has_access_to_media = true;
         if ($vs_rep_join_sql && isset($pa_options['checkAccess']) && is_array($pa_options['checkAccess']) && sizeof($pa_options['checkAccess'])) {
             $vb_has_access_to_media = in_array($va_row['rep_access'], $pa_options['checkAccess']);
         }
         if ($vs_rep_join_sql && $vb_has_access_to_media) {
             if (isset($pa_options['thumbnailVersion'])) {
                 $va_row['representation_tag'] = $qr_res->getMediaTag('media', $pa_options['thumbnailVersion']);
                 $va_row['representation_url'] = $qr_res->getMediaUrl('media', $pa_options['thumbnailVersion']);
                 $va_row['representation_width'] = $qr_res->getMediaInfo('media', $pa_options['thumbnailVersion'], 'WIDTH');
                 $va_row['representation_height'] = $qr_res->getMediaInfo('media', $pa_options['thumbnailVersion'], 'HEIGHT');
             }
             if (isset($pa_options['thumbnailVersions']) && is_array($pa_options['thumbnailVersions'])) {
                 foreach ($pa_options['thumbnailVersions'] as $vs_version) {
                     $va_row['representation_tag_' . $vs_version] = $qr_res->getMediaTag('media', $vs_version);
                     $va_row['representation_url_' . $vs_version] = $qr_res->getMediaUrl('media', $vs_version);
                     $va_row['representation_width_' . $vs_version] = $qr_res->getMediaInfo('media', $vs_version, 'WIDTH');
                     $va_row['representation_height_' . $vs_version] = $qr_res->getMediaInfo('media', $vs_version, 'HEIGHT');
                 }
             }
         }
         if ($t_rel_table->tableName() === 'ca_objects') {
             if (isset($va_vars['selected_services'])) {
                 $va_row['selected_services'] = array_keys($va_vars['selected_services']);
             } else {
                 $va_row['selected_services'] = array();
             }
             if (isset($va_vars['selected_representations'])) {
                 $va_row['selected_representations'] = array_keys($va_vars['selected_representations']);
             } else {
                 $va_row['selected_representations'] = array();
             }
             $va_row['representation_count'] = (int) $va_representation_counts[$qr_res->get('row_id')];
         }
         if (is_array($va_labels[$vn_item_id = $qr_res->get('item_id')])) {
             $va_row = array_merge($va_row, $va_labels[$vn_item_id]);
         }
         if (isset($pa_options['returnItemAttributes']) && is_array($pa_options['returnItemAttributes']) && sizeof($pa_options['returnItemAttributes'])) {
             // TODO: doing a load for each item is inefficient... must replace with a query
             $t_item = new ca_set_items($va_row['item_id']);
             foreach ($pa_options['returnItemAttributes'] as $vs_element_code) {
                 $va_row['ca_attribute_' . $vs_element_code] = $t_item->getAttributesForDisplay($vs_element_code);
             }
             $va_row['set_item_label'] = $t_item->getLabelForDisplay(false);
         }
         if ($ps_template) {
             $va_row['displayTemplate'] = array_shift($va_processed_templates);
         }
         $va_items[$qr_res->get('item_id')][$qr_res->get('rel_locale_id') ? $qr_res->get('rel_locale_id') : 0] = $va_row;
     }
     if (caGetOption('idsOnly', $pa_options, false)) {
         return array_keys($va_items);
     }
     return $va_items;
 }
 /**
  * Prepopulate record fields according to rules in prepopulate.conf
  *
  * @param array $pa_options Options array. Available options are:
  * 		prepopulateConfig = override path to prepopulate.conf, e.g. for testing purposes
  * @return bool success or not
  */
 public function prepopulateFields($pa_options = null)
 {
     if (!$this->getPrimaryKey()) {
         return false;
     }
     if (!($vs_prepopulate_cfg = caGetOption('prepopulateConfig', $pa_options, null))) {
         $vs_prepopulate_cfg = $this->getAppConfig()->get('prepopulate_config');
     }
     $o_prepopulate_conf = Configuration::load($vs_prepopulate_cfg);
     if (!($o_prepopulate_conf->get('prepopulate_fields_on_save') || $o_prepopulate_conf->get('prepopulate_fields_on_load'))) {
         return false;
     }
     $va_rules = $o_prepopulate_conf->get('prepopulate_rules');
     if (!$va_rules || !is_array($va_rules) || sizeof($va_rules) < 1) {
         return false;
     }
     global $g_ui_locale_id;
     // we need to unset the form timestamp to disable the 'Changes have been made since you loaded this data' warning when we update() $this
     // the warning makes sense because an update()/insert() is called before we arrive here but after the form_timestamp ... but we chose to ignore it
     $vn_timestamp = $_REQUEST['form_timestamp'];
     unset($_REQUEST['form_timestamp']);
     $vb_we_set_transaction = true;
     if (!$this->inTransaction()) {
         $this->setTransaction(new Transaction($this->getDb()));
         $vb_we_set_transaction = true;
     }
     // process rules
     $va_expression_vars = array();
     // we only process those if and when we need them
     foreach ($va_rules as $vs_rule_key => $va_rule) {
         if ($this->tableName() != $va_rule['table']) {
             continue;
         }
         // check target
         $vs_target = $va_rule['target'];
         if (strlen($vs_target) < 1) {
             Debug::msg("[prepopulateFields()] skipping rule {$vs_rule_key} because target is not set");
             continue;
         }
         // check template
         $vs_template = $va_rule['template'];
         if (strlen($vs_template) < 1) {
             Debug::msg("[prepopulateFields()] skipping rule {$vs_rule_key} because template is not set");
             continue;
         }
         $vs_mode = caGetOption('mode', $va_rule, 'merge');
         // respect restrictToTypes option
         if ($va_rule['restrictToTypes'] && is_array($va_rule['restrictToTypes']) && sizeof($va_rule['restrictToTypes']) > 0) {
             if (!in_array($this->getTypeCode(), $va_rule['restrictToTypes'])) {
                 Debug::msg("[prepopulateFields()] skipping rule {$vs_rule_key} because current record type " . $this->getTypeCode() . " is not in restrictToTypes");
                 continue;
             }
         }
         // skip this rule if expression is true
         if ($va_rule['skipIfExpression'] && strlen($va_rule['skipIfExpression']) > 0) {
             $va_tags = caGetTemplateTags($va_rule['skipIfExpression']);
             foreach ($va_tags as $vs_tag) {
                 if (!isset($va_expression_vars[$vs_tag])) {
                     $va_expression_vars[$vs_tag] = $this->get($vs_tag, array('returnIdno' => true, 'delimiter' => ';'));
                 }
             }
             if (ExpressionParser::evaluate($va_rule['skipIfExpression'], $va_expression_vars)) {
                 Debug::msg("[prepopulateFields()] skipping rule {$vs_rule_key} because skipIfExpression evaluated true");
                 continue;
             }
         }
         // evaluate template
         $vs_value = caProcessTemplateForIDs($vs_template, $this->tableNum(), array($this->getPrimaryKey()), array('path' => true));
         Debug::msg("[prepopulateFields()] processed template for rule {$vs_rule_key} value is: " . $vs_value);
         // inject into target
         $va_parts = explode('.', $vs_target);
         // intrinsic or simple (non-container) attribute
         if (sizeof($va_parts) == 2) {
             // intrinsic
             if ($this->hasField($va_parts[1])) {
                 switch (strtolower($vs_mode)) {
                     case 'overwrite':
                         // always set
                         $this->set($va_parts[1], $vs_value);
                         break;
                     case 'addifempty':
                     default:
                         if (!$this->get($va_parts[1])) {
                             $this->set($va_parts[1], $vs_value);
                         } else {
                             Debug::msg("[prepopulateFields()] rule {$vs_rule_key}: intrinsic skipped because it already has value and mode is addIfEmpty or merge");
                         }
                         break;
                 }
                 // attribute/element
             } elseif ($this->hasElement($va_parts[1])) {
                 $va_attributes = $this->getAttributesByElement($va_parts[1]);
                 if (sizeof($va_attributes) > 1) {
                     Debug::msg("[prepopulateFields()] containers with multiple values are not supported");
                     continue;
                 }
                 switch (strtolower($vs_mode)) {
                     case 'overwrite':
                         // always replace first value we find
                         $this->replaceAttribute(array($va_parts[1] => $vs_value, 'locale_id' => $g_ui_locale_id), $va_parts[1]);
                         break;
                     default:
                     case 'addifempty':
                         // only add value if none exists
                         if (!$this->get($vs_target)) {
                             $this->replaceAttribute(array($va_parts[1] => $vs_value, 'locale_id' => $g_ui_locale_id), $va_parts[1]);
                         }
                         break;
                 }
             }
             // "container"
         } elseif (sizeof($va_parts) == 3) {
             // actual container
             if ($this->hasElement($va_parts[1])) {
                 $va_attr = $this->getAttributesByElement($va_parts[1]);
                 switch (sizeof($va_attr)) {
                     case 1:
                         switch (strtolower($vs_mode)) {
                             case 'overwrite':
                                 $vo_attr = array_pop($va_attr);
                                 $va_value = array($va_parts[2] => $vs_value);
                                 foreach ($vo_attr->getValues() as $o_val) {
                                     if ($o_val->getElementCode() != $va_parts[2]) {
                                         $va_value[$o_val->getElementCode()] = $o_val->getDisplayValue();
                                     }
                                 }
                                 $this->_editAttribute($vo_attr->getAttributeID(), $va_value);
                                 break;
                             case 'addifempty':
                                 $vo_attr = array_pop($va_attr);
                                 $va_value = array($va_parts[2] => $vs_value);
                                 $vb_update = false;
                                 foreach ($vo_attr->getValues() as $o_val) {
                                     if ($o_val->getElementCode() != $va_parts[2]) {
                                         $va_value[$o_val->getElementCode()] = $o_val->getDisplayValue();
                                     } else {
                                         if (!$o_val->getDisplayValue()) {
                                             $vb_update = true;
                                         }
                                     }
                                 }
                                 if ($vb_update) {
                                     $this->editAttribute($vo_attr->getAttributeID(), $va_parts[1], $va_value);
                                 }
                                 break;
                             default:
                                 Debug::msg("[prepopulateFields()] unsupported mode {$vs_mode} for target bundle");
                                 break;
                         }
                         break;
                     case 0:
                         // if no container value exists, always add it (ignoring mode)
                         $this->addAttribute(array($va_parts[2] => $vs_value, 'locale_id' => $g_ui_locale_id), $va_parts[1]);
                         break;
                     default:
                         Debug::msg("[prepopulateFields()] containers with multiple values are not supported");
                         break;
                 }
                 // labels
             } elseif ($va_parts[1] == 'preferred_labels' || $va_parts[1] == 'nonpreferred_labels') {
                 $vb_preferred = $va_parts[1] == 'preferred_labels';
                 if (!($t_label = $this->getAppDatamodel()->getInstanceByTableName($this->getLabelTableName(), true))) {
                     continue;
                 }
                 if (!$t_label->hasField($va_parts[2])) {
                     continue;
                 }
                 switch ($this->getLabelCount($vb_preferred)) {
                     case 0:
                         // if no value exists, always add it (ignoring mode)
                         $this->addLabel(array($va_parts[2] => $vs_value), $g_ui_locale_id, null, $vb_preferred);
                         break;
                     case 1:
                         switch (strtolower($vs_mode)) {
                             case 'overwrite':
                             case 'addifempty':
                                 $va_labels = $this->getLabels(null, $vb_preferred ? __CA_LABEL_TYPE_PREFERRED__ : __CA_LABEL_TYPE_NONPREFERRED__);
                                 if (sizeof($va_labels)) {
                                     $va_labels = caExtractValuesByUserLocale($va_labels);
                                     $va_label = array_shift($va_labels);
                                     $va_label = $va_label[0];
                                     $va_label[$va_parts[2]] = $vs_value;
                                     $vb_update = false;
                                     if (strtolower($vs_mode) == 'overwrite') {
                                         $va_label[$va_parts[2]] = $vs_value;
                                         $vb_update = true;
                                     } else {
                                         if (strlen(trim($va_label[$va_parts[2]])) == 0) {
                                             // in addifempty mode only edit label when field is not set
                                             $va_label[$va_parts[2]] = $vs_value;
                                             $vb_update = true;
                                         }
                                     }
                                     if ($vb_update) {
                                         $this->editLabel($va_label['label_id'], $va_label, $g_ui_locale_id, null, $vb_preferred);
                                     }
                                 } else {
                                     $this->addLabel(array($va_parts[2] => $vs_value), $g_ui_locale_id, null, $vb_preferred);
                                 }
                                 break;
                             default:
                                 Debug::msg("[prepopulateFields()] unsupported mode {$vs_mode} for target bundle");
                                 break;
                         }
                         break;
                     default:
                         Debug::msg("[prepopulateFields()] records with multiple labels are not supported");
                         break;
                 }
             }
         }
     }
     $vn_old_mode = $this->getMode();
     $this->setMode(ACCESS_WRITE);
     $this->update();
     $this->setMode($vn_old_mode);
     $_REQUEST['form_timestamp'] = $vn_timestamp;
     if ($this->numErrors() > 0) {
         foreach ($this->getErrors() as $vs_error) {
             Debug::msg("[prepopulateFields()] there was an error while updating the record: " . $vs_error);
         }
         if ($vb_we_set_transaction) {
             $this->removeTransaction(false);
         }
         return false;
     }
     if ($vb_we_set_transaction) {
         $this->removeTransaction(true);
     }
     return true;
 }
示例#22
0
 /**
  * Processes single exporter item for a given record
  *
  * @param int $pn_item_id Primary of exporter item
  * @param int $pn_table_num Table num of item to export
  * @param int $pn_record_id Primary key value of item to export
  * @param array $pa_options
  *		ignoreContext = don't switch context even though context may be set for current item
  *		relationship_type_id, relationship_type_code, relationship_typename =
  *			if this export is a sub-export (context-switch), we have no way of knowing the relationship
  *			to the 'parent' element in the export, so there has to be a means to pass it down to make it accessible
  * 		attribute_id = signals that this is an export relative to a specific attribute instance
  * 			this triggers special behavior that allows getting container values in a kind of sub-export
  *			it's really only useful for Containers but in theory can be any attribute
  *		logger = KLogger instance to use for logging. This option is mandatory!
  * @return array Item info
  */
 public function processExporterItem($pn_item_id, $pn_table_num, $pn_record_id, $pa_options = array())
 {
     $o_log = caGetOption('logger', $pa_options);
     // always set by exportRecord()
     $vb_ignore_context = caGetOption('ignoreContext', $pa_options);
     $vn_attribute_id = caGetOption('attribute_id', $pa_options);
     $o_log->logInfo(_t("Export mapping processor called with parameters [exporter_item_id:%1 table_num:%2 record_id:%3]", $pn_item_id, $pn_table_num, $pn_record_id));
     $t_exporter_item = ca_data_exporters::loadExporterItemByID($pn_item_id);
     $t_instance = ca_data_exporters::loadInstanceByID($pn_record_id, $pn_table_num);
     // switch context to a different set of records if necessary and repeat current exporter item for all those selected records
     // (e.g. hierarchy children or related items in another table, restricted by types or relationship types)
     if (!$vb_ignore_context && ($vs_context = $t_exporter_item->getSetting('context'))) {
         $va_restrict_to_types = $t_exporter_item->getSetting('restrictToTypes');
         $va_restrict_to_rel_types = $t_exporter_item->getSetting('restrictToRelationshipTypes');
         $va_restrict_to_bundle_vals = $t_exporter_item->getSetting('restrictToBundleValues');
         $va_check_access = $t_exporter_item->getSetting('checkAccess');
         $va_sort = $t_exporter_item->getSetting('sort');
         $vn_new_table_num = $this->getAppDatamodel()->getTableNum($vs_context);
         $vb_context_is_related_table = false;
         $va_related = null;
         if ($vn_new_table_num) {
             // switch to new table
             $vs_key = $this->getAppDatamodel()->getTablePrimaryKeyName($vs_context);
         } else {
             // this table, i.e. hierarchy context switch
             $vs_key = $t_instance->primaryKey();
         }
         $o_log->logInfo(_t("Initiating context switch to '%1' for mapping ID %2 and record ID %3. The processor now tries to find matching records for the switch and calls itself for each of those items.", $vs_context, $pn_item_id, $pn_record_id));
         switch ($vs_context) {
             case 'children':
                 $va_related = $t_instance->getHierarchyChildren();
                 break;
             case 'parent':
                 $va_related = array();
                 if ($vs_parent_id_fld = $t_instance->getProperty("HIERARCHY_PARENT_ID_FLD")) {
                     $va_related[] = array($vs_key => $t_instance->get($vs_parent_id_fld));
                 }
                 break;
             case 'ancestors':
                 $va_parents = $t_instance->getHierarchyAncestors(null, array('idsOnly' => true));
                 $va_related = array();
                 foreach (array_unique($va_parents) as $vn_pk) {
                     $va_related[] = array($vs_key => intval($vn_pk));
                 }
                 break;
             case 'ca_sets':
                 $t_set = new ca_sets();
                 $va_set_options = array();
                 if (isset($va_restrict_to_types[0])) {
                     // the utility used below doesn't support passing multiple types so we just pass the first.
                     // this should be enough for 99.99% of the actual use cases anyway
                     $va_set_options['setType'] = $va_restrict_to_types[0];
                 }
                 $va_set_options['checkAccess'] = $va_check_access;
                 $va_set_options['setIDsOnly'] = true;
                 $va_set_ids = $t_set->getSetsForItem($pn_table_num, $t_instance->getPrimaryKey(), $va_set_options);
                 $va_related = array();
                 foreach (array_unique($va_set_ids) as $vn_pk) {
                     $va_related[] = array($vs_key => intval($vn_pk));
                 }
                 break;
             case 'ca_list_items.firstLevel':
                 if ($t_instance->tableName() == 'ca_lists') {
                     $o_dm = Datamodel::load();
                     $va_related = array();
                     $va_items_legacy_format = $t_instance->getListItemsAsHierarchy(null, array('maxLevels' => 1, 'dontIncludeRoot' => true));
                     $vn_new_table_num = $o_dm->getTableNum('ca_list_items');
                     $vs_key = 'item_id';
                     foreach ($va_items_legacy_format as $va_item_legacy_format) {
                         $va_related[$va_item_legacy_format['NODE']['item_id']] = $va_item_legacy_format['NODE'];
                     }
                     break;
                 } else {
                     return array();
                 }
                 break;
             default:
                 if ($vn_new_table_num) {
                     $va_options = array('restrictToTypes' => $va_restrict_to_types, 'restrictToRelationshipTypes' => $va_restrict_to_rel_types, 'restrictToBundleValues' => $va_restrict_to_bundle_vals, 'checkAccess' => $va_check_access, 'sort' => $va_sort);
                     $o_log->logDebug(_t("Calling getRelatedItems with options: %1.", print_r($va_options, true)));
                     $va_related = $t_instance->getRelatedItems($vs_context, $va_options);
                     $vb_context_is_related_table = true;
                 } else {
                     // container or invalid context
                     $va_context_tmp = explode('.', $vs_context);
                     if (sizeof($va_context_tmp) != 2) {
                         $o_log->logError(_t("Invalid context %1. Ignoring this mapping.", $vs_context));
                         return array();
                     }
                     $va_attrs = $t_instance->getAttributesByElement($va_context_tmp[1]);
                     $va_info = array();
                     if (is_array($va_attrs) && sizeof($va_attrs) > 0) {
                         $o_log->logInfo(_t("Switching context for element code: %1.", $va_context_tmp[1]));
                         $o_log->logDebug(_t("Raw attribute value array is as follows. The mapping will now be repeated for each (outer) attribute. %1", print_r($va_attrs, true)));
                         foreach ($va_attrs as $vo_attr) {
                             $va_attribute_export = $this->processExporterItem($pn_item_id, $pn_table_num, $pn_record_id, array_merge(array('ignoreContext' => true, 'attribute_id' => $vo_attr->getAttributeID()), $pa_options));
                             $va_info = array_merge($va_info, $va_attribute_export);
                         }
                     } else {
                         $o_log->logInfo(_t("Switching context for element code %1 failed. Either there is no attribute with that code attached to the current row or the code is invalid. Mapping is ignored for current row.", $va_context_tmp[1]));
                     }
                     return $va_info;
                 }
                 break;
         }
         $va_info = array();
         if (is_array($va_related)) {
             $o_log->logDebug(_t("The current mapping will now be repreated for these items: %1", print_r($va_related, true)));
             if (!$vn_new_table_num) {
                 $vn_new_table_num = $pn_table_num;
             }
             foreach ($va_related as $va_rel) {
                 // if we're dealing with a related table, pass on some info the relationship type to the context-switched invocation of processExporterItem(),
                 // because we can't access that information from the related item simply because we don't exactly know where the call originated
                 if ($vb_context_is_related_table) {
                     $pa_options['relationship_typename'] = $va_rel['relationship_typename'];
                     $pa_options['relationship_type_code'] = $va_rel['relationship_type_code'];
                     $pa_options['relationship_type_id'] = $va_rel['relationship_type_id'];
                 }
                 $va_rel_export = $this->processExporterItem($pn_item_id, $vn_new_table_num, $va_rel[$vs_key], array_merge(array('ignoreContext' => true), $pa_options));
                 $va_info = array_merge($va_info, $va_rel_export);
             }
         } else {
             $o_log->logDebug(_t("No matching related items found for last context switch"));
         }
         return $va_info;
     }
     // end switch context
     // Don't prevent context switches for children of context-switched exporter items. This way you can
     // build cascades for jobs like exporting objects related to the creator of the record in question.
     unset($pa_options['ignoreContext']);
     $va_item_info = array();
     $vs_source = $t_exporter_item->get('source');
     $vs_element = $t_exporter_item->get('element');
     $vb_repeat = $t_exporter_item->getSetting('repeat_element_for_multiple_values');
     // if omitIfEmpty is set and get() returns nothing, we ignore this exporter item and all children
     if ($vs_omit_if_empty = $t_exporter_item->getSetting('omitIfEmpty')) {
         if (!(strlen($t_instance->get($vs_omit_if_empty)) > 0)) {
             return array();
         }
     }
     // if omitIfNotEmpty is set and get() returns a value, we ignore this exporter item and all children
     if ($vs_omit_if_not_empty = $t_exporter_item->getSetting('omitIfNotEmpty')) {
         if (strlen($t_instance->get($vs_omit_if_not_empty)) > 0) {
             return array();
         }
     }
     // always return URL for export, not an HTML tag
     $va_get_options = array('returnURL' => true);
     if ($vs_delimiter = $t_exporter_item->getSetting("delimiter")) {
         $va_get_options['delimiter'] = $vs_delimiter;
     }
     if ($vs_template = $t_exporter_item->getSetting('template')) {
         $va_get_options['template'] = $vs_template;
     }
     if ($vs_locale = $t_exporter_item->getSetting('locale')) {
         // the global UI locale for some reason has a higher priority
         // than the locale setting in BaseModelWithAttributes::get
         // which is why we unset it here and restore it later
         global $g_ui_locale;
         $vs_old_ui_locale = $g_ui_locale;
         $g_ui_locale = null;
         $va_get_options['locale'] = $vs_locale;
     }
     // AttributeValue settings that are simply passed through by the exporter
     if ($t_exporter_item->getSetting('convertCodesToDisplayText')) {
         $va_get_options['convertCodesToDisplayText'] = true;
         // try to return text suitable for display for system lists stored in intrinsics (ex. ca_objects.access, ca_objects.status, ca_objects.source_id)
         // this does not affect list attributes
     } else {
         $va_get_options['convertCodesToIdno'] = true;
         // if display text is not requested try to return list item idno's... since underlying integer ca_list_items.item_id values are unlikely to be useful in an export context
     }
     if ($t_exporter_item->getSetting('returnIdno')) {
         $va_get_options['returnIdno'] = true;
     }
     if ($t_exporter_item->getSetting('start_as_iso8601')) {
         $va_get_options['start_as_iso8601'] = true;
     }
     if ($t_exporter_item->getSetting('end_as_iso8601')) {
         $va_get_options['end_as_iso8601'] = true;
     }
     if ($t_exporter_item->getSetting('dontReturnValueIfOnSameDayAsStart')) {
         $va_get_options['dontReturnValueIfOnSameDayAsStart'] = true;
     }
     if ($vs_date_format = $t_exporter_item->getSetting('dateFormat')) {
         $va_get_options['dateFormat'] = $vs_date_format;
     }
     // context was switched to attribute
     if ($vn_attribute_id) {
         $o_log->logInfo(_t("Processing mapping in attribute mode for attribute_id = %1.", $vn_attribute_id));
         if ($vs_source) {
             // trying to find the source only makes sense if the source is set
             $t_attr = new ca_attributes($vn_attribute_id);
             $va_values = $t_attr->getAttributeValues();
             $va_src_tmp = explode('.', $vs_source);
             if (sizeof($va_src_tmp) == 2) {
                 $o_dm = Datamodel::load();
                 if ($t_attr->get('table_num') == $o_dm->getTableNum($va_src_tmp[0])) {
                     $vs_source = $va_src_tmp[1];
                 }
             }
             $o_log->logDebug(_t("Trying to find code %1 in value array for the current attribute.", $vs_source));
             $o_log->logDebug(_t("Value array is %1.", print_r($va_values, true)));
             foreach ($va_values as $vo_val) {
                 $va_display_val_options = array();
                 if ($vo_val instanceof ListAttributeValue) {
                     // figure out list_id -- without it we can't pull display values
                     $t_element = new ca_metadata_elements($vo_val->getElementID());
                     $va_display_val_options = array('list_id' => $t_element->get('list_id'));
                     if ($t_exporter_item->getSetting('returnIdno') || $t_exporter_item->getSetting('convertCodesToIdno')) {
                         $va_display_val_options['output'] = 'idno';
                     } elseif ($t_exporter_item->getSetting('convertCodesToDisplayText')) {
                         $va_display_val_options['output'] = 'text';
                     }
                 }
                 $o_log->logDebug(_t("Trying to match code from array %1 and the code we're looking for %2.", $vo_val->getElementCode(), $vs_source));
                 if ($vo_val->getElementCode() == $vs_source) {
                     $vs_display_value = $vo_val->getDisplayValue($va_display_val_options);
                     $o_log->logDebug(_t("Found value %1.", $vs_display_value));
                     $va_item_info[] = array('text' => $vs_display_value, 'element' => $vs_element);
                 }
             }
         } else {
             // no source in attribute context probably means this is some form of wrapper, e.g. a MARC field
             $va_item_info[] = array('element' => $vs_element);
         }
     } else {
         if ($vs_source) {
             $o_log->logDebug(_t("Source for current mapping is %1", $vs_source));
             $va_matches = array();
             // CONSTANT value
             if (preg_match("/^_CONSTANT_:(.*)\$/", $vs_source, $va_matches)) {
                 $o_log->logDebug(_t("This is a constant. Value for this mapping is '%1'", trim($va_matches[1])));
                 $va_item_info[] = array('text' => trim($va_matches[1]), 'element' => $vs_element);
             } else {
                 if (in_array($vs_source, array("relationship_type_id", "relationship_type_code", "relationship_typename"))) {
                     if (isset($pa_options[$vs_source]) && strlen($pa_options[$vs_source]) > 0) {
                         $o_log->logDebug(_t("Source refers to releationship type information. Value for this mapping is '%1'", $pa_options[$vs_source]));
                         $va_item_info[] = array('text' => $pa_options[$vs_source], 'element' => $vs_element);
                     }
                 } else {
                     if (!$vb_repeat) {
                         $vs_get = $t_instance->get($vs_source, $va_get_options);
                         $o_log->logDebug(_t("Source is a simple get() for some bundle. Value for this mapping is '%1'", $vs_get));
                         $o_log->logDebug(_t("get() options are: %1", print_r($va_get_options, true)));
                         $va_item_info[] = array('text' => $vs_get, 'element' => $vs_element);
                     } else {
                         // user wants current element repeated in case of multiple returned values
                         $va_get_options['delimiter'] = ';#;';
                         $vs_values = $t_instance->get($vs_source, $va_get_options);
                         $o_log->logDebug(_t("Source is a get() that should be repeated for multiple values. Value for this mapping is '%1'. It includes the custom delimiter ';#;' that is later used to split the value into multiple values.", $vs_values));
                         $o_log->logDebug(_t("get() options are: %1", print_r($va_get_options, true)));
                         $va_tmp = explode(";#;", $vs_values);
                         foreach ($va_tmp as $vs_text) {
                             $va_item_info[] = array('element' => $vs_element, 'text' => $vs_text);
                         }
                     }
                 }
             }
         } else {
             if ($vs_template) {
                 // templates without source are probably just static text, but you never know
                 // -> run them through processor anyways
                 $vs_proc_template = caProcessTemplateForIDs($vs_template, $pn_table_num, array($pn_record_id), array());
                 $o_log->logDebug(_t("Current mapping has no source but a template '%1'. Value from extracted via template processor is '%2'", $vs_template, $vs_proc_template));
                 $va_item_info[] = array('element' => $vs_element, 'text' => $vs_proc_template);
             } else {
                 // no source, no template -> probably wrapper
                 $o_log->logDebug(_t("Current mapping has no source and no template and is probably an XML/MARC wrapper element"));
                 $va_item_info[] = array('element' => $vs_element);
             }
         }
     }
     // reset UI locale if we unset it
     if ($vs_locale) {
         $g_ui_locale = $vs_old_ui_locale;
     }
     $o_log->logDebug(_t("We're now processing other settings like default, prefix, suffix, skipIfExpression, filterByRegExp, maxLength, plugins and replacements for this mapping"));
     $o_log->logDebug(_t("Local data before processing is: %1", print_r($va_item_info, true)));
     // handle other settings and plugin hooks
     $vs_default = $t_exporter_item->getSetting('default');
     $vs_prefix = $t_exporter_item->getSetting('prefix');
     $vs_suffix = $t_exporter_item->getSetting('suffix');
     //$vs_regexp = $t_exporter_item->getSetting('filterByRegExp');		// Deprecated -- remove?
     $vn_max_length = $t_exporter_item->getSetting('maxLength');
     $vs_skip_if_expr = $t_exporter_item->getSetting('skipIfExpression');
     $vs_original_values = $t_exporter_item->getSetting('original_values');
     $vs_replacement_values = $t_exporter_item->getSetting('replacement_values');
     $va_replacements = ca_data_exporter_items::getReplacementArray($vs_original_values, $vs_replacement_values);
     foreach ($va_item_info as $vn_key => &$va_item) {
         $this->opo_app_plugin_manager->hookExportItemBeforeSettings(array('instance' => $t_instance, 'exporter_item_instance' => $t_exporter_item, 'export_item' => &$va_item));
         // handle dontReturnValueIfOnSameDayAsStart
         if (caGetOption('dontReturnValueIfOnSameDayAsStart', $va_get_options, false)) {
             if (strlen($va_item['text']) < 1) {
                 unset($va_item_info[$vn_key]);
             }
         }
         // handle skipIfExpression setting
         if ($vs_skip_if_expr) {
             // Add current value as variable "value", accessible in expressions as ^value
             $va_vars = array_merge(array('value' => $va_item['text']), ca_data_exporters::$s_variables);
             if (ExpressionParser::evaluate($vs_skip_if_expr, $va_vars)) {
                 unset($va_item_info[$vn_key]);
                 continue;
             }
         }
         // filter by regex (deprecated since you can do the same thing and more with skipIfExpression) -- remove?
         //if((strlen($va_item['text'])>0) && $vs_regexp) {
         //	if(!preg_match("!".$vs_regexp."!i", $va_item['text'])) {
         //		unset($va_item_info[$vn_key]);
         //		continue;
         //	}
         //}
         // do replacements
         $va_item['text'] = ca_data_exporter_items::replaceText($va_item['text'], $va_replacements);
         // if text is empty, fill in default
         // if text isn't empty, respect prefix and suffix
         if (strlen($va_item['text']) == 0) {
             if ($vs_default) {
                 $va_item['text'] = $vs_default;
             }
         } else {
             if (strlen($vs_prefix) > 0 || strlen($vs_suffix) > 0) {
                 $va_item['text'] = $vs_prefix . $va_item['text'] . $vs_suffix;
             }
         }
         if ($vn_max_length && strlen($va_item['text']) > $vn_max_length) {
             $va_item['text'] = substr($va_item['text'], 0, $vn_max_length) . " ...";
         }
         // if this is a variable, set the value and delete it from the export tree
         $va_matches = array();
         if (preg_match("/^_VARIABLE_:(.*)\$/", $va_item['element'], $va_matches)) {
             ca_data_exporters::$s_variables[$va_matches[1]] = $va_item['text'];
             unset($va_item_info[$vn_key]);
             continue;
         }
         // if returned value is null then we skip the item
         $this->opo_app_plugin_manager->hookExportItem(array('instance' => $t_instance, 'exporter_item_instance' => $t_exporter_item, 'export_item' => &$va_item));
     }
     $o_log->logInfo(_t("Extracted data for this mapping is as follows:"));
     foreach ($va_item_info as $va_tmp) {
         $o_log->logInfo(sprintf("    element:%-20s value: %-10s", $va_tmp['element'], $va_tmp['text']));
     }
     $va_children = $t_exporter_item->getHierarchyChildren();
     if (is_array($va_children) && sizeof($va_children) > 0) {
         $o_log->logInfo(_t("Now proceeding to process %1 direct children in the mapping hierarchy", sizeof($va_children)));
         foreach ($va_children as $va_child) {
             foreach ($va_item_info as &$va_info) {
                 $va_child_export = $this->processExporterItem($va_child['item_id'], $pn_table_num, $pn_record_id, $pa_options);
                 $va_info['children'] = array_merge((array) $va_info['children'], $va_child_export);
             }
         }
     }
     return $va_item_info;
 }
示例#23
0
 /**
  * Perform search
  * @param array|null $pa_bundles list of bundles to return for search result
  * @return array|bool
  */
 protected function search($pa_bundles = null)
 {
     if (!($vo_search = caGetSearchInstance($this->getTableName()))) {
         $this->addError(_t("Invalid table"));
         return false;
     }
     $t_instance = $this->_getTableInstance($vs_table_name = $this->getTableName());
     $va_return = array();
     $vo_result = $vo_search->search($this->ops_query, array('deletedOnly' => $this->opb_deleted_only, 'sort' => $this->opo_request->getParameter('sort', pString), 'sortDirection' => $this->opo_request->getParameter('sortDirection', pString)));
     $vs_template = $this->opo_request->getParameter('template', pString);
     // allow user-defined template to be passed; allows flexible formatting of returned label
     while ($vo_result->nextHit()) {
         $va_item = array();
         $va_item[$t_instance->primaryKey()] = $vn_id = $vo_result->get($t_instance->primaryKey());
         $va_item['id'] = $vn_id;
         if ($vs_idno = $vo_result->get("idno")) {
             $va_item["idno"] = $vs_idno;
         }
         if ($vs_template) {
             $va_item["display_label"] = caProcessTemplateForIDs($vs_template, $vs_table_name, array($vn_id), array('convertCodesToDisplayText' => true));
         } else {
             $va_item["display_label"] = $vo_result->get($vs_table_name . '.preferred_labels');
         }
         if (is_array($pa_bundles)) {
             foreach ($pa_bundles as $vs_bundle => $va_options) {
                 if (!is_array($va_options)) {
                     $va_options = array();
                 }
                 if ($this->_isBadBundle($vs_bundle)) {
                     continue;
                 }
                 // special treatment for ca_object_representations.media bundle
                 // it should provide a means to get the media info array
                 if (trim($vs_bundle) == 'ca_object_representations.media') {
                     if ($t_instance instanceof RepresentableBaseModel) {
                         $va_reps = $vo_result->getMediaInfo($vs_bundle);
                         if (is_array($va_reps) && sizeof($va_reps) > 0) {
                             $va_item[$vs_bundle] = $va_reps;
                             continue;
                         }
                     }
                 }
                 $vm_return = $vo_result->get($vs_bundle, $va_options);
                 // render 'empty' arrays as JSON objects, not as lists (which is the default behavior of json_encode)
                 if (is_array($vm_return) && sizeof($vm_return) == 0) {
                     $va_item[$vs_bundle] = new stdClass();
                 } else {
                     $va_item[$vs_bundle] = $vm_return;
                 }
             }
         }
         $va_return["results"][] = $va_item;
     }
     return $va_return;
 }
示例#24
0
 /** 
  * Get display value(s) out of result $po_result for specified bundle and format it using the configured value template
  *
  * @param object $po_result A sub-class of SearchResult or BaseModel to extract data out of
  * @param int $pn_placement_id 
  * @param array Optional array of options. Supported options include:
  *		request = The current RequestHTTP object
  *		convertCodesToDisplayText = If true numeric list id's and value lists are converted to display text. Default is true. If false then all such values are returned as the original integer codes.
  *		forReport = If true then certain values are transformed for display in a report. Namely, all media output is forced to use the version specified by the app.conf 'representation_version_for_report' directive, no matter the setting in the display.
  *		purify = if true then value is run through HTMLPurifier (http://htmlpurifier.org) before being returned; this is useful when you want to make sure any HTML in the value is valid, particularly when converting HTML to a PDF as invalid markup will cause an exception. Default is false as HTMLPurify can significantly slow down things if used everywhere.
  *		delimiter = character(s) to place between repeating values
  *
  * @return string The processed value ready for display
  */
 public function getDisplayValue($po_result, $pn_placement_id, $pa_options = null)
 {
     if (!is_numeric($pn_placement_id)) {
         $vs_bundle_name = $pn_placement_id;
         $va_placement = array();
     } else {
         $va_placements = $this->getPlacements();
         $va_placement = $va_placements[$pn_placement_id];
         $vs_bundle_name = $va_placement['bundle_name'];
     }
     if (!is_array($pa_options)) {
         $pa_options = array();
     }
     $o_request = caGetOption('request', $pa_options, null);
     if (!isset($pa_options['convertCodesToDisplayText'])) {
         $pa_options['convertCodesToDisplayText'] = true;
     }
     if (!isset($pa_options['delimiter'])) {
         $pa_options['delimiter'] = ";\n\n";
     }
     if (!isset($pa_options['forReport'])) {
         $pa_options['forReport'] = false;
     }
     if (!isset($pa_options['purify'])) {
         $pa_options['purify'] = false;
     }
     if (!isset($pa_options['asHTML'])) {
         $pa_options['asHTML'] = true;
     }
     if (!isset($pa_options['maximumLength'])) {
         $pa_options['maximumLength'] = $va_placement['settings']['maximum_length'] ? $va_placement['settings']['maximum_length'] : null;
     }
     if (!isset($pa_options['filter'])) {
         $pa_options['filter'] = caGetOption('filter', $va_placement['settings'], null);
     }
     $pa_options['delimiter'] = $va_placement['settings']['delimiter'] ? $va_placement['settings']['delimiter'] : $pa_options['delimiter'];
     $pa_options['useSingular'] = isset($va_placement['settings']['sense']) && $va_placement['settings']['sense'] == 'singular' ? true : false;
     $pa_options['returnURL'] = isset($va_placement['settings']['display_mode']) && $va_placement['settings']['display_mode'] == 'url' ? true : false;
     $pa_options['dateFormat'] = isset($va_placement['settings']['dateFormat']) && $va_placement['settings']['dateFormat'] ? $va_placement['settings']['dateFormat'] : $pa_options['dateFormat'];
     if (caGetOption('display_currency_conversion', $va_placement['settings'], false) && $o_request && $o_request->isLoggedIn()) {
         $pa_options['displayCurrencyConversion'] = $o_request->user->getPreference('currency');
     }
     $pa_options['hierarchicalDelimiter'] = '';
     $va_tmp = explode('.', $vs_bundle_name);
     if ($va_placement['settings']['show_hierarchy'] || $pa_options['show_hierarchy']) {
         if ($va_tmp[1] == 'related') {
             array_splice($va_tmp, 2, 0, 'hierarchy');
         } else {
             array_splice($va_tmp, 1, 0, 'hierarchy');
         }
         $vs_bundle_name = join(".", $va_tmp);
         $pa_options['hierarchicalDelimiter'] = $va_placement['settings']['hierarchical_delimiter'] ? $va_placement['settings']['hierarchical_delimiter'] : null;
         $pa_options['direction'] = $va_placement['settings']['hierarchy_order'] ? $va_placement['settings']['hierarchy_order'] : null;
         $pa_options['bottom'] = $va_placement['settings']['hierarchy_limit'] ? $va_placement['settings']['hierarchy_limit'] : null;
         $pa_options['removeFirstItems'] = $va_placement['settings']['remove_first_items'] ? $va_placement['settings']['remove_first_items'] : null;
     }
     $pa_options['restrict_to_relationship_types'] = $va_placement['settings']['restrict_to_relationship_types'];
     $pa_options['restrict_to_types'] = $va_placement['settings']['restrict_to_types'];
     if (sizeof($va_tmp) == 1 || sizeof($va_tmp) == 2 && $va_tmp[1] == 'related') {
         $pa_options['template'] = $va_placement['settings']['format'] ? $va_placement['settings']['format'] : $this->getAppConfig()->get($va_tmp[0] . '_relationship_display_format');
     } else {
         $pa_options['template'] = $va_placement['settings']['format'] ? $va_placement['settings']['format'] : null;
     }
     $vs_val = '';
     if ($pa_options['template']) {
         if ($t_instance = $this->getAppDatamodel()->getInstanceByTableName($va_tmp[0], true)) {
             $va_tmp2 = $va_tmp;
             if (sizeof($va_tmp2) > 1 && in_array($vs_tmp = array_pop($va_tmp2), array('related'))) {
                 $va_tmp2[] = $vs_tmp;
             }
             $va_tmp2[] = $t_instance->primaryKey();
             $va_ids = $po_result->get(join('.', $va_tmp2), array('returnAsArray' => true));
             $va_links = array();
             if (is_array($va_ids)) {
                 $vs_val = caProcessTemplateForIDs($pa_options['template'], $va_tmp2[0], $va_ids, array_merge($pa_options, array('returnAsArray' => false)));
             }
         }
     } else {
         $vs_val = $po_result->get(join(".", $va_tmp), $pa_options);
     }
     if (isset($pa_options['purify']) && $pa_options['purify']) {
         $o_purifier = new HTMLPurifier();
         $vs_val = $o_purifier->purify($vs_val);
     }
     return $vs_val;
 }
示例#25
0
 /**
  * Get a record summary that is easier to parse when importing to another system
  */
 private function getItemInfoForImport()
 {
     if (!($t_instance = $this->_getTableInstance($this->ops_table, $this->opn_id))) {
         return false;
     }
     $o_dm = Datamodel::load();
     $t_list = new ca_lists();
     $t_locales = new ca_locales();
     //
     // Options
     //
     if (!($vs_delimiter = $this->opo_request->getParameter('delimiter', pString))) {
         $vs_delimiter = "; ";
     }
     if (!($vs_flatten = $this->opo_request->getParameter('flatten', pString))) {
         $vs_flatten = null;
     }
     $va_flatten = preg_split("![ ]*[;]+[ ]*!", $vs_flatten);
     $va_flatten = array_flip($va_flatten);
     $va_locales = $t_locales->getLocaleList(array("available_for_cataloguing_only" => true));
     $va_return = array();
     // allow user-defined template to be passed; allows flexible formatting of returned "display" value
     if (!($vs_template = $this->opo_request->getParameter('template', pString))) {
         $vs_template = '';
     }
     if ($vs_template) {
         $va_return['display'] = caProcessTemplateForIDs($vs_template, $this->ops_table, array($this->opn_id));
     }
     // "intrinsic" fields
     foreach ($t_instance->getFieldsArray() as $vs_field_name => $va_field_info) {
         $vs_list = null;
         if (!is_null($vs_val = $t_instance->get($vs_field_name))) {
             if (preg_match("/^hier\\_/", $vs_field_name)) {
                 continue;
             }
             if (preg_match("/\\_sort\$/", $vs_field_name)) {
                 continue;
             }
             if ($vs_field_name == $t_instance->primaryKey()) {
                 continue;
             }
             if (isset($va_field_info["LIST_CODE"])) {
                 // typical example: type_id
                 $va_item = $t_list->getItemFromListByItemID($va_field_info["LIST_CODE"], $vs_val);
                 if ($t_item = new ca_list_items($va_item["item_id"])) {
                     $vs_val = $t_item->get('idno');
                 }
             }
             $va_return['intrinsic'][$vs_field_name] = $vs_val;
         }
     }
     // preferred labels
     $va_labels = $t_instance->get($this->ops_table . ".preferred_labels", array("returnAllLocales" => true));
     $va_labels = end($va_labels);
     $vs_display_field_name = $t_instance->getLabelDisplayField();
     if (is_array($va_labels)) {
         foreach ($va_labels as $vn_locale_id => $va_labels_by_locale) {
             foreach ($va_labels_by_locale as $va_tmp) {
                 $va_label = array();
                 $va_label['locale'] = $va_locales[$vn_locale_id]["code"];
                 // add only UI fields to return
                 foreach (array_merge($t_instance->getLabelUIFields(), array('type_id')) as $vs_label_fld) {
                     $va_label[$vs_label_fld] = $va_tmp[$vs_label_fld];
                 }
                 $va_label[$vs_label_fld] = $va_tmp[$vs_label_fld];
                 $va_label['label'] = $va_tmp[$vs_display_field_name];
                 $va_return["preferred_labels"][$va_label['locale']] = $va_label;
             }
         }
         if (isset($va_flatten['locales'])) {
             $va_return["preferred_labels"] = array_pop(caExtractValuesByUserLocale(array($va_return["preferred_labels"])));
         }
     }
     // nonpreferred labels
     $va_labels = $t_instance->get($this->ops_table . ".nonpreferred_labels", array("returnAllLocales" => true));
     $va_labels = end($va_labels);
     if (is_array($va_labels)) {
         foreach ($va_labels as $vn_locale_id => $va_labels_by_locale) {
             foreach ($va_labels_by_locale as $va_tmp) {
                 $va_label = array();
                 $va_label['locale'] = $va_locales[$vn_locale_id]["code"];
                 // add only UI fields to return
                 foreach (array_merge($t_instance->getLabelUIFields(), array('type_id')) as $vs_label_fld) {
                     $va_label[$vs_label_fld] = $va_tmp[$vs_label_fld];
                 }
                 $va_return["nonpreferred_labels"][$va_label['locale']] = $va_label;
             }
         }
         if (isset($va_flatten['locales'])) {
             $va_return["nonpreferred_labels"] = array_pop(caExtractValuesByUserLocale(array($va_return["nonpreferred_labels"])));
         }
     }
     // attributes
     $va_codes = $t_instance->getApplicableElementCodes();
     foreach ($va_codes as $vs_code) {
         if ($va_vals = $t_instance->get($this->ops_table . "." . $vs_code, array("convertCodesToDisplayText" => false, "returnAllLocales" => true))) {
             $va_vals_as_text = end($t_instance->get($this->ops_table . "." . $vs_code, array("convertCodesToDisplayText" => true, "returnAllLocales" => true)));
             $va_vals_by_locale = end($va_vals);
             foreach ($va_vals_by_locale as $vn_locale_id => $va_locale_vals) {
                 foreach ($va_locale_vals as $vs_val_id => $va_actual_data) {
                     if (!is_array($va_actual_data)) {
                         continue;
                     }
                     $vs_locale_code = isset($va_locales[$vn_locale_id]["code"]) ? $va_locales[$vn_locale_id]["code"] : "none";
                     foreach ($va_actual_data as $vs_f => $vs_v) {
                         if (isset($va_vals_as_text[$vn_locale_id][$vs_val_id][$vs_f]) && $vs_v != $va_vals_as_text[$vn_locale_id][$vs_val_id][$vs_f]) {
                             $va_actual_data[$vs_f . '_display'] = $va_vals_as_text[$vn_locale_id][$vs_val_id][$vs_f];
                             if ($vs_item_idno = caGetListItemIdno($va_actual_data[$vs_f])) {
                                 $va_actual_data[$vs_f] = $vs_item_idno;
                             }
                         }
                     }
                     $va_return['attributes'][$vs_code][$vs_locale_code][] = array_merge(array('locale' => $vs_locale_code), $va_actual_data);
                 }
             }
         }
     }
     if (isset($va_flatten['locales'])) {
         $va_return['attributes'] = caExtractValuesByUserLocale($va_return['attributes']);
     }
     // relationships
     // yes, not all combinations between these tables have
     // relationships but it also doesn't hurt to query
     foreach ($this->opa_valid_tables as $vs_rel_table) {
         $t_rel = $o_dm->getInstanceByTableName($vs_rel_table, true);
         //
         // set-related hacks
         if ($this->ops_table == "ca_sets" && $vs_rel_table == "ca_tours") {
             // throw SQL error in getRelatedItems
             continue;
         }
         $va_related_items = $t_instance->get($vs_rel_table, array("returnAsArray" => true, 'returnLocaleCodes' => true, 'groupFields' => true));
         if ($this->ops_table == "ca_objects" && $vs_rel_table == "ca_object_representations") {
             $va_versions = $t_instance->getMediaVersions('media');
             if (isset($va_flatten['all'])) {
                 $va_reps = $t_instance->getRepresentations(array('original'));
                 $va_urls = array();
                 foreach ($va_reps as $vn_i => $va_rep) {
                     $va_urls[] = $va_rep['urls']['original'];
                 }
                 $va_return['representations'] = join($vs_delimiter, $va_urls);
             } else {
                 $va_return['representations'] = $t_instance->getRepresentations($va_versions);
             }
             foreach ($va_return['representations'] as $vn_i => $va_rep) {
                 unset($va_return['representations'][$vn_i]['media']);
                 unset($va_return['representations'][$vn_i]['media_metadata']);
             }
         }
         if (is_array($va_related_items) && sizeof($va_related_items) > 0) {
             foreach ($va_related_items as $va_rel_item) {
                 $va_item_add = array();
                 foreach ($va_rel_item as $vs_fld => $vs_val) {
                     if (!is_array($vs_val) && strlen(trim($vs_val)) > 0) {
                         // rewrite and ignore certain field names
                         switch ($vs_fld) {
                             case 'item_type_id':
                                 $va_item_add[$vs_fld] = $vs_val;
                                 $va_item_add['type_id'] = $vs_val;
                                 break;
                             default:
                                 $va_item_add[$vs_fld] = $vs_val;
                                 break;
                         }
                     } else {
                         if (in_array($vs_fld, array('preferred_labels', 'intrinsic'))) {
                             $va_item_add[$vs_fld] = $vs_val;
                         }
                     }
                 }
                 if ($vs_rel_table == "ca_object_representations") {
                     $t_rep = new ca_object_representations($va_rel_item['representation_id']);
                     $va_item_add['media'] = $t_rep->getMediaUrl('media', 'original');
                 }
                 $va_return["related"][$vs_rel_table][] = $va_item_add;
             }
         }
     }
     return $va_return;
 }
示例#26
0
 /**
  * Extract geographic data from a data object (model instance or search result) and load it for rendering
  *
  * @param $po_data_object BaseModel|SearchResult A model instance or search result object from which to extract data for the map
  * @param $ps_georeference_field_name string The name of the georeference or geonames attribute to plot map items with; should be in <table>.<element_code> format (eg. "ca_objects.map_coords")
  * @param $pa_options array Optional array of options; supported options include:
  *			label - attribute (or field) to use for a short label for the map point, in <table>.<element_code> format (eg. "ca_objects.idno" or "ca_objects.preferred_labels.name")
  *			content - attribute (or field) to use for info balloon content shown when map item is clicked, in <table>.<element_code> format (eg. "ca_objects.description"). The content of the field is used as-is, so you must apply any styling to the data before it is stored in the database. If you want to style content "on-the-fly" use contentView or contentTemplate
  *			contentTemplate - text template to use for info balloon content shown when map item is clicked; attributes in <table>.<element_code> format will be substituted when prefixed with a caret ("^"). Eg. "The title of this is ^ca_objects.preferred_labels.name and the date is ^ca_objects.creation_date"
  *			contentView - view to use to render info balloon content shown when map item is clicked; specify the view filename with path relative to the main view directory (eg. "Splash/splash_html.php"); the view will be passed a single variable, "data", containing the data object
  *			ajaxContentUrl - URL to use to load via AJAX in info balloon. The primary key of the item will be added to the URL as the "id" parameter. The AJAX handler referenced by the URL must return ready-to-display HTML suitable for display in an info balloon. Unlike all other balloon content options, ajaxContentUrl defers rendering of balloon content until viewed, and does not embed content in the initial HTML load. For these reasons it is usually the best performing and most scaleable option.
  *			checkAccess - array of access field values to filter data (item and representation level); omit or pass empty array to do no filtering
  *			viewPath - path to views; will use standard system view path if not defined
  *			request = current request; required for generation of editor links
  *			color = hex color to use for item marker; can include bundle display template tags for inclusion of colors stored in metadata elements
  * @return array Returns an array with two keys: 'points' = number of unique markers added to map; 'items' = number of result hits than were plotted at least once on the map
  */
 public function mapFrom($po_data_object, $ps_georeference_field_name, $pa_options = null)
 {
     $po_request = caGetOption('request', $pa_options, null);
     $pa_options['label'] = caGetOption('label', $pa_options, null);
     $pa_options['content'] = caGetOption('content', $pa_options, null);
     $vs_color = caGetOption('color', $pa_options, null);
     $vb_render_label_as_link = caGetOption('renderLabelAsLink', $pa_options, false);
     $vn_point_count = 0;
     $vn_item_count = 0;
     $va_tmp = explode('.', $ps_georeference_field_name);
     $vs_field_name = array_pop($va_tmp);
     $va_point_buf = array();
     //
     // Data object is a model instance?
     //
     if (is_subclass_of($po_data_object, 'BaseModel')) {
         if ($po_data_object->hasField('access') && isset($pa_options['checkAccess']) && is_array($pa_options['checkAccess']) && sizeof($pa_options['checkAccess'])) {
             if (!in_array($po_data_object->get('access'), $pa_options['checkAccess'])) {
                 return array('items' => 0, 'points' => 0);
             }
         }
         $vn_id = $po_data_object->getPrimaryKey();
         if (is_array($va_coordinates = $po_data_object->get($ps_georeference_field_name, array('coordinates' => true, 'returnAsArray' => true)))) {
             foreach ($va_coordinates as $vn_i => $va_geoname) {
                 $va_coordinate = isset($va_geoname[$vs_field_name]) ? $va_geoname[$vs_field_name] : $va_geoname;
                 $vs_label = $vs_content = $vs_ajax_content = null;
                 if (!is_null($pa_options['labelTemplate'])) {
                     $vs_label = caProcessTemplateForIDs($pa_options['labelTemplate'], $po_data_object->tableName(), array($vn_id), array('returnAsLink' => $vb_render_label_as_link || strpos($pa_options['contentTemplate'], "<l>") !== false));
                 } else {
                     if (!is_null($pa_options['label'])) {
                         $vs_label = $po_data_object->get($pa_options['label'], array('returnAsLink' => $vb_render_label_as_link || strpos($pa_options['contentTemplate'], "<l>") !== false));
                     } else {
                         $vs_label = $va_coordinate['label'];
                     }
                 }
                 if (!is_null($vs_color)) {
                     $vs_color = caProcessTemplateForIDs($vs_color, $po_data_object->tableName(), array($vn_id), array('returnAsLink' => false));
                 } else {
                     $vs_color = null;
                 }
                 if (isset($pa_options['ajaxContentUrl']) && $pa_options['ajaxContentUrl']) {
                     $vs_ajax_content = $pa_options['ajaxContentUrl'];
                 } else {
                     if (!is_null($pa_options['contentView']) && $pa_options['request']) {
                         $o_view = new View($pa_options['request'], isset($pa_options['viewPath']) && $pa_options['viewPath'] ? $pa_options['viewPath'] : $pa_options['request']->getViewsDirectoryPath());
                         $o_view->setVar('data', $po_data_object);
                         $o_view->setVar('access_values', $pa_options['checkAccess']);
                         $vs_content = $o_view->render($pa_options['contentView']);
                     } else {
                         if (!is_null($pa_options['contentTemplate'])) {
                             $vs_content = caProcessTemplateForIDs($pa_options['contentTemplate'], $po_data_object->tableName(), $po_data_object->get($po_data_object->tableName() . "." . $po_data_object->primaryKey(), array('returnAsArray' => true)), array('returnAsLink' => strpos($pa_options['contentTemplate'], "<l>") !== false));
                         } else {
                             if (!is_null($pa_options['content'])) {
                                 if ($pa_options['content']) {
                                     $vs_content = $po_data_object->get($pa_options['content']);
                                 }
                             } else {
                                 $vs_content = $va_coordinate['label'];
                             }
                         }
                     }
                 }
                 $va_path = explode(";", $va_coordinate['path']);
                 if (sizeof($va_path) > 1) {
                     $va_coordinate_pairs = array();
                     foreach ($va_path as $vs_pair) {
                         $va_pair = explode(',', $vs_pair);
                         $va_coordinate_pairs[] = array('latitude' => $va_pair[0], 'longitude' => $va_pair[1]);
                     }
                     $this->addMapItem(new GeographicMapItem(array('coordinates' => $va_coordinate_pairs, 'label' => $vs_label, 'content' => $vs_content, 'ajaxContentUrl' => $vs_ajax_content, 'ajaxContentID' => $vn_id, 'color' => $vs_color)));
                 } else {
                     $this->addMapItem(new GeographicMapItem(array('latitude' => $va_coordinate['latitude'], 'longitude' => $va_coordinate['longitude'], 'label' => $vs_label, 'content' => $vs_content, 'ajaxContentUrl' => $vs_ajax_content, 'ajaxContentID' => $vn_id, 'color' => $vs_color)));
                 }
                 if (!$va_point_buf[$va_coordinate['latitude'] . '/' . $va_coordinate['longitude']]) {
                     $vn_point_count++;
                 }
                 $va_point_buf[$va_coordinate['latitude'] . '/' . $va_coordinate['longitude']]++;
             }
             $vn_item_count++;
         }
         return array('items' => $vn_item_count, 'points' => $vn_point_count);
     }
     //
     // Data object is a search result?
     //
     if (is_subclass_of($po_data_object, 'SearchResult')) {
         $po_data_object->setOption('prefetch', 1000);
         $va_access_values = null;
         if (isset($pa_options['checkAccess']) && is_array($pa_options['checkAccess']) && sizeof($pa_options['checkAccess'])) {
             $va_access_values = $pa_options['checkAccess'];
         }
         $t_instance = $po_data_object->getResultTableInstance();
         $vs_table = $t_instance->tableName();
         $vs_pk = $t_instance->primaryKey();
         while ($po_data_object->nextHit()) {
             if ($va_access_values) {
                 if (!in_array($po_data_object->get('access'), $va_access_values)) {
                     continue;
                 }
             }
             if ($va_coordinates = $po_data_object->get($ps_georeference_field_name, array('coordinates' => true, 'returnAsArray' => true, 'returnAllLocales' => true))) {
                 $vn_id = $po_data_object->get("{$vs_table}.{$vs_pk}");
                 $vs_table = $po_data_object->tableName();
                 foreach ($va_coordinates as $vn_element_id => $va_geonames_by_locale) {
                     foreach ($va_geonames_by_locale as $vn_locale_id => $va_coord_list) {
                         foreach ($va_coord_list as $vn_attribute_id => $va_geoname) {
                             $va_coordinate = isset($va_geoname[$vs_field_name]) ? $va_geoname[$vs_field_name] : $va_geoname;
                             $vs_label = $vs_content = $vs_ajax_content = null;
                             if (!is_null($pa_options['labelTemplate'])) {
                                 $vs_label = caProcessTemplateForIDs($pa_options['labelTemplate'], $vs_table, array($vn_id), array('returnAsLink' => $vb_render_label_as_link || strpos($pa_options['contentTemplate'], "<l>") !== false));
                             } else {
                                 if (!is_null($pa_options['label'])) {
                                     $vs_label = $po_data_object->get($pa_options['label'], array('returnAsLink' => $vb_render_label_as_link || strpos($pa_options['contentTemplate'], "<l>") !== false));
                                 } else {
                                     $vs_label = $va_coordinate['label'];
                                 }
                             }
                             if (!is_null($pa_options['color'])) {
                                 $vs_color = caProcessTemplateForIDs($pa_options['color'], $vs_table, array($vn_id), array('returnAsLink' => false));
                             } else {
                                 $vs_color = null;
                             }
                             if (isset($pa_options['ajaxContentUrl']) && $pa_options['ajaxContentUrl']) {
                                 $vs_ajax_content = $pa_options['ajaxContentUrl'];
                             } else {
                                 if (!is_null($pa_options['contentView']) && $pa_options['request']) {
                                     $o_view = new View($pa_options['request'], isset($pa_options['viewPath']) && $pa_options['viewPath'] ? $pa_options['viewPath'] : $pa_options['request']->getViewsDirectoryPath());
                                     $o_view->setVar('data', $po_data_object);
                                     $o_view->setVar('access_values', $pa_options['checkAccess']);
                                     $vs_content = $o_view->render($pa_options['contentView']);
                                 } else {
                                     if (!is_null($pa_options['contentTemplate'])) {
                                         $vs_content = caProcessTemplateForIDs($pa_options['contentTemplate'], $po_data_object->tableName(), $po_data_object->get($po_data_object->tableName() . "." . $po_data_object->primaryKey(), array('returnAsArray' => true)), array('returnAsLink' => strpos($pa_options['contentTemplate'], "<l>") !== false));
                                     } else {
                                         if (!is_null($pa_options['content'])) {
                                             if ($pa_options['content']) {
                                                 $vs_content = $po_data_object->get($pa_options['content']);
                                             }
                                         } else {
                                             $vs_content = $va_coordinate['label'];
                                         }
                                     }
                                 }
                             }
                             $va_path = explode(";", $va_coordinate['path']);
                             if (sizeof($va_path) > 1) {
                                 $va_coordinate_pairs = array();
                                 foreach ($va_path as $vs_pair) {
                                     $va_pair = explode(',', $vs_pair);
                                     $va_coordinate_pairs[] = array('latitude' => $va_pair[0], 'longitude' => $va_pair[1]);
                                 }
                                 $this->addMapItem(new GeographicMapItem(array('coordinates' => $va_coordinate_pairs, 'label' => $vs_label, 'content' => $vs_content, 'ajaxContentUrl' => $vs_ajax_content, 'ajaxContentID' => $vn_id, 'color' => $vs_color)));
                             } else {
                                 $this->addMapItem(new GeographicMapItem(array('latitude' => $va_coordinate['latitude'], 'longitude' => $va_coordinate['longitude'], 'label' => $vs_label, 'content' => $vs_content, 'ajaxContentUrl' => $vs_ajax_content, 'ajaxContentID' => $vn_id, 'color' => $vs_color)));
                             }
                             if (!$va_point_buf[$va_coordinate['latitude'] . '/' . $va_coordinate['longitude']]) {
                                 $vn_point_count++;
                             }
                             $va_point_buf[$va_coordinate['latitude'] . '/' . $va_coordinate['longitude']]++;
                         }
                         $vn_item_count++;
                     }
                 }
             }
         }
     }
     return array('items' => $vn_item_count, 'points' => $vn_point_count);
 }
 * ----------------------------------------------------------------------
 */
AssetLoadManager::register('hierBrowser');
AssetLoadManager::register('tabUI');
$t_subject = $this->getVar('t_subject');
$vs_subject_label = $t_subject->getLabelForDisplay();
if (($vs_priv_table = $t_subject->tableName()) == 'ca_list_items') {
    $vs_priv_table = 'ca_lists';
}
// actions happen to be on names for ca_lists for ca_list_items
$pn_parent_id = $this->getVar('parent_id');
$pa_ancestors = $this->getVar('ancestors');
$pn_id = $this->getVar('id');
$vs_id_prefix = $this->getVar('placement_code') . $this->getVar('id_prefix');
$vn_items_in_hier = $t_subject->getHierarchySize();
$vs_bundle_preview = '(' . $vn_items_in_hier . ') ' . caProcessTemplateForIDs("^preferred_labels", $t_subject->tableName(), array($t_subject->getPrimaryKey()));
switch ($vs_priv_table) {
    case 'ca_relationship_types':
        $vb_has_privs = $this->request->user->canDoAction('can_configure_relationship_types');
        break;
    case 'ca_tour_stops':
        $vb_has_privs = $this->request->user->canDoAction('can_create_ca_tours');
        break;
    default:
        $vb_has_privs = $this->request->user->canDoAction('can_create_' . $vs_priv_table);
        break;
}
$vb_objects_x_collections_hierarchy_enabled = (bool) $t_subject->getAppConfig()->get('ca_objects_x_collections_hierarchy_enabled');
$vs_disabled_items_mode = $t_subject->getAppConfig()->get($t_subject->tableName() . '_hierarchy_browser_disabled_items_mode');
$vs_disabled_items_mode = $vs_disabled_items_mode ? $vs_disabled_items_mode : 'hide';
$t_object = new ca_objects();
示例#28
0
 /**
  * Given a item_id (request parameter 'id') returns a list of direct children for use in the hierarchy browser
  * Returned data is JSON format
  */
 public function GetHierarchyLevel()
 {
     header("Content-type: application/json");
     $ps_bundle = (string) $this->request->getParameter('bundle', pString);
     $pa_ids = explode(";", $ps_ids = $this->request->getParameter('id', pString));
     if (!sizeof($pa_ids)) {
         $pa_ids = array(null);
     }
     $t_item = $this->opo_item_instance;
     if (!$t_item->isHierarchical()) {
         return;
     }
     $va_level_data = array();
     foreach ($pa_ids as $pn_id) {
         $va_tmp = explode(":", $pn_id);
         $vn_id = $va_tmp[0];
         $vn_start = (int) $va_tmp[1];
         if ($vn_start < 0) {
             $vn_start = 0;
         }
         $va_items_for_locale = array();
         if (!$vn_id && method_exists($t_item, "getHierarchyList")) {
             $vn_id = (int) $this->request->getParameter('root_item_id', pInteger);
             $t_item->load($vn_id);
             // no id so by default return list of available hierarchies
             $va_items_for_locale = $t_item->getHierarchyList();
         } else {
             if ($t_item->load($vn_id)) {
                 // id is the id of the parent for the level we're going to return
                 $vs_table_name = $t_item->tableName();
                 $vs_label_table_name = $this->opo_item_instance->getLabelTableName();
                 $vs_label_display_field_name = $this->opo_item_instance->getLabelDisplayField();
                 $vs_pk = $this->opo_item_instance->primaryKey();
                 $va_additional_wheres = array();
                 $t_label_instance = $this->opo_item_instance->getLabelTableInstance();
                 if ($t_label_instance && $t_label_instance->hasField('is_preferred')) {
                     $va_additional_wheres[] = "(({$vs_label_table_name}.is_preferred = 1) OR ({$vs_label_table_name}.is_preferred IS NULL))";
                 }
                 $o_config = Configuration::load();
                 if (!is_array($va_sorts = $o_config->getList($this->ops_table_name . '_hierarchy_browser_sort_values')) || !sizeof($va_sorts)) {
                     $va_sorts = array();
                 }
                 foreach ($va_sorts as $vn_i => $vs_sort_fld) {
                     $va_tmp = explode(".", $vs_sort_fld);
                     if ($va_tmp[1] == 'preferred_labels') {
                         $va_tmp[0] = $vs_label_table_name;
                         if (!($va_tmp[1] = $va_tmp[2])) {
                             $va_tmp[1] = $vs_label_display_field_name;
                         }
                         unset($va_tmp[2]);
                         $va_sorts[$vn_i] = join(".", $va_tmp);
                     }
                 }
                 if (!in_array($vs_sort_dir = strtolower($o_config->get($this->ops_table_name . '_hierarchy_browser_sort_direction')), array('asc', 'desc'))) {
                     $vs_sort_dir = 'asc';
                 }
                 $va_items = array();
                 if (is_array($va_item_ids = $t_item->getHierarchyChildren($t_item->getPrimaryKey(), array('idsOnly' => true))) && sizeof($va_item_ids)) {
                     $qr_children = $t_item->makeSearchResult($t_item->tableName(), $va_item_ids);
                     $va_child_counts = $t_item->getHierarchyChildCountsForIDs($va_item_ids);
                     if (!($vs_item_template = trim($o_config->get("{$vs_table_name}_hierarchy_browser_display_settings")))) {
                         $vs_item_template = "^{$vs_table_name}.preferred_labels.{$vs_label_display_field_name}";
                     }
                     if (($vn_max_items_per_page = $this->request->getParameter('max', pInteger)) < 1 || $vn_max_items_per_page > 1000) {
                         $vn_max_items_per_page = 100;
                     }
                     $vn_c = 0;
                     while ($qr_children->nextHit()) {
                         $va_tmp = array($vs_pk => $vn_id = $qr_children->get($this->ops_table_name . '.' . $vs_pk), 'item_id' => $vn_id, 'parent_id' => $qr_children->get($this->ops_table_name . '.parent_id'), 'idno' => $qr_children->get($this->ops_table_name . '.idno'), $vs_label_display_field_name => $qr_children->get($this->ops_table_name . '.preferred_labels.' . $vs_label_display_field_name), 'locale_id' => $qr_children->get($this->ops_table_name . '.' . 'locale_id'));
                         if (!$va_tmp[$vs_label_display_field_name]) {
                             $va_tmp[$vs_label_display_field_name] = $va_tmp['idno'];
                         }
                         if (!$va_tmp[$vs_label_display_field_name]) {
                             $va_tmp[$vs_label_display_field_name] = '???';
                         }
                         $va_tmp['name'] = caProcessTemplateForIDs($vs_item_template, $vs_table_name, array($va_tmp[$vs_pk]), array('requireLinkTags' => true));
                         // Child count is only valid if has_children is not null
                         $va_tmp['children'] = isset($va_child_counts[$vn_id]) ? (int) $va_child_counts[$vn_id] : 0;
                         if (is_array($va_sorts)) {
                             $vs_sort_acc = array();
                             foreach ($va_sorts as $vs_sort) {
                                 $vs_sort_acc[] = $qr_children->get($vs_sort, array('sortable' => true));
                             }
                             $va_tmp['sort'] = join(";", $vs_sort_acc);
                         }
                         $va_items[$va_tmp[$vs_pk]][$va_tmp['locale_id']] = $va_tmp;
                         $vn_c++;
                     }
                     $va_items_for_locale = caExtractValuesByUserLocale($va_items);
                 }
                 $vs_rank_fld = $t_item->getProperty('RANK');
                 $va_sorted_items = array();
                 foreach ($va_items_for_locale as $vn_id => $va_node) {
                     $vs_key = preg_replace('![^A-Za-z0-9]!', '_', $va_node['name']);
                     if (isset($va_node['sort']) && $va_node['sort']) {
                         $va_sorted_items[$va_node['sort']][$vs_key] = $va_node;
                     } else {
                         if ($vs_rank_fld && ($vs_rank = (int) sprintf("%08d", $va_node[$vs_rank_fld]))) {
                             $va_sorted_items[$vs_rank][$vs_key] = $va_node;
                         } else {
                             $va_sorted_items[$vs_key][$vs_key] = $va_node;
                         }
                     }
                 }
                 ksort($va_sorted_items);
                 if ($vs_sort_dir == 'desc') {
                     $va_sorted_items = array_reverse($va_sorted_items);
                 }
                 $va_items_for_locale = array();
                 $va_sorted_items = array_slice($va_sorted_items, $vn_start, $vn_max_items_per_page);
                 foreach ($va_sorted_items as $vs_k => $va_v) {
                     ksort($va_v);
                     if ($vs_sort_dir == 'desc') {
                         $va_v = array_reverse($va_v);
                     }
                     $va_items_for_locale = array_merge($va_items_for_locale, $va_v);
                 }
             }
         }
         $va_items_for_locale['_primaryKey'] = $t_item->primaryKey();
         // pass the name of the primary key so the hierbrowser knows where to look for item_id's
         $va_items_for_locale['_itemCount'] = $qr_children ? $qr_children->numHits() : 0;
         $va_level_data[$pn_id] = $va_items_for_locale;
     }
     if (!$this->request->getParameter('init', pInteger)) {
         // only set remember "last viewed" if the load is done interactively
         // if the GetHierarchyLevel() call is part of the initialization of the hierarchy browser
         // then all levels are loaded, sometimes out-of-order; if we record these initialization loads
         // as the 'last viewed' we can end up losing the true 'last viewed' value
         //
         // ... so the hierbrowser passes an extra 'init' parameters set to 1 if the GetHierarchyLevel() call
         // is part of a browser initialization
         $this->request->session->setVar($this->ops_table_name . '_' . $ps_bundle . '_browse_last_id', array_pop($pa_ids));
     }
     $this->view->setVar(str_replace(' ', '_', $this->ops_name_singular) . '_list', $va_level_data);
     return $this->render(str_replace(' ', '_', $this->ops_name_singular) . '_hierarchy_level_json.php');
 }
示例#29
0
/**
 * Converts result set into display labels for relationship lookup
 *
 * @param SearchResult $qr_rel_items 
 * @param BaseModel $pt_rel
 * @param array $pa_options Array of options, including:
 *		stripTags = default is false
 * 		exclude = list of primary key values to omit from returned list
 *		config = 
 *		limit = maximum number of items to return; if omitted all items are returned
 *		inlineCreateMessage = 
 *		inlineCreateQuery =
 *		inlineCreateMessageDoesNotExist =
 *		template = 
 *		primaryIDs = row_ids for primary rows in related table, keyed by table name; when resolving ambiguous relationships the row_ids will be excluded from consideration. This option is rarely used and exists primarily to take care of a single
 *						edge case: you are processing a template relative to a self-relationship such as ca_entities_x_entities that includes references to the subject table (ca_entities, in the case of ca_entities_x_entities). There are
 *						two possible paths to take in this situations; primaryIDs lets you specify which ones you *don't* want to take by row_id. For interstitial editors, the ids will be set to a single id: that of the subject (Eg. ca_entities) row
 *						from which the interstitial was launched.
 * @return mixed 
 */
function caProcessRelationshipLookupLabel($qr_rel_items, $pt_rel, $pa_options = null)
{
    $va_initial_values = array();
    $vs_hier_fld = $pt_rel->getProperty('HIERARCHY_ID_FLD');
    $vs_idno_fld = $pt_rel->getProperty('ID_NUMBERING_ID_FIELD');
    $vs_idno_sort_fld = $pt_rel->getProperty('ID_NUMBERING_SORT_FIELD');
    $vs_rel_pk = caGetOption('primaryKey', $pa_options, $pt_rel->primaryKey());
    $vs_rel_table = caGetOption('table', $pa_options, $pt_rel->tableName());
    $o_config = !isset($pa_options['config']) || !is_object($pa_options['config']) ? Configuration::load() : $pa_options['config'];
    $pn_limit = caGetOption('limit', $pa_options, null);
    $ps_inline_create_message = caGetOption('inlineCreateMessage', $pa_options, null);
    $ps_inline_create_does_not_exist_message = caGetOption('inlineCreateMessageDoesNotExist', $pa_options, null);
    $ps_inline_create_query = caGetOption('inlineCreateQuery', $pa_options, null);
    $ps_inline_create_query_lc = mb_strtolower($ps_inline_create_query);
    $ps_empty_result_message = caGetOption('emptyResultMessage', $pa_options, null);
    $ps_empty_result_query = caGetOption('emptyResultQuery', $pa_options, null);
    $vs_template = caGetOption('template', $pa_options, null);
    $va_exclude = caGetOption('exclude', $pa_options, array(), array('castTo' => 'array'));
    $va_display_format = $o_config->getList("{$vs_rel_table}_lookup_settings");
    $vs_display_delimiter = $o_config->get("{$vs_rel_table}_lookup_delimiter");
    if (!$vs_template) {
        $vs_template = join($vs_display_delimiter, $va_display_format);
    }
    $va_related_item_info = $va_parent_ids = $va_hierarchy_ids = array();
    $va_items = array();
    $o_dm = Datamodel::load();
    $t_rel = $o_dm->getInstanceByTableName($vs_rel_table, true);
    $vs_type_id_fld = method_exists($t_rel, 'getTypeFieldName') ? $t_rel->getTypeFieldName() : null;
    $vn_c = 0;
    $vb_include_inline_add_does_not_exist_message = $vb_include_empty_result_message = false;
    $vb_include_inline_add_message = true;
    if (is_object($qr_rel_items)) {
        if (!$qr_rel_items->numHits()) {
            if ($ps_inline_create_does_not_exist_message) {
                $vb_include_inline_add_does_not_exist_message = true;
                $vb_include_inline_add_message = false;
            } else {
                if ($ps_empty_result_message) {
                    $vb_include_empty_result_message = true;
                }
            }
        } else {
            $vs_table = $qr_rel_items->tableName();
            $vs_pk = $qr_rel_items->primaryKey();
            $va_primary_ids = method_exists($pt_rel, "isSelfRelationship") && ($vb_is_self_rel = $pt_rel->isSelfRelationship()) ? caGetOption("primaryIDs", $pa_options, null) : null;
            while ($qr_rel_items->nextHit()) {
                $vn_id = $qr_rel_items->get("{$vs_rel_table}.{$vs_rel_pk}");
                if (in_array($vn_id, $va_exclude)) {
                    continue;
                }
                $va_item = array('id' => $vn_id, $vs_rel_pk => $vn_id);
                if ($vs_type_id_fld) {
                    $va_item['type_id'] = $qr_rel_items->get("{$vs_rel_table}.{$vs_type_id_fld}");
                }
                $va_item['_display'] = caProcessTemplateForIDs($vs_template, $vs_table, array($qr_rel_items->get("{$vs_table}.{$vs_pk}")), array('returnAsArray' => false, 'returnAsLink' => false, 'delimiter' => caGetOption('delimiter', $pa_options, $vs_display_delimiter), 'resolveLinksUsing' => $vs_rel_table, 'primaryIDs' => $va_primary_ids));
                $va_item['label'] = mb_strtolower($qr_rel_items->get("{$vs_table}.preferred_labels"));
                $va_items[$vn_id] = $va_item;
                $vn_c++;
                if ($pn_limit && $pn_limit <= $vn_c) {
                    break;
                }
            }
        }
    }
    if (isset($pa_options['relatedItems']) && is_array($pa_options['relatedItems']) && sizeof($pa_options['relatedItems'])) {
        $va_tmp = array();
        foreach ($pa_options['relatedItems'] as $vn_relation_id => $va_relation) {
            $va_items[$va_relation[$vs_rel_pk]]['relation_id'] = $va_relation['relation_id'];
            $va_items[$va_relation[$vs_rel_pk]]['relationship_type_id'] = $va_items[$va_relation[$vs_rel_pk]]['type_id'] = $va_relation['direction'] ? $va_relation['direction'] . '_' . $va_relation['relationship_type_id'] : $va_relation['relationship_type_id'];
            $va_items[$va_relation[$vs_rel_pk]]['rel_type_id'] = $va_relation['relationship_type_id'];
            $va_items[$va_relation[$vs_rel_pk]]['relationship_typename'] = $va_relation['relationship_typename'];
            $va_items[$va_relation[$vs_rel_pk]]['idno'] = $va_relation[$vs_idno_fld];
            $va_items[$va_relation[$vs_rel_pk]]['idno_sort'] = $va_relation[$vs_idno_sort_fld];
            $va_items[$va_relation[$vs_rel_pk]]['label'] = $va_relation['label'];
            $va_items[$va_relation[$vs_rel_pk]]['direction'] = $va_relation['direction'];
            $va_items[$va_relation[$vs_rel_pk]]['effective_date'] = $va_relation['effective_date'];
            if (isset($va_relation['surname'])) {
                // pass forename and surname entity label fields to support proper sorting by name
                $va_items[$va_relation[$vs_rel_pk]]['surname'] = $va_relation['surname'];
                $va_items[$va_relation[$vs_rel_pk]]['forename'] = $va_relation['forename'];
            }
            if (!isset($va_items[$va_relation[$vs_rel_pk]][$vs_rel_pk]) || !$va_items[$va_relation[$vs_rel_pk]][$vs_rel_pk]) {
                $va_items[$va_relation[$vs_rel_pk]][$vs_rel_pk] = $va_items[$va_relation[$vs_rel_pk]]['id'] = $va_relation[$vs_rel_pk];
            }
            if ($vs_template) {
                $va_items[$va_relation[$vs_rel_pk]]['_display'] = caProcessTemplateForIDs($vs_template, $pt_rel->tableName(), array($va_relation['relation_id'] ? $va_relation['relation_id'] : $va_relation[$vs_pk]), array('returnAsArray' => false, 'returnAsLink' => false, 'delimiter' => caGetOption('delimiter', $pa_options, $vs_display_delimiter), 'resolveLinksUsing' => $vs_rel_table, 'primaryIDs' => $va_primary_ids));
            } else {
                $va_items[$va_relation[$vs_rel_pk]]['_display'] = $va_items[$va_relation[$vs_rel_pk]]['label'];
            }
            $va_tmp[$vn_relation_id] = $va_items[$va_relation[$vs_rel_pk]];
        }
        $va_items = $va_tmp;
        unset($va_tmp);
    }
    foreach ($va_items as $va_item) {
        $vn_id = $va_item[$vs_rel_pk];
        if (in_array($vn_id, $va_exclude)) {
            continue;
        }
        $vs_display = $va_item['_display'];
        if (isset($pa_options['stripTags']) && $pa_options['stripTags']) {
            if (preg_match('!(<[A-Za-z0-9]+[ ]+[A-Za-z0-9 ,;\\&\\-_]*>)!', $vs_display, $va_matches)) {
                // convert text in <> to non-tags if the text has only letters, numbers and spaces in it
                array_shift($va_matches);
                foreach ($va_matches as $vs_match) {
                    $vs_display = str_replace($vs_match, htmlspecialchars($vs_match), $vs_display);
                }
            }
            $vs_display = trim(strip_tags($vs_display));
            $vs_label = $va_item['label'];
            if (preg_match('!(<[A-Za-z0-9]+[ ]+[A-Za-z0-9 ,;\\&\\-_]*>)!', $vs_label, $va_matches)) {
                // convert text in <> to non-tags if the text has only letters, numbers and spaces in it
                array_shift($va_matches);
                foreach ($va_matches as $vs_match) {
                    $vs_label = str_replace($vs_match, htmlspecialchars($vs_match), $vs_label);
                }
            }
            $va_item['label'] = trim(strip_tags($vs_label));
        }
        $vs_display_lc = mb_strtolower($vs_display);
        if ($vs_display_lc == $ps_inline_create_query_lc || isset($va_item['label']) && $va_item['label'] == $ps_inline_create_query_lc) {
            $vb_include_inline_add_message = false;
        }
        $po_request = caGetOption('request', $pa_options);
        if ($po_request && ca_editor_uis::loadDefaultUI($pt_rel->tableName(), $po_request, $va_item['rel_type_id'])) {
            $va_item['hasInterstitialUI'] = true;
        } else {
            $va_item['hasInterstitialUI'] = false;
        }
        $va_initial_values[$va_item['relation_id'] ? (int) $va_item['relation_id'] : $va_item[$vs_rel_pk]] = array_merge($va_item, array('label' => $vs_display));
    }
    if ($vb_include_inline_add_message && $ps_inline_create_message) {
        array_push($va_initial_values, array('label' => $ps_inline_create_message, 'id' => 0, $vs_rel_pk => 0, '_query' => $ps_inline_create_query));
    } elseif ($vb_include_inline_add_does_not_exist_message && $ps_inline_create_does_not_exist_message) {
        array_push($va_initial_values, array('label' => $ps_inline_create_does_not_exist_message, 'id' => 0, $vs_rel_pk => 0, '_query' => $ps_inline_create_query));
    } elseif ($vb_include_empty_result_message) {
        array_push($va_initial_values, array('label' => $ps_empty_result_message, 'id' => -1, $vs_rel_pk => -1, '_query' => $ps_empty_result_query));
    }
    return $va_initial_values;
}
示例#30
0
 /**
  *
  */
 public function getWithTemplateForResults($ps_template, $pa_options = null)
 {
     $pn_start = caGetOption('start', $pa_options, 0);
     $this->seek($pn_start);
     return caProcessTemplateForIDs($ps_template, $this->ops_table_name, $this->getRowIDsToPrefetch($pn_start, $this->numHits()), array_merge($pa_options, array('returnAsArray' => true)));
 }