/**
 * Returns array of name for bundles in the specified form. The array is keyed on bundle name (in <table>.<name> format) with values set to arrays of bundle-specific form options (no such options are currently supported however)
 *
 * @param string $ps_code The code for the form
 * @param string $ps_target The type of search the form targets. This should be a table name (ca_objects, ca_entities, etc.). If omitted defaults to ca_objects.
 * @return array An array of bundle names with associated bundle-level form option arrays
 */
function caGetAdvancedSearchFormElementNames($ps_code, $ps_target = 'ca_objects', $pa_options = null)
{
    $o_config = Configuration::load(Configuration::load()->get('advanced_search_config'));
    $va_forms = $o_config->getAssoc($ps_target);
    $va_form_elements = array();
    if (isset($va_forms[$ps_code]) && is_array($va_forms[$ps_code])) {
        $t_element = new ca_metadata_elements();
        foreach ($va_forms[$ps_code]['bundles'] as $vs_bundle => $va_info) {
            $va_tmp = explode('.', $vs_bundle);
            if ($t_element->load(array('element_code' => $va_tmp[1]))) {
                if ($t_element->get('datatype') > 0) {
                    $va_form_elements[$vs_bundle] = $va_info;
                    continue;
                }
                if (isset($pa_options['includeSubElements']) && $pa_options['includeSubElements']) {
                    if (sizeof($va_sub_elements = $t_element->getElementsInSet()) > 1) {
                        foreach ($va_sub_elements as $vn_element_id => $va_element_info) {
                            if ($va_tmp[1] == $va_element_info['element_code']) {
                                continue;
                            }
                            if ($va_element_info['datatype'] == 0) {
                                continue;
                            }
                            $va_form_elements[$va_tmp[0] . '.' . $va_element_info['element_code']] = array();
                        }
                    }
                }
            }
            $va_form_elements[$vs_bundle] = $va_info;
        }
        return $va_form_elements;
    }
    return null;
}
Example #2
0
 public function testGetElementIDsForTable()
 {
     $o_mapping = new ElasticSearch\Mapping();
     $va_element_ids = $o_mapping->getElementIDsForTable('ca_objects');
     foreach (array_keys(ca_metadata_elements::getElementsAsList(true, 'ca_objects')) as $vn_element_id) {
         $this->assertTrue(in_array($vn_element_id, $va_element_ids), "Expected element id {$vn_element_id} to be part of " . print_r($va_element_ids, true));
     }
 }
Example #3
0
 /**
  * @param string $ps_table
  * @param string $ps_content_fieldname
  * @return \ElasticSearch\FieldTypes\FieldType
  */
 public static function getInstance($ps_table, $ps_content_fieldname)
 {
     if ($ps_table == 'created' || $ps_table == 'modified') {
         return new Timestamp($ps_table);
     }
     // if this is an indexing field name, rewrite it
     if (preg_match("/^(I|A)[0-9]+\$/", $ps_content_fieldname)) {
         if ($ps_content_fieldname[0] === 'A') {
             // Metadata attribute
             $vn_field_num_proc = (int) substr($ps_content_fieldname, 1);
             $t_element = new \ca_metadata_elements($vn_field_num_proc);
             if (!$t_element->getPrimaryKey()) {
                 return null;
             }
             $ps_content_fieldname = $t_element->get('element_code');
         } else {
             // Plain intrinsic
             $vn_field_num_proc = (int) substr($ps_content_fieldname, 1);
             $ps_content_fieldname = \Datamodel::load()->getFieldName($ps_table, $vn_field_num_proc);
         }
     }
     if ($vn_datatype = \ca_metadata_elements::getDataTypeForElementCode($ps_content_fieldname)) {
         switch ($vn_datatype) {
             case 2:
                 return new DateRange($ps_table, $ps_content_fieldname);
             case 4:
                 return new Geocode($ps_table, $ps_content_fieldname);
             case 6:
                 return new Currency($ps_table, $ps_content_fieldname);
             case 8:
                 return new Length($ps_table, $ps_content_fieldname);
             case 9:
                 return new Weight($ps_table, $ps_content_fieldname);
             case 10:
                 return new Timecode($ps_table, $ps_content_fieldname);
             case 11:
                 return new Integer($ps_table, $ps_content_fieldname);
             case 12:
                 return new Float($ps_table, $ps_content_fieldname);
             default:
                 return new GenericElement($ps_table, $ps_content_fieldname);
         }
     } else {
         return new Intrinsic($ps_table, $ps_content_fieldname);
     }
 }
 public function __call($ps_function, $pa_args)
 {
     $ps_function = strtolower($ps_function);
     if (!($va_form_info = $this->_checkForm($ps_function))) {
         return;
     }
     $this->view->setVar('t_subject', $t_subject = $this->pt_subject);
     $va_tags = $this->view->getTagList($va_form_info['view']);
     foreach ($va_tags as $vs_tag) {
         if (in_array($vs_tag, array('form', '/form', 'submit', 'reset'))) {
             continue;
         }
         $va_parse = caParseTagOptions($vs_tag);
         $vs_tag_proc = $va_parse['tag'];
         $va_opts = $va_parse['options'];
         if (($vs_default_value = caGetOption('default', $va_opts, null)) || ($vs_default_value = caGetOption($vs_tag_proc, $va_default_form_values, null))) {
             $va_default_form_values[$vs_tag_proc] = $vs_default_value;
             unset($va_opts['default']);
         }
         $vs_tag_val = null;
         switch (strtolower($vs_tag_proc)) {
             case 'submit':
                 $this->view->setVar($vs_tag, "<a href='#' class='caContributeFormSubmit'>" . (isset($va_opts['label']) && $va_opts['label'] ? $va_opts['label'] : _t('Submit')) . "</a>");
                 break;
             case 'reset':
                 $this->view->setVar($vs_tag, "<a href='#' class='caContributeFormReset'>" . (isset($va_opts['label']) && $va_opts['label'] ? $va_opts['label'] : _t('Reset')) . "</a>");
                 $vs_script = "<script type='text/javascript'>\n\tjQuery('.caContributeFormSubmit').bind('click', function() {\n\t\tjQuery('#caContribute').submit();\n\t\treturn false;\n\t});\n\tjQuery('.caContributeFormReset').bind('click', function() {\n\t\tjQuery('#caContribute').find('input[type!=\"hidden\"],textarea').val('');\n\t\tjQuery('#caContribute').find('select.caContributeBoolean').val('AND');\n\t\tjQuery('#caContribute').find('select').prop('selectedIndex', 0);\n\t\treturn false;\n\t});\n\tjQuery(document).ready(function() {\n\t\tvar f, defaultValues = " . json_encode($va_default_form_values) . ", defaultBooleans = " . json_encode($va_default_form_booleans) . ";\n\t\tfor (f in defaultValues) {\n\t\t\tvar f_proc = f + '[]';\n\t\t\tjQuery('input[name=\"' + f_proc+ '\"], textarea[name=\"' + f_proc+ '\"], select[name=\"' + f_proc+ '\"]').each(function(k, v) {\n\t\t\t\tif (defaultValues[f][k]) { jQuery(v).val(defaultValues[f][k]); } \n\t\t\t});\n\t\t}\n\t\tfor (f in defaultBooleans) {\n\t\t\tvar f_proc = f + '[]';\n\t\t\tjQuery('select[name=\"' + f_proc+ '\"].caContributeBoolean').each(function(k, v) {\n\t\t\t\tif (defaultBooleans[f][k]) { jQuery(v).val(defaultBooleans[f][k]); }\n\t\t\t});\n\t\t}\n\t});\n</script>\n";
                 break;
             default:
                 if (preg_match("!^(.*):label\$!", $vs_tag_proc, $va_matches)) {
                     $this->view->setVar($vs_tag, $vs_tag_val = $t_subject->getDisplayLabel($va_matches[1]));
                 } else {
                     $va_opts['asArrayElement'] = true;
                     if ($vs_tag_val = $t_subject->htmlFormElementForSimpleForm($this->request, $vs_tag_proc, $va_opts)) {
                         $this->view->setVar($vs_tag, $vs_tag_val);
                     }
                     $va_tmp = explode('.', $vs_tag_proc);
                     if (($t_element = ca_metadata_elements::getInstance($va_tmp[1])) && $t_element->get('datatype') == 0) {
                         if (is_array($va_elements = $t_element->getElementsInSet())) {
                             foreach ($va_elements as $va_element) {
                                 if ($va_element['datatype'] > 0) {
                                     $va_form_elements[] = $va_tmp[0] . '.' . $va_tmp[1] . '.' . $va_element['element_code'];
                                 }
                             }
                         }
                         break;
                     }
                 }
                 if ($vs_tag_val) {
                     $va_form_elements[] = $vs_tag_proc;
                 }
                 break;
         }
     }
     $this->view->setVar("form", caFormTag($this->request, "Send", 'caContribute', null, 'post', 'multipart/form-data', '_top', array('disableUnsavedChangesWarning' => true)));
     $this->view->setVar("/form", $vs_script . caHTMLHiddenInput("_contributeFormName", array("value" => $ps_function)) . caHTMLHiddenInput("_formElements", array("value" => join(';', $va_form_elements))) . caHTMLHiddenInput("_contribute", array("value" => 1)) . "</form>");
     $this->render($va_form_info['view']);
 }
 public function __construct(&$po_request, &$po_response, $pa_view_paths = null)
 {
     parent::__construct($po_request, $po_response, $pa_view_paths);
     $va_sortable_elements = ca_metadata_elements::getSortableElements($this->ops_tablename, $this->opn_type_restriction_id);
     $this->opa_sorts = array();
     foreach ($va_sortable_elements as $vn_element_id => $va_sortable_element) {
         $this->opa_sorts[$this->ops_tablename . '.' . $va_sortable_element['element_code']] = $va_sortable_element['display_label'];
     }
 }
 public function Get($pa_additional_query_params = null, $pa_options = null)
 {
     $ps_query = $this->request->getParameter('q', pString);
     $ps_bundle = $this->request->getParameter('bundle', pString);
     $va_tmp = explode('.', $ps_bundle);
     $o_dm = Datamodel::load();
     if (!($t_table = $o_dm->getInstanceByTableName($va_tmp[0], true))) {
         // bad table name
         print _t("Invalid table name");
         return null;
     }
     $t_element = new ca_metadata_elements();
     if (!$t_element->load(array('element_code' => $va_tmp[1]))) {
         print _t("Invalid element code");
         return null;
     }
     if ((int) $t_element->getSetting('suggestExistingValues') !== 1) {
         print _t("Value suggestion is not supported for this metadata element");
         return null;
     }
     $va_type_restrictions = $t_element->getTypeRestrictions($t_table->tableNum());
     if (!$va_type_restrictions || !is_array($va_type_restrictions) || !sizeof($va_type_restrictions)) {
         print _t("Element code is not bound to the specified table");
         return null;
     }
     $o_db = new Db();
     switch ($t_element->getSetting('suggestExistingValueSort')) {
         case 'recent':
             // date/time entered
             $vs_sort_field = 'value_id DESC';
             $vn_max_returned_values = 10;
             break;
         default:
             // alphabetically
             $vs_sort_field = 'value_longtext1 ASC';
             $vn_max_returned_values = 50;
             break;
     }
     $qr_res = $o_db->query("\n\t\t\t\tSELECT DISTINCT value_longtext1\n\t\t\t\tFROM ca_attribute_values\n\t\t\t\tWHERE\n\t\t\t\t\telement_id = ?\n\t\t\t\t\tAND\n\t\t\t\t\t(value_longtext1 LIKE ?)\n\t\t\t\tORDER BY\n\t\t\t\t\t{$vs_sort_field}\n\t\t\t\tLIMIT {$vn_max_returned_values}\n\t\t\t", (int) $t_element->getPrimaryKey(), (string) $ps_query . '%');
     $this->view->setVar('attribute_value_list', $qr_res->getAllFieldValues('value_longtext1'));
     return $this->render('lookup/ajax_attribute_value_list_html.php');
 }
Example #7
0
 public function Get()
 {
     $ps_query = $this->request->getParameter('q', pString);
     $ps_type = $this->request->getParameter('type', pString);
     $va_vocs = array();
     $vs_voc_query = '';
     if ($vn_element_id = $this->request->getParameter('element_id', pInteger)) {
         $t_element = new ca_metadata_elements($vn_element_id);
         if ($vs_voc = $t_element->getSetting('vocabulary')) {
             $vs_voc_query .= '&q=' . urlencode($vs_voc);
         }
     }
     $va_items = array();
     if (unicode_strlen($ps_query) >= 3) {
         try {
             //
             // Get up to 50 suggestions as ATOM feed
             //
             $vs_data = @file_get_contents($x = "http://id.loc.gov/search/?q=" . urlencode($ps_query) . $vs_voc_query . '&format=atom&count=50');
             if ($vs_data) {
                 $o_xml = @simplexml_load_string($vs_data);
                 if ($o_xml) {
                     $o_entries = $o_xml->{'entry'};
                     if ($o_entries && sizeof($o_entries)) {
                         foreach ($o_entries as $o_entry) {
                             $o_links = $o_entry->{'link'};
                             $va_attr = $o_links[0]->attributes();
                             $vs_url = (string) $va_attr->{'href'};
                             $va_items[$vs_url] = array('displayname' => (string) $o_entry->{'title'}, 'idno' => (string) $o_entry->{'id'});
                         }
                     }
                 }
             }
         } catch (Exception $e) {
             $va_items['error'] = array('displayname' => _t('ERROR') . ':' . $e->getMessage(), 'idno' => '');
         }
     }
     $this->view->setVar('lcsh_list', $va_items);
     return $this->render('ajax_lcsh_list_html.php');
 }
 public function Get($pa_additional_query_params = null, $pa_options = null)
 {
     if (!($ps_query = $this->request->getParameter('q', pString))) {
         $ps_query = $this->request->getParameter('term', pString);
     }
     $ps_type = $this->request->getParameter('type', pString);
     $va_vocs = array();
     $vs_voc_query = '';
     if ($vn_element_id = $this->request->getParameter('element_id', pInteger)) {
         $t_element = new ca_metadata_elements($vn_element_id);
         if ($vs_voc = $t_element->getSetting('vocabulary')) {
             $vs_voc_query .= '&q=' . rawurlencode($vs_voc);
         }
     }
     $vo_conf = Configuration::load();
     $va_items = array();
     if (unicode_strlen($ps_query) >= 3) {
         try {
             $vs_data = caQueryExternalWebservice('http://id.loc.gov/search/?q=' . urlencode('"' . $ps_query . '"') . $vs_voc_query . '&format=atom&count=150');
             if ($vs_data) {
                 $o_xml = @simplexml_load_string($vs_data);
                 if ($o_xml) {
                     $o_entries = $o_xml->{'entry'};
                     if ($o_entries && sizeof($o_entries)) {
                         foreach ($o_entries as $o_entry) {
                             $o_links = $o_entry->{'link'};
                             $va_attr = $o_links[0]->attributes();
                             $vs_url = (string) $va_attr->{'href'};
                             $va_items[] = array('label' => (string) $o_entry->{'title'}, 'idno' => (string) $o_entry->{'id'}, 'url' => $vs_url);
                         }
                     }
                 }
             }
         } catch (Exception $e) {
             $va_items['error'] = array('displayname' => _t('ERROR') . ':' . $e->getMessage(), 'idno' => '');
         }
     }
     $this->view->setVar('lcsh_list', $va_items);
     return $this->render('ajax_lcsh_list_html.php');
 }
Example #9
0
 /**
  * Return list of items from the specified table that are related to the current browse set. This is the method that actually
  * pulls the facet content, regardless of whether the facet is cached yet or not. If you want to use the facet cache, call
  * BrowseEngine::getFacet()
  *
  * @see BrowseEngine::getFacet()
  * Options:
  *		checkAccess = array of access values to filter facets that have an 'access' field by
  *		checkAvailabilityOnly = if true then content is not actually fetch - only the availablility of content is verified
  *		user_id = If set item level access control is performed relative to specified user_id, otherwise defaults to logged in user
  */
 public function getFacetContent($ps_facet_name, $pa_options = null)
 {
     global $AUTH_CURRENT_USER_ID;
     $vs_browse_table_name = $this->ops_browse_table_name;
     $vs_browse_table_num = $this->opn_browse_table_num;
     $vn_user_id = isset($pa_options['user_id']) && (int) $pa_options['user_id'] ? (int) $pa_options['user_id'] : (int) $AUTH_CURRENT_USER_ID;
     $vb_show_if_no_acl = (bool) ($this->opo_config->get('default_item_access_level') > __CA_ACL_NO_ACCESS__);
     $t_user = new ca_users($vn_user_id);
     if (is_array($va_groups = $t_user->getUserGroups()) && sizeof($va_groups)) {
         $va_group_ids = array_keys($va_groups);
     } else {
         $va_group_ids = array();
     }
     if (!is_array($this->opa_browse_settings)) {
         return null;
     }
     if (!isset($this->opa_browse_settings['facets'][$ps_facet_name])) {
         return null;
     }
     if (!is_array($pa_options)) {
         $pa_options = array();
     }
     $vb_check_availability_only = isset($pa_options['checkAvailabilityOnly']) ? (bool) $pa_options['checkAvailabilityOnly'] : false;
     $va_all_criteria = $this->getCriteria();
     $va_criteria = $this->getCriteria($ps_facet_name);
     $va_facet_info = $this->opa_browse_settings['facets'][$ps_facet_name];
     $t_subject = $this->getSubjectInstance();
     if ($va_facet_info['relative_to']) {
         $vs_browse_table_name = $va_facet_info['relative_to'];
         $vs_browse_table_num = $this->opo_datamodel->getTableNum($vs_browse_table_name);
     }
     $vs_browse_type_limit_sql = '';
     if (($va_browse_type_ids = $this->getTypeRestrictionList()) && sizeof($va_browse_type_ids)) {
         // type restrictions
         $vs_browse_type_limit_sql = '(' . $t_subject->tableName() . '.' . $t_subject->getTypeFieldName() . ' IN (' . join(', ', $va_browse_type_ids) . ')' . ($t_subject->getFieldInfo('type_id', 'IS_NULL') ? " OR (" . $this->ops_browse_table_name . '.' . $t_subject->getTypeFieldName() . " IS NULL)" : '') . ')';
         if (is_array($va_facet_info['type_restrictions'])) {
             // facet type restrictions bind a facet to specific types; we check them here
             $va_restrict_to_types = $this->_convertTypeCodesToIDs($va_facet_info['type_restrictions']);
             $vb_is_ok_to_browse = false;
             foreach ($va_browse_type_ids as $vn_type_id) {
                 if (in_array($vn_type_id, $va_restrict_to_types)) {
                     $vb_is_ok_to_browse = true;
                     break;
                 }
             }
             if (!$vb_is_ok_to_browse) {
                 return array();
             }
         }
     }
     // Values to exclude from list attributes and authorities; can be idnos or ids
     $va_exclude_values = caGetOption('exclude_values', $va_facet_info, array(), array('castTo' => 'array'));
     $va_results = $this->opo_ca_browse_cache->getResults();
     $vb_single_value_is_present = false;
     $vs_single_value = isset($va_facet_info['single_value']) ? $va_facet_info['single_value'] : null;
     $va_wheres = array();
     switch ($va_facet_info['type']) {
         # -----------------------------------------------------
         case 'has':
             $vn_state = null;
             if (isset($va_all_criteria[$ps_facet_name])) {
                 break;
             }
             // only one instance of this facet allowed per browse
             if (!($t_item = $this->opo_datamodel->getInstanceByTableName($vs_browse_table_name, true))) {
                 break;
             }
             $vs_yes_text = isset($va_facet_info['label_yes']) && $va_facet_info['label_yes'] ? $va_facet_info['label_yes'] : _t('Yes');
             $vs_no_text = isset($va_facet_info['label_no']) && $va_facet_info['label_no'] ? $va_facet_info['label_no'] : _t('No');
             $va_facet_values = array('yes' => array('id' => 1, 'label' => $vs_yes_text), 'no' => array('id' => 0, 'label' => $vs_no_text));
             // Actually check that both yes and no values will result in something
             if ($va_facet_info['element_code']) {
                 $t_element = new ca_metadata_elements();
                 if (!$t_element->load(array('element_code' => $va_facet_info['element_code']))) {
                     break;
                 }
                 $vs_element_code = $va_facet_info['element_code'];
                 $va_facet = array();
                 $va_counts = array();
                 foreach ($va_facet_values as $vs_state_name => $va_state_info) {
                     $va_wheres = array();
                     $va_joins = array();
                     if (!(bool) $va_state_info['id']) {
                         // no option
                         $va_wheres[] = $this->ops_browse_table_name . '.' . $t_item->primaryKey() . " NOT IN (select row_id from ca_attributes where table_num = " . $t_item->tableNum() . " AND element_id = " . $t_element->getPrimaryKey() . ")";
                     } else {
                         // yes option
                         $va_joins[] = "LEFT JOIN ca_attributes AS caa ON  " . $this->ops_browse_table_name . '.' . $t_item->primaryKey() . " = caa.row_id AND " . $t_item->tableNum() . " = caa.table_num";
                         $va_wheres[] = "caa.element_id = " . $t_element->getPrimaryKey();
                     }
                     if ($t_item->hasField('deleted')) {
                         $va_wheres[] = "(" . $t_item->tableName() . ".deleted = 0)";
                     }
                     if (isset($pa_options['checkAccess']) && is_array($pa_options['checkAccess']) && sizeof($pa_options['checkAccess']) && $t_item->hasField('access')) {
                         $va_wheres[] = "(" . $vs_browse_table_name . ".access IN (" . join(',', $pa_options['checkAccess']) . "))";
                     }
                     if (sizeof($va_results)) {
                         $va_wheres[] = $vs_browse_table_name . "." . $t_item->primaryKey() . " IN (" . join(",", $va_results) . ")";
                     }
                     if ($va_facet_info['relative_to']) {
                         if ($t_subject->hasField('deleted')) {
                             $va_wheres[] = "(" . $t_subject->tableName() . ".deleted = 0)";
                         }
                         if ($va_relative_sql_data = $this->_getRelativeFacetSQLData($va_facet_info['relative_to'], $pa_options)) {
                             $va_joins = array_merge($va_joins, $va_relative_sql_data['joins']);
                             $va_wheres = array_merge($va_wheres, $va_relative_sql_data['wheres']);
                         }
                     }
                     if ($this->opo_config->get('perform_item_level_access_checking')) {
                         if ($t_item = $this->opo_datamodel->getInstanceByTableName($vs_browse_table_name, true)) {
                             // Join to limit what browse table items are used to generate facet
                             $va_joins[] = 'LEFT JOIN ca_acl ON ' . $vs_browse_table_name . '.' . $t_item->primaryKey() . ' = ca_acl.row_id AND ca_acl.table_num = ' . $t_item->tableNum() . "\n";
                             $va_wheres[] = "(\n\t\t\t\t\t\t\t\t\t\t((\n\t\t\t\t\t\t\t\t\t\t\t(ca_acl.user_id = " . (int) $vn_user_id . ")\n\t\t\t\t\t\t\t\t\t\t\t" . (sizeof($va_group_ids) > 0 ? "OR\n\t\t\t\t\t\t\t\t\t\t\t(ca_acl.group_id IN (" . join(",", $va_group_ids) . "))" : "") . "\n\t\t\t\t\t\t\t\t\t\t\tOR\n\t\t\t\t\t\t\t\t\t\t\t(ca_acl.user_id IS NULL and ca_acl.group_id IS NULL)\n\t\t\t\t\t\t\t\t\t\t) AND ca_acl.access >= " . __CA_ACL_READONLY_ACCESS__ . ")\n\t\t\t\t\t\t\t\t\t\t" . ($vb_show_if_no_acl ? "OR ca_acl.acl_id IS NULL" : "") . "\n\t\t\t\t\t\t\t\t\t)";
                         }
                     }
                     $vs_join_sql = join("\n", $va_joins);
                     $vs_where_sql = '';
                     if (sizeof($va_wheres) > 0) {
                         $vs_where_sql = ' WHERE ' . join(' AND ', $va_wheres);
                     }
                     if ($vb_check_availability_only) {
                         $vs_sql = "\n\t\t\t\t\t\t\t\t\tSELECT 1\n\t\t\t\t\t\t\t\t\tFROM " . $vs_browse_table_name . "\n\t\t\t\t\t\t\t\t\t{$vs_join_sql}\n\t\t\t\t\t\t\t\t\t{$vs_where_sql}\n\t\t\t\t\t\t\t\t\tLIMIT 2\n\t\t\t\t\t\t\t\t";
                         //print "$vs_sql<hr>";
                         $qr_res = $this->opo_db->query($vs_sql);
                         if ($qr_res->nextRow()) {
                             $va_counts[$vs_state_name] = (int) $qr_res->numRows();
                         }
                     } else {
                         $vs_sql = "\n\t\t\t\t\t\t\t\t\tSELECT " . $vs_browse_table_name . '.' . $t_item->primaryKey() . "\n\t\t\t\t\t\t\t\t\tFROM " . $vs_browse_table_name . "\n\t\t\t\t\t\t\t\t\t{$vs_join_sql}\n\t\t\t\t\t\t\t\t\t{$vs_where_sql}\n\t\t\t\t\t\t\t\t";
                         //print "$vs_sql<hr>";
                         $qr_res = $this->opo_db->query($vs_sql);
                         if ($qr_res->numRows() > 0) {
                             $va_facet[$vs_state_name] = $va_state_info;
                         } else {
                             return array();
                             // if either option in a "has" facet fails then don't show the facet
                         }
                     }
                 }
             } else {
                 $vs_rel_table_name = $va_facet_info['table'];
                 if (!is_array($va_restrict_to_relationship_types = $va_facet_info['restrict_to_relationship_types'])) {
                     $va_restrict_to_relationship_types = array();
                 }
                 $va_restrict_to_relationship_types = $this->_getRelationshipTypeIDs($va_restrict_to_relationship_types, $va_facet_info['relationship_table']);
                 if (!is_array($va_exclude_relationship_types = $va_facet_info['exclude_relationship_types'])) {
                     $va_exclude_relationship_types = array();
                 }
                 $va_exclude_relationship_types = $this->_getRelationshipTypeIDs($va_exclude_relationship_types, $va_facet_info['relationship_table']);
                 $vn_table_num = $this->opo_datamodel->getTableNum($vs_rel_table_name);
                 $vs_rel_table_pk = $this->opo_datamodel->getTablePrimaryKeyName($vn_table_num);
                 switch (sizeof($va_path = array_keys($this->opo_datamodel->getPath($vs_browse_table_name, $vs_rel_table_name)))) {
                     case 3:
                         $t_item_rel = $this->opo_datamodel->getInstanceByTableName($va_path[1], true);
                         $t_rel_item = $this->opo_datamodel->getInstanceByTableName($va_path[2], true);
                         $vs_key = 'relation_id';
                         break;
                     case 2:
                         $t_item_rel = null;
                         $t_rel_item = $this->opo_datamodel->getInstanceByTableName($va_path[1], true);
                         $vs_key = $t_rel_item->primaryKey();
                         break;
                     default:
                         // bad related table
                         return null;
                         break;
                 }
                 $vs_cur_table = array_shift($va_path);
                 $va_joins_init = array();
                 foreach ($va_path as $vs_join_table) {
                     $va_rel_info = $this->opo_datamodel->getRelationships($vs_cur_table, $vs_join_table);
                     $va_joins_init[] = ($vn_state ? 'INNER' : 'LEFT') . ' JOIN ' . $vs_join_table . ' ON ' . $vs_cur_table . '.' . $va_rel_info[$vs_cur_table][$vs_join_table][0][0] . ' = ' . $vs_join_table . '.' . $va_rel_info[$vs_cur_table][$vs_join_table][0][1] . "\n";
                     $vs_cur_table = $vs_join_table;
                 }
                 $va_facet = array();
                 $va_counts = array();
                 foreach ($va_facet_values as $vs_state_name => $va_state_info) {
                     $va_wheres = array();
                     $va_joins = $va_joins_init;
                     if (!(bool) $va_state_info['id']) {
                         // no option
                         $va_wheres[] = "(" . $t_rel_item->tableName() . "." . $t_rel_item->primaryKey() . " IS NULL)";
                         if ($t_rel_item->hasField('deleted')) {
                             $va_wheres[] = "((" . $t_rel_item->tableName() . ".deleted = 0) OR (" . $t_rel_item->tableName() . ".deleted IS NULL))";
                         }
                         if (isset($pa_options['checkAccess']) && is_array($pa_options['checkAccess']) && sizeof($pa_options['checkAccess']) && $t_rel_item->hasField('access')) {
                             $va_wheres[] = "((" . $t_rel_item->tableName() . ".access NOT IN (" . join(',', $pa_options['checkAccess']) . ")) OR (" . $t_rel_item->tableName() . ".access IS NULL))";
                         }
                         if (sizeof($va_restrict_to_relationship_types) > 0 && is_object($t_item_rel)) {
                             $va_wheres[] = "((" . $t_item_rel->tableName() . ".type_id NOT IN (" . join(',', $va_restrict_to_relationship_types) . ")) OR (" . $t_item_rel->tableName() . ".type_id IS NULL))";
                         }
                         if (sizeof($va_exclude_relationship_types) > 0 && is_object($t_item_rel)) {
                             $va_wheres[] = "(" . $t_item_rel->tableName() . ".type_id IN (" . join(',', $va_exclude_relationship_types) . "))";
                         }
                     } else {
                         // yes option
                         $va_wheres[] = "(" . $t_rel_item->tableName() . "." . $t_rel_item->primaryKey() . " IS NOT NULL)";
                         if ($t_rel_item->hasField('deleted')) {
                             $va_wheres[] = "(" . $t_rel_item->tableName() . ".deleted = 0)";
                         }
                         if (isset($pa_options['checkAccess']) && is_array($pa_options['checkAccess']) && sizeof($pa_options['checkAccess']) && $t_rel_item->hasField('access')) {
                             $va_wheres[] = "(" . $t_rel_item->tableName() . ".access IN (" . join(',', $pa_options['checkAccess']) . "))";
                         }
                         if (sizeof($va_restrict_to_relationship_types) > 0 && is_object($t_item_rel)) {
                             $va_wheres[] = "(" . $t_item_rel->tableName() . ".type_id IN (" . join(',', $va_restrict_to_relationship_types) . "))";
                         }
                         if (sizeof($va_exclude_relationship_types) > 0 && is_object($t_item_rel)) {
                             $va_wheres[] = "(" . $t_item_rel->tableName() . ".type_id NOT IN (" . join(',', $va_exclude_relationship_types) . "))";
                         }
                     }
                     if ($t_item->hasField('deleted')) {
                         $va_wheres[] = "(" . $t_item->tableName() . ".deleted = 0)";
                     }
                     if (isset($pa_options['checkAccess']) && is_array($pa_options['checkAccess']) && sizeof($pa_options['checkAccess']) && $t_item->hasField('access')) {
                         $va_wheres[] = "(" . $vs_browse_table_name . ".access IN (" . join(',', $pa_options['checkAccess']) . "))";
                     }
                     if (sizeof($va_results)) {
                         $va_wheres[] = $vs_browse_table_name . "." . $t_item->primaryKey() . " IN (" . join(",", $va_results) . ")";
                     }
                     if ($va_facet_info['relative_to']) {
                         if ($t_subject->hasField('deleted')) {
                             $va_wheres[] = "(" . $t_subject->tableName() . ".deleted = 0)";
                         }
                         if ($va_relative_sql_data = $this->_getRelativeFacetSQLData($va_facet_info['relative_to'], $pa_options)) {
                             $va_joins = array_merge($va_joins, $va_relative_sql_data['joins']);
                             $va_wheres = array_merge($va_wheres, $va_relative_sql_data['wheres']);
                         }
                     }
                     if ($this->opo_config->get('perform_item_level_access_checking')) {
                         if ($t_item = $this->opo_datamodel->getInstanceByTableName($vs_browse_table_name, true)) {
                             // Join to limit what browse table items are used to generate facet
                             $va_joins[] = 'LEFT JOIN ca_acl ON ' . $vs_browse_table_name . '.' . $t_item->primaryKey() . ' = ca_acl.row_id AND ca_acl.table_num = ' . $t_item->tableNum() . "\n";
                             $va_wheres[] = "(\n\t\t\t\t\t\t\t\t\t\t((\n\t\t\t\t\t\t\t\t\t\t\t(ca_acl.user_id = " . (int) $vn_user_id . ")\n\t\t\t\t\t\t\t\t\t\t\t" . (sizeof($va_group_ids) > 0 ? "OR\n\t\t\t\t\t\t\t\t\t\t\t(ca_acl.group_id IN (" . join(",", $va_group_ids) . "))" : "") . "\n\t\t\t\t\t\t\t\t\t\t\tOR\n\t\t\t\t\t\t\t\t\t\t\t(ca_acl.user_id IS NULL and ca_acl.group_id IS NULL)\n\t\t\t\t\t\t\t\t\t\t) AND ca_acl.access >= " . __CA_ACL_READONLY_ACCESS__ . ")\n\t\t\t\t\t\t\t\t\t\t" . ($vb_show_if_no_acl ? "OR ca_acl.acl_id IS NULL" : "") . "\n\t\t\t\t\t\t\t\t\t)";
                         }
                     }
                     $vs_join_sql = join("\n", $va_joins);
                     $vs_where_sql = '';
                     if (sizeof($va_wheres) > 0) {
                         $vs_where_sql = ' WHERE ' . join(' AND ', $va_wheres);
                     }
                     if ($vb_check_availability_only) {
                         $vs_sql = "\n\t\t\t\t\t\t\t\t\tSELECT 1\n\t\t\t\t\t\t\t\t\tFROM " . $vs_browse_table_name . "\n\t\t\t\t\t\t\t\t\t{$vs_join_sql}\n\t\t\t\t\t\t\t\t\t{$vs_where_sql}\n\t\t\t\t\t\t\t\t\tLIMIT 2\n\t\t\t\t\t\t\t\t";
                         //print "$vs_sql<hr>";
                         $qr_res = $this->opo_db->query($vs_sql);
                         if ($qr_res->nextRow()) {
                             $va_counts[$vs_state_name] = (int) $qr_res->numRows();
                         }
                     } else {
                         $vs_sql = "\n\t\t\t\t\t\t\t\t\tSELECT " . $vs_browse_table_name . '.' . $t_item->primaryKey() . "\n\t\t\t\t\t\t\t\t\tFROM " . $vs_browse_table_name . "\n\t\t\t\t\t\t\t\t\t{$vs_join_sql}\n\t\t\t\t\t\t\t\t\t{$vs_where_sql}\n\t\t\t\t\t\t\t\t";
                         //print "$vs_sql<hr>";
                         $qr_res = $this->opo_db->query($vs_sql);
                         if ($qr_res->numRows() > 0) {
                             $va_facet[$vs_state_name] = $va_state_info;
                         } else {
                             return array();
                             // if either option in a "has" facet fails then don't show the facet
                         }
                     }
                 }
             }
             if ($vb_check_availability_only) {
                 return sizeof($va_counts) > 1 ? true : false;
             }
             return $va_facet;
             break;
             # -----------------------------------------------------
         # -----------------------------------------------------
         case 'label':
             if (!($t_item = $this->opo_datamodel->getInstanceByTableName($vs_browse_table_name, true))) {
                 break;
             }
             if (!($t_label = $t_item->getLabelTableInstance())) {
                 break;
             }
             if (!is_array($va_restrict_to_types = $va_facet_info['restrict_to_types'])) {
                 $va_restrict_to_types = array();
             }
             $vs_item_pk = $t_item->primaryKey();
             $vs_label_table_name = $t_label->tableName();
             $vs_label_pk = $t_label->primaryKey();
             $vs_label_display_field = $t_item->getLabelDisplayField();
             $vs_label_sort_field = $t_item->getLabelSortField();
             $vs_where_sql = $vs_join_sql = '';
             $vb_needs_join = false;
             $va_where_sql = array();
             $va_joins = array();
             if ($vs_browse_type_limit_sql) {
                 $va_where_sql[] = $vs_browse_type_limit_sql;
             }
             if (isset($va_facet_info['preferred_labels_only']) && $va_facet_info['preferred_labels_only'] && $t_label->hasField('is_preferred')) {
                 $va_where_sql[] = "l.is_preferred = 1";
             }
             if (isset($pa_options['checkAccess']) && is_array($pa_options['checkAccess']) && sizeof($pa_options['checkAccess']) && $t_item->hasField('access')) {
                 $va_where_sql[] = "(" . $vs_browse_table_name . ".access IN (" . join(',', $pa_options['checkAccess']) . "))";
             }
             if ($t_item->hasField('deleted')) {
                 $va_where_sql[] = "(" . $vs_browse_table_name . ".deleted = 0)";
                 $vb_needs_join = true;
             }
             if (sizeof($va_restrict_to_types)) {
                 $va_restrict_to_type_ids = caMakeTypeIDList($vs_browse_table_name, $va_restrict_to_types, array('dont_include_subtypes_in_type_restriction' => true));
                 if (sizeof($va_restrict_to_type_ids)) {
                     $va_where_sql[] = "(" . $vs_browse_table_name . "." . $t_item->getTypeFieldName() . " IN (" . join(", ", $va_restrict_to_type_ids) . ")" . ($t_item->getFieldInfo('type_id', 'IS_NULL') ? " OR (" . $vs_browse_table_name . '.' . $t_item->getTypeFieldName() . " IS NULL)" : '') . ")";
                     $vb_needs_join = true;
                 }
             }
             if (sizeof($va_exclude_types)) {
                 $va_exclude_type_ids = caMakeTypeIDList($vs_browse_table_name, $va_exclude_types, array('dont_include_subtypes_in_type_restriction' => true));
                 if (sizeof($va_exclude_type_ids)) {
                     $va_where_sql[] = "(" . $vs_browse_table_name . "." . $t_item->getTypeFieldName() . " NOT IN (" . join(", ", $va_exclude_type_ids) . ")" . ($t_item->getFieldInfo('type_id', 'IS_NULL') ? " OR (" . $vs_browse_table_name . '.' . $t_item->getTypeFieldName() . " IS NULL)" : '') . ")";
                     $vb_needs_join = true;
                 }
             }
             if ($vb_needs_join) {
                 $va_joins[] = "INNER JOIN " . $vs_browse_table_name . " ON " . $vs_browse_table_name . "." . $t_item->primaryKey() . " = l." . $t_item->primaryKey();
             }
             if ($va_facet_info['relative_to']) {
                 if ($t_subject->hasField('deleted')) {
                     $va_where_sql[] = "(" . $t_subject->tableName() . ".deleted = 0)";
                 }
                 if ($va_relative_sql_data = $this->_getRelativeFacetSQLData($va_facet_info['relative_to'], $pa_options)) {
                     $va_joins = array_merge($va_joins, $va_relative_sql_data['joins']);
                     $va_where_sql = array_merge($va_where_sql, $va_relative_sql_data['wheres']);
                 }
             }
             if (sizeof($va_results)) {
                 if ($va_facet_info['relative_to']) {
                     $va_where_sql[] = $this->ops_browse_table_name . "." . $t_subject->primaryKey() . " IN (" . join(",", $va_results) . ")";
                 } else {
                     $va_where_sql[] = "l.{$vs_item_pk} IN (" . join(",", $va_results) . ")";
                 }
             }
             if ($this->opo_config->get('perform_item_level_access_checking')) {
                 if ($t_item = $this->opo_datamodel->getInstanceByTableName($vs_browse_table_name, true)) {
                     // Join to limit what browse table items are used to generate facet
                     $va_joins[] = 'LEFT JOIN ca_acl ON ' . $vs_browse_table_name . '.' . $t_item->primaryKey() . ' = ca_acl.row_id AND ca_acl.table_num = ' . $t_item->tableNum() . "\n";
                     $va_where_sql[] = "(\n\t\t\t\t\t\t\t\t((\n\t\t\t\t\t\t\t\t\t(ca_acl.user_id = " . (int) $vn_user_id . ")\n\t\t\t\t\t\t\t\t\t" . (sizeof($va_group_ids) > 0 ? "OR\n\t\t\t\t\t\t\t\t\t(ca_acl.group_id IN (" . join(",", $va_group_ids) . "))" : "") . "\n\t\t\t\t\t\t\t\t\tOR\n\t\t\t\t\t\t\t\t\t(ca_acl.user_id IS NULL and ca_acl.group_id IS NULL)\n\t\t\t\t\t\t\t\t) AND ca_acl.access >= " . __CA_ACL_READONLY_ACCESS__ . ")\n\t\t\t\t\t\t\t\t" . ($vb_show_if_no_acl ? "OR ca_acl.acl_id IS NULL" : "") . "\n\t\t\t\t\t\t\t)";
                 }
             }
             $vs_join_sql = join("\n", $va_joins);
             if (sizeof($va_where_sql)) {
                 $vs_where_sql = "WHERE " . join(" AND ", $va_where_sql);
             }
             if ($vb_check_availability_only) {
                 $vs_sql = "\n\t\t\t\t\t\t\tSELECT 1\n\t\t\t\t\t\t\tFROM {$vs_label_table_name} l\n\t\t\t\t\t\t\t\t{$vs_join_sql}\n\t\t\t\t\t\t\t\t{$vs_where_sql}\n\t\t\t\t\t\t\tLIMIT 1\n\t\t\t\t\t\t";
                 $qr_res = $this->opo_db->query($vs_sql);
                 return (int) $qr_res->numRows() > 0 ? true : false;
             } else {
                 $vs_parent_fld = $t_item->getProperty('HIERARCHY_PARENT_ID_FLD');
                 $vs_sql = "\n\t\t\t\t\t\t\tSELECT  l.* " . ($vs_parent_fld ? ", " . $vs_browse_table_name . "." . $vs_parent_fld : '') . " \n\t\t\t\t\t\t\tFROM {$vs_label_table_name} l\n\t\t\t\t\t\t\t\t{$vs_join_sql}\n\t\t\t\t\t\t\t\t{$vs_where_sql}\n\t\t\t\t\t\t";
                 $qr_res = $this->opo_db->query($vs_sql);
                 $va_values = array();
                 $va_child_counts = array();
                 $vn_parent_id = null;
                 while ($qr_res->nextRow()) {
                     $vn_id = $qr_res->get($t_item->primaryKey());
                     if ($vs_parent_fld) {
                         $vn_parent_id = $qr_res->get($vs_parent_fld);
                         if ($vn_parent_id) {
                             $va_child_counts[$vn_parent_id]++;
                         }
                     }
                     $va_values[$vn_id][$qr_res->get('locale_id')] = array_merge($qr_res->getRow(), array('id' => $vn_id, 'parent_id' => $vn_parent_id, 'label' => $qr_res->get($vs_label_display_field)));
                     if (!is_null($vs_single_value) && $vn_id == $vs_single_value) {
                         $vb_single_value_is_present = true;
                     }
                 }
                 if ($vs_parent_fld) {
                     foreach ($va_values as $vn_id => $va_values_by_locale) {
                         foreach ($va_values_by_locale as $vn_locale_id => $va_value) {
                             $va_values[$vn_id][$vn_locale_id]['child_count'] = (int) $va_child_counts[$vn_id];
                         }
                     }
                 }
                 if (!is_null($vs_single_value) && !$vb_single_value_is_present) {
                     return array();
                 }
                 $va_values = caExtractValuesByUserLocale($va_values);
                 return $va_values;
             }
             break;
             # -----------------------------------------------------
         # -----------------------------------------------------
         case 'attribute':
             $t_item = $this->opo_datamodel->getInstanceByTableName($vs_browse_table_name, true);
             $t_element = new ca_metadata_elements();
             if (!$t_element->load(array('element_code' => $va_facet_info['element_code']))) {
                 return array();
             }
             $vn_element_type = $t_element->get('datatype');
             $vn_element_id = $t_element->getPrimaryKey();
             $va_joins = array('INNER JOIN ca_attribute_values ON ca_attributes.attribute_id = ca_attribute_values.attribute_id', 'INNER JOIN ' . $vs_browse_table_name . ' ON ' . $vs_browse_table_name . '.' . $t_item->primaryKey() . ' = ca_attributes.row_id AND ca_attributes.table_num = ' . intval($vs_browse_table_num));
             $va_wheres = array();
             if (sizeof($va_results) && $this->numCriteria() > 0) {
                 $va_wheres[] = "(" . $t_subject->tableName() . '.' . $t_subject->primaryKey() . " IN (" . join(',', $va_results) . "))";
             }
             if (isset($pa_options['checkAccess']) && is_array($pa_options['checkAccess']) && sizeof($pa_options['checkAccess']) && $t_item->hasField('access')) {
                 $va_wheres[] = "(" . $vs_browse_table_name . ".access IN (" . join(',', $pa_options['checkAccess']) . "))";
             }
             if ($vs_browse_type_limit_sql) {
                 $va_wheres[] = $vs_browse_type_limit_sql;
             }
             if ($t_item->hasField('deleted')) {
                 $va_wheres[] = "(" . $vs_browse_table_name . ".deleted = 0)";
             }
             if ($va_facet_info['relative_to']) {
                 if ($t_subject->hasField('deleted')) {
                     $va_wheres[] = "(" . $t_subject->tableName() . ".deleted = 0)";
                 }
                 if ($va_relative_sql_data = $this->_getRelativeFacetSQLData($va_facet_info['relative_to'], $pa_options)) {
                     $va_joins = array_merge($va_joins, $va_relative_sql_data['joins']);
                     $va_wheres = array_merge($va_wheres, $va_relative_sql_data['wheres']);
                 }
             }
             if ($this->opo_config->get('perform_item_level_access_checking')) {
                 if ($t_item = $this->opo_datamodel->getInstanceByTableName($vs_browse_table_name, true)) {
                     // Join to limit what browse table items are used to generate facet
                     $va_joins[] = 'LEFT JOIN ca_acl ON ' . $vs_browse_table_name . '.' . $t_item->primaryKey() . ' = ca_acl.row_id AND ca_acl.table_num = ' . $t_item->tableNum() . "\n";
                     $va_wheres[] = "(\n\t\t\t\t\t\t\t\t((\n\t\t\t\t\t\t\t\t\t(ca_acl.user_id = " . (int) $vn_user_id . ")\n\t\t\t\t\t\t\t\t\t" . (sizeof($va_group_ids) > 0 ? "OR\n\t\t\t\t\t\t\t\t\t(ca_acl.group_id IN (" . join(",", $va_group_ids) . "))" : "") . "\n\t\t\t\t\t\t\t\t\tOR\n\t\t\t\t\t\t\t\t\t(ca_acl.user_id IS NULL and ca_acl.group_id IS NULL)\n\t\t\t\t\t\t\t\t) AND ca_acl.access >= " . __CA_ACL_READONLY_ACCESS__ . ")\n\t\t\t\t\t\t\t\t" . ($vb_show_if_no_acl ? "OR ca_acl.acl_id IS NULL" : "") . "\n\t\t\t\t\t\t\t)";
                 }
             }
             $vs_join_sql = join("\n", $va_joins);
             if (is_array($va_wheres) && sizeof($va_wheres) && ($vs_where_sql = join(' AND ', $va_wheres))) {
                 $vs_where_sql = ' AND (' . $vs_where_sql . ')';
             }
             if ($vb_check_availability_only) {
                 // exclude criteria values
                 $vs_criteria_exclude_sql = '';
                 if (is_array($va_criteria) && sizeof($va_criteria)) {
                     $vs_criteria_exclude_sql = ' AND (ca_attribute_values.value_longtext1 NOT IN (' . join(", ", caQuoteList(array_keys($va_criteria))) . ')) ';
                 }
                 $vs_sql = "\n\t\t\t\t\t\t\tSELECT 1\n\t\t\t\t\t\t\tFROM ca_attributes\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t{$vs_join_sql}\n\t\t\t\t\t\t\tWHERE\n\t\t\t\t\t\t\t\t(ca_attribute_values.element_id = ?) {$vs_criteria_exclude_sql} {$vs_where_sql}\n\t\t\t\t\t\t\tLIMIT 2";
                 //print $vs_sql;
                 $qr_res = $this->opo_db->query($vs_sql, $vn_element_id);
                 return (int) $qr_res->numRows() > 1 ? true : false;
             } else {
                 $vs_sql = "\n\t\t\t\t\t\t\tSELECT DISTINCT value_longtext1, value_decimal1, value_longtext2, value_integer1\n\t\t\t\t\t\t\tFROM ca_attributes\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t{$vs_join_sql}\n\t\t\t\t\t\t\tWHERE\n\t\t\t\t\t\t\t\tca_attribute_values.element_id = ? {$vs_where_sql}";
                 $qr_res = $this->opo_db->query($vs_sql, $vn_element_id);
                 $va_values = array();
                 $va_list_items = null;
                 $va_suppress_values = null;
                 if ($va_facet_info['suppress'] && !is_array($va_facet_info['suppress'])) {
                     $va_facet_info['suppress'] = array($va_facet_info['suppress']);
                 }
                 if (!is_array($va_suppress_values = caGetOption('suppress', $va_facet_info, null))) {
                     $va_suppress_values = caGetOption('exclude_values', $va_facet_info, null);
                 }
                 switch ($vn_element_type) {
                     case __CA_ATTRIBUTE_VALUE_LIST__:
                         $va_values = $qr_res->getAllFieldValues('value_longtext1');
                         $qr_res->seek(0);
                         $t_list_item = new ca_list_items();
                         $va_list_item_cache = $t_list_item->getFieldValuesForIDs($va_values, array('idno', 'item_value', 'parent_id', 'access'));
                         $va_list_child_count_cache = array();
                         if (is_array($va_list_item_cache)) {
                             foreach ($va_list_item_cache as $vn_id => $va_item) {
                                 if (!($vn_parent_id = $va_item['parent_id'])) {
                                     continue;
                                 }
                                 if (is_array($pa_options['checkAccess']) && sizeof($pa_options['checkAccess']) && !in_array($va_item['access'], $pa_options['checkAccess'])) {
                                     continue;
                                 }
                                 $va_list_child_count_cache[$vn_parent_id]++;
                             }
                         }
                         $va_list_label_cache = $t_list_item->getPreferredDisplayLabelsForIDs($va_values);
                         // Translate value idnos to ids
                         if (is_array($va_suppress_values)) {
                             $va_suppress_values = ca_lists::getItemIDsFromList($t_element->get('list_id'), $va_suppress_values);
                         }
                         $va_facet_list = array();
                         foreach ($va_values as $vn_val) {
                             if (!$vn_val) {
                                 continue;
                             }
                             if (is_array($va_suppress_values) && in_array($vn_val, $va_suppress_values)) {
                                 continue;
                             }
                             if (is_array($pa_options['checkAccess']) && sizeof($pa_options['checkAccess']) && !in_array($va_item['access'], $pa_options['checkAccess'])) {
                                 continue;
                             }
                             if ($va_criteria[$vn_val]) {
                                 continue;
                             }
                             // skip items that are used as browse critera - don't want to browse on something you're already browsing on
                             $vn_child_count = isset($va_list_child_count_cache[$vn_val]) ? $va_list_child_count_cache[$vn_val] : 0;
                             $va_facet_list[$vn_val] = array('id' => $vn_val, 'label' => html_entity_decode($va_list_label_cache[$vn_val]), 'parent_id' => isset($va_list_item_cache[$vn_val]['parent_id']) ? $va_list_item_cache[$vn_val]['parent_id'] : null, 'child_count' => $vn_child_count);
                         }
                         // preserve order of list
                         $va_values_sorted_by_list_order = array();
                         if (is_array($va_list_item_cache)) {
                             foreach ($va_list_item_cache as $vn_item_id => $va_item) {
                                 if (isset($va_facet_list[$vn_item_id])) {
                                     $va_values_sorted_by_list_order[$vn_item_id] = $va_facet_list[$vn_item_id];
                                 }
                             }
                         }
                         return caSortArrayByKeyInValue($va_values_sorted_by_list_order, array('label'));
                         break;
                     case __CA_ATTRIBUTE_VALUE_OBJECTS__:
                     case __CA_ATTRIBUTE_VALUE_ENTITIES__:
                     case __CA_ATTRIBUTE_VALUE_PLACES__:
                     case __CA_ATTRIBUTE_VALUE_OCCURRENCES__:
                     case __CA_ATTRIBUTE_VALUE_COLLECTIONS__:
                     case __CA_ATTRIBUTE_VALUE_LOANS__:
                     case __CA_ATTRIBUTE_VALUE_MOVEMENTS__:
                     case __CA_ATTRIBUTE_VALUE_STORAGELOCATIONS__:
                     case __CA_ATTRIBUTE_VALUE_OBJECTLOTS__:
                         if ($t_rel_item = AuthorityAttributeValue::elementTypeToInstance($vn_element_type)) {
                             $va_ids = $qr_res->getAllFieldValues('value_integer1');
                             $va_auth_items = $t_rel_item->getPreferredDisplayLabelsForIDs($va_ids);
                             $qr_res->seek(0);
                         }
                         break;
                     default:
                         if (isset($va_facet_info['suppress']) && is_array($va_facet_info['suppress'])) {
                             $va_suppress_values = $va_facet_info['suppress'];
                         }
                         break;
                 }
                 while ($qr_res->nextRow()) {
                     $o_attr = Attribute::getValueInstance($vn_element_type, $qr_res->getRow(), true);
                     if (!($vs_val = trim($o_attr->getDisplayValue()))) {
                         continue;
                     }
                     if (is_array($va_suppress_values) && in_array($vs_val, $va_suppress_values)) {
                         continue;
                     }
                     if ($va_criteria[$vs_val]) {
                         continue;
                     }
                     // skip items that are used as browse critera - don't want to browse on something you're already browsing on
                     switch ($vn_element_type) {
                         case __CA_ATTRIBUTE_VALUE_LIST__:
                             $vn_child_count = 0;
                             if ($va_list_parent_ids[$vs_val]) {
                                 $vn_child_count++;
                             }
                             $va_values[$vs_val] = array('id' => str_replace('/', '&#47;', $vs_val), 'label' => html_entity_decode($va_list_items[$vs_val]['name_plural'] ? $va_list_items[$vs_val]['name_plural'] : $va_list_items[$vs_val]['item_value']), 'parent_id' => $va_list_items[$vs_val]['parent_id'], 'child_count' => $vn_child_count);
                             break;
                         case __CA_ATTRIBUTE_VALUE_OBJECTS__:
                         case __CA_ATTRIBUTE_VALUE_ENTITIES__:
                         case __CA_ATTRIBUTE_VALUE_PLACES__:
                         case __CA_ATTRIBUTE_VALUE_OCCURRENCES__:
                         case __CA_ATTRIBUTE_VALUE_COLLECTIONS__:
                         case __CA_ATTRIBUTE_VALUE_LOANS__:
                         case __CA_ATTRIBUTE_VALUE_MOVEMENTS__:
                         case __CA_ATTRIBUTE_VALUE_STORAGELOCATIONS__:
                         case __CA_ATTRIBUTE_VALUE_OBJECTLOTS__:
                             $va_values[$vs_val] = array('id' => $vn_id, 'label' => html_entity_decode($va_auth_items[$vn_id] ? $va_auth_items[$vn_id] : $vs_val));
                             break;
                         case __CA_ATTRIBUTE_VALUE_CURRENCY__:
                             $va_values[sprintf("%014.2f", preg_replace("![\\D]+!", "", $vs_val))] = array('id' => str_replace('/', '&#47;', $vs_val), 'label' => $vs_val);
                             break;
                         default:
                             $va_values[$vs_val] = array('id' => str_replace('/', '&#47;', $vs_val), 'label' => $vs_val);
                             break;
                     }
                     if (!is_null($vs_single_value) && $vs_val == $vs_single_value) {
                         $vb_single_value_is_present = true;
                     }
                 }
                 if (!is_null($vs_single_value) && !$vb_single_value_is_present) {
                     return array();
                 }
                 ksort($va_values);
                 return $va_values;
             }
             break;
             # -----------------------------------------------------
         # -----------------------------------------------------
         case 'location':
             $t_item = $this->opo_datamodel->getInstanceByTableName($vs_browse_table_name, true);
             $vs_sort_field = null;
             if ($t_item->getProperty('ID_NUMBERING_ID_FIELD') == $vs_field_name) {
                 $vs_sort_field = $t_item->getProperty('ID_NUMBERING_SORT_FIELD');
             }
             $va_joins = array();
             $va_wheres = array();
             $vs_where_sql = '';
             $va_wheres[] = "({$vs_browse_table_name}.current_loc_class IS NOT NULL)";
             if (sizeof($va_results) && $this->numCriteria() > 0) {
                 $va_wheres[] = "(" . $t_subject->tableName() . '.' . $t_subject->primaryKey() . " IN (" . join(',', $va_results) . "))";
             }
             if (isset($pa_options['checkAccess']) && is_array($pa_options['checkAccess']) && sizeof($pa_options['checkAccess']) && $t_item->hasField('access')) {
                 $va_wheres[] = "(" . $vs_browse_table_name . ".access IN (" . join(',', $pa_options['checkAccess']) . "))";
             }
             if ($vs_browse_type_limit_sql) {
                 $va_wheres[] = $vs_browse_type_limit_sql;
             }
             if ($t_item->hasField('deleted')) {
                 $va_wheres[] = "(" . $vs_browse_table_name . ".deleted = 0)";
             }
             if ($this->opo_config->get('perform_item_level_access_checking')) {
                 if ($t_item = $this->opo_datamodel->getInstanceByTableName($vs_browse_table_name, true)) {
                     // Join to limit what browse table items are used to generate facet
                     $va_joins[] = 'LEFT JOIN ca_acl ON ' . $vs_browse_table_name . '.' . $t_item->primaryKey() . ' = ca_acl.row_id AND ca_acl.table_num = ' . $t_item->tableNum() . "\n";
                     $va_wheres[] = "(\n\t\t\t\t\t\t\t\t((\n\t\t\t\t\t\t\t\t\t(ca_acl.user_id = " . (int) $vn_user_id . ")\n\t\t\t\t\t\t\t\t\t" . (sizeof($va_group_ids) > 0 ? "OR\n\t\t\t\t\t\t\t\t\t(ca_acl.group_id IN (" . join(",", $va_group_ids) . "))" : "") . "\n\t\t\t\t\t\t\t\t\tOR\n\t\t\t\t\t\t\t\t\t(ca_acl.user_id IS NULL and ca_acl.group_id IS NULL)\n\t\t\t\t\t\t\t\t) AND ca_acl.access >= " . __CA_ACL_READONLY_ACCESS__ . ")\n\t\t\t\t\t\t\t\t" . ($vb_show_if_no_acl ? "OR ca_acl.acl_id IS NULL" : "") . "\n\t\t\t\t\t\t\t)";
                 }
             }
             $vs_join_sql = join("\n", $va_joins);
             if (is_array($va_wheres) && sizeof($va_wheres) && ($vs_where_sql = join(' AND ', $va_wheres))) {
                 $vs_where_sql = '(' . $vs_where_sql . ')';
             }
             if ($vb_check_availability_only) {
                 if (sizeof($va_criteria) > 0) {
                     return false;
                 }
                 // only one current location criteria allowed
                 $vs_sql = "\n\t\t\t\t\t\t\tSELECT 1\n\t\t\t\t\t\t\tFROM {$vs_browse_table_name}\n\t\t\t\t\t\t\t{$vs_join_sql}\n\t\t\t\t\t\t\tWHERE\n\t\t\t\t\t\t\t\t{$vs_where_sql}\n\t\t\t\t\t\t\tLIMIT 2";
                 $qr_res = $this->opo_db->query($vs_sql);
                 if ($qr_res->nextRow()) {
                     return (int) $qr_res->numRows() > 0 ? true : false;
                 }
                 return false;
             } else {
                 if (sizeof($va_criteria) > 0) {
                     return array();
                 }
                 // only one current location criteria allowed
                 $vs_pk = $t_item->primaryKey();
                 $vs_sql = "\n\t\t\t\t\t\t\tSELECT DISTINCT {$vs_browse_table_name}.current_loc_class, {$vs_browse_table_name}.current_loc_subclass, {$vs_browse_table_name}.current_loc_id\n\t\t\t\t\t\t\tFROM {$vs_browse_table_name}\n\t\t\t\t\t\t\t{$vs_join_sql}\n\t\t\t\t\t\t\tWHERE\n\t\t\t\t\t\t\t\t{$vs_where_sql}";
                 if ($vs_sort_field) {
                     $vs_sql .= " ORDER BY {$vs_sort_field}";
                 }
                 $qr_res = $this->opo_db->query($vs_sql);
                 $va_collapse_map = $this->getCollapseMapForLocationFacet($va_facet_info);
                 $va_values = $va_values_by_table = array();
                 while ($qr_res->nextRow()) {
                     if (!($vs_loc_class = trim($qr_res->get('current_loc_class')))) {
                         continue;
                     }
                     if (!($vs_loc_subclass = trim($qr_res->get('current_loc_subclass')))) {
                         continue;
                     }
                     if (!($vs_loc_id = trim($qr_res->get('current_loc_id')))) {
                         continue;
                     }
                     $vs_val = "{$vs_loc_class}:{$vs_loc_subclass}:{$vs_loc_id}";
                     if ($va_criteria[$vs_val]) {
                         continue;
                     }
                     // skip items that are used as browse critera - don't want to browse on something you're already browsing on
                     $va_values_by_table[$vs_loc_class][$vs_loc_subclass][$vs_loc_id] = true;
                 }
                 foreach ($va_values_by_table as $vs_loc_class => $va_loc_id_by_subclass) {
                     foreach ($va_loc_id_by_subclass as $vs_loc_subclass => $va_loc_ids) {
                         if (sizeof($va_tmp = array_keys($va_loc_ids))) {
                             $vs_loc_table_name = $this->opo_datamodel->getTableName($vs_loc_class);
                             if (($vs_table_name = $vs_loc_table_name) == 'ca_objects_x_storage_locations') {
                                 $vs_table_name = 'ca_storage_locations';
                             }
                             $qr_res = caMakeSearchResult($vs_table_name, $va_tmp);
                             if (isset($va_collapse_map[$vs_table_name]) && isset($va_collapse_map[$vs_table_name]['*']) && $va_collapse_map[$vs_table_name]['*']) {
                                 $va_values[$vs_id = "{$vs_loc_class}"] = array('id' => $vs_id, 'label' => $va_collapse_map[$vs_table_name]['*']);
                                 continue;
                             }
                             while ($qr_res->nextHit()) {
                                 $vn_id = $qr_res->getPrimaryKey();
                                 $va_config = ca_objects::getConfigurationForCurrentLocationType($vs_table_name, $vs_loc_subclass, array('facet' => isset($va_facet_info['display']) ? $va_facet_info['display'] : null));
                                 $vs_template = isset($va_config['template']) ? $va_config['template'] : "^{$vs_table_name}.preferred_labels";
                                 if (isset($va_collapse_map[$vs_table_name]) && isset($va_collapse_map[$vs_table_name][$vs_loc_subclass]) && $va_collapse_map[$vs_table_name][$vs_loc_subclass]) {
                                     $va_values[$vs_id = "{$vs_loc_class}:{$vs_loc_subclass}"] = array('id' => $vs_id, 'label' => $va_collapse_map[$vs_table_name][$vs_loc_subclass]);
                                     continue;
                                 }
                                 $va_values[$vs_id = "{$vs_loc_class}:{$vs_loc_subclass}:{$vn_id}"] = array('id' => $vs_id, 'label' => $qr_res->getWithTemplate($vs_template));
                             }
                         }
                     }
                 }
                 if (!is_null($vs_single_value) && !$vb_single_value_is_present) {
                     return array();
                 }
                 return caSortArrayByKeyInValue($va_values, array('label'));
             }
             return array();
             break;
             # -----------------------------------------------------
         # -----------------------------------------------------
         case 'fieldList':
             $t_item = $this->opo_datamodel->getInstanceByTableName($vs_browse_table_name, true);
             $vs_field_name = $va_facet_info['field'];
             $va_field_info = $t_item->getFieldInfo($vs_field_name);
             $t_list = new ca_lists();
             $t_list_item = new ca_list_items();
             $va_joins = array();
             $va_wheres = array();
             $vs_where_sql = '';
             if (isset($va_field_info['LIST_CODE']) && ($vs_list_name = $va_field_info['LIST_CODE'])) {
                 // Handle fields containing ca_list_item.item_id's
                 $va_joins = array('INNER JOIN ' . $vs_browse_table_name . ' ON ' . $vs_browse_table_name . '.' . $vs_field_name . ' = li.item_id', 'INNER JOIN ca_lists ON ca_lists.list_id = li.list_id');
                 if (sizeof($va_results) && $this->numCriteria() > 0) {
                     $va_wheres[] = "(" . $t_subject->tableName() . '.' . $t_subject->primaryKey() . " IN (" . join(',', $va_results) . "))";
                 }
                 if (isset($pa_options['checkAccess']) && is_array($pa_options['checkAccess']) && sizeof($pa_options['checkAccess']) && $t_item->hasField('access')) {
                     $va_wheres[] = "(" . $vs_browse_table_name . ".access IN (" . join(',', $pa_options['checkAccess']) . "))";
                     $va_wheres[] = "(li.access IN (" . join(',', $pa_options['checkAccess']) . "))";
                 }
                 if ($vs_browse_type_limit_sql) {
                     $va_wheres[] = $vs_browse_type_limit_sql;
                 }
                 if ($t_subject->hasField('deleted')) {
                     $va_wheres[] = "(" . $t_subject->tableName() . ".deleted = 0)";
                 }
                 if ($va_facet_info['relative_to']) {
                     if ($va_relative_sql_data = $this->_getRelativeFacetSQLData($va_facet_info['relative_to'], $pa_options)) {
                         $va_joins = array_merge($va_joins, $va_relative_sql_data['joins']);
                         $va_wheres = array_merge($va_wheres, $va_relative_sql_data['wheres']);
                     }
                 }
                 if (is_array($va_criteria) && sizeof($va_criteria)) {
                     $va_wheres[] = "(li.item_id NOT IN (" . join(",", array_keys($va_criteria)) . "))";
                 }
                 if ($this->opo_config->get('perform_item_level_access_checking')) {
                     if ($t_item = $this->opo_datamodel->getInstanceByTableName($vs_browse_table_name, true)) {
                         // Join to limit what browse table items are used to generate facet
                         $va_joins[] = 'LEFT JOIN ca_acl ON ' . $vs_browse_table_name . '.' . $t_item->primaryKey() . ' = ca_acl.row_id AND ca_acl.table_num = ' . $t_item->tableNum() . "\n";
                         $va_wheres[] = "(\n\t\t\t\t\t\t\t\t\t((\n\t\t\t\t\t\t\t\t\t\t(ca_acl.user_id = " . (int) $vn_user_id . ")\n\t\t\t\t\t\t\t\t\t\t" . (sizeof($va_group_ids) > 0 ? "OR\n\t\t\t\t\t\t\t\t\t\t(ca_acl.group_id IN (" . join(",", $va_group_ids) . "))" : "") . "\n\t\t\t\t\t\t\t\t\t\tOR\n\t\t\t\t\t\t\t\t\t\t(ca_acl.user_id IS NULL and ca_acl.group_id IS NULL)\n\t\t\t\t\t\t\t\t\t) AND ca_acl.access >= " . __CA_ACL_READONLY_ACCESS__ . ")\n\t\t\t\t\t\t\t\t\t" . ($vb_show_if_no_acl ? "OR ca_acl.acl_id IS NULL" : "") . "\n\t\t\t\t\t\t\t\t)";
                     }
                 }
                 $vs_join_sql = join("\n", $va_joins);
                 if (is_array($va_wheres) && sizeof($va_wheres) && ($vs_where_sql = join(' AND ', $va_wheres))) {
                     $vs_where_sql = ' AND (' . $vs_where_sql . ')';
                 }
                 if ($vb_check_availability_only) {
                     $vs_sql = "\n\t\t\t\t\t\t\t\tSELECT 1\n\t\t\t\t\t\t\t\tFROM ca_list_items li\n\t\t\t\t\t\t\t\t{$vs_join_sql}\n\t\t\t\t\t\t\t\tWHERE\n\t\t\t\t\t\t\t\t\tca_lists.list_code = ? {$vs_where_sql}\n\t\t\t\t\t\t\t\tLIMIT 2";
                     $qr_res = $this->opo_db->query($vs_sql, $vs_list_name);
                     return (int) $qr_res->numRows() > 1 ? true : false;
                 } else {
                     // Get label ordering fields
                     $va_ordering_fields_to_fetch = isset($va_facet_info['order_by_label_fields']) && is_array($va_facet_info['order_by_label_fields']) ? $va_facet_info['order_by_label_fields'] : array();
                     $va_orderbys = array();
                     $t_rel_item_label = new ca_list_item_labels();
                     foreach ($va_ordering_fields_to_fetch as $vs_sort_by_field) {
                         if (!$t_rel_item_label->hasField($vs_sort_by_field)) {
                             continue;
                         }
                         $va_orderbys[] = $va_label_selects[] = 'lil.' . $vs_sort_by_field;
                     }
                     $vs_order_by = sizeof($va_orderbys) ? "ORDER BY " . join(', ', $va_orderbys) : '';
                     $vs_sql = "\n\t\t\t\t\t\t\t\tSELECT DISTINCT lil.item_id, lil.name_singular, lil.name_plural, lil.locale_id\n\t\t\t\t\t\t\t\tFROM ca_list_items li\n\t\t\t\t\t\t\t\tINNER JOIN ca_list_item_labels AS lil ON lil.item_id = li.item_id\n\t\t\t\t\t\t\t\t{$vs_join_sql}\n\t\t\t\t\t\t\t\tWHERE\n\t\t\t\t\t\t\t\t\tca_lists.list_code = ?  AND lil.is_preferred = 1 {$vs_where_sql} {$vs_order_by}";
                     //print $vs_sql." [$vs_list_name]";
                     $qr_res = $this->opo_db->query($vs_sql, $vs_list_name);
                     $va_values = array();
                     while ($qr_res->nextRow()) {
                         $vn_id = $qr_res->get('item_id');
                         if ($va_criteria[$vn_id]) {
                             continue;
                         }
                         // skip items that are used as browse critera - don't want to browse on something you're already browsing on
                         $va_values[$vn_id][$qr_res->get('locale_id')] = array('id' => $vn_id, 'label' => $qr_res->get('name_plural'));
                         if (!is_null($vs_single_value) && $vn_id == $vs_single_value) {
                             $vb_single_value_is_present = true;
                         }
                     }
                     if (!is_null($vs_single_value) && !$vb_single_value_is_present) {
                         return array();
                     }
                     return caExtractValuesByUserLocale($va_values);
                 }
             } else {
                 if ($vs_list_name = $va_field_info['LIST']) {
                     $va_list_items_by_value = array();
                     // fields with values set according to ca_list_items (not a foreign key ref)
                     if ($va_list_items = caExtractValuesByUserLocale($t_list->getItemsForList($vs_list_name))) {
                         foreach ($va_list_items as $vn_id => $va_list_item) {
                             $va_list_items_by_value[$va_list_item['item_value']] = $va_list_item['name_plural'];
                         }
                     } else {
                         foreach ($va_field_info['BOUNDS_CHOICE_LIST'] as $vs_val => $vn_id) {
                             $va_list_items_by_value[$vn_id] = $vs_val;
                         }
                     }
                     if (sizeof($va_results) && $this->numCriteria() > 0) {
                         $va_wheres[] = "(" . $t_subject->tableName() . '.' . $t_subject->primaryKey() . " IN (" . join(',', $va_results) . "))";
                     }
                     if ($vs_browse_type_limit_sql) {
                         $va_wheres[] = $vs_browse_type_limit_sql;
                     }
                     if ($t_subject->hasField('deleted')) {
                         $va_wheres[] = "(" . $t_subject->tableName() . ".deleted = 0)";
                     }
                     if ($va_facet_info['relative_to']) {
                         if ($va_relative_sql_data = $this->_getRelativeFacetSQLData($va_facet_info['relative_to'], $pa_options)) {
                             $va_joins = array_merge($va_joins, $va_relative_sql_data['joins']);
                             $va_wheres = array_merge($va_wheres, $va_relative_sql_data['wheres']);
                         }
                     }
                     if ($this->opo_config->get('perform_item_level_access_checking')) {
                         if ($t_item = $this->opo_datamodel->getInstanceByTableName($vs_browse_table_name, true)) {
                             // Join to limit what browse table items are used to generate facet
                             $va_joins[] = 'LEFT JOIN ca_acl ON ' . $vs_browse_table_name . '.' . $t_item->primaryKey() . ' = ca_acl.row_id AND ca_acl.table_num = ' . $t_item->tableNum() . "\n";
                             $va_wheres[] = "(\n\t\t\t\t\t\t\t\t\t\t((\n\t\t\t\t\t\t\t\t\t\t\t(ca_acl.user_id = " . (int) $vn_user_id . ")\n\t\t\t\t\t\t\t\t\t\t\t" . (sizeof($va_group_ids) > 0 ? "OR\n\t\t\t\t\t\t\t\t\t\t\t(ca_acl.group_id IN (" . join(",", $va_group_ids) . "))" : "") . "\n\t\t\t\t\t\t\t\t\t\t\tOR\n\t\t\t\t\t\t\t\t\t\t\t(ca_acl.user_id IS NULL and ca_acl.group_id IS NULL)\n\t\t\t\t\t\t\t\t\t\t) AND ca_acl.access >= " . __CA_ACL_READONLY_ACCESS__ . ")\n\t\t\t\t\t\t\t\t\t\t" . ($vb_show_if_no_acl ? "OR ca_acl.acl_id IS NULL" : "") . "\n\t\t\t\t\t\t\t\t\t)";
                         }
                     }
                     if (is_array($va_wheres) && sizeof($va_wheres) && ($vs_where_sql = join(' AND ', $va_wheres))) {
                         $vs_where_sql = '(' . $vs_where_sql . ')';
                     }
                     $vs_join_sql = join("\n", $va_joins);
                     if ($vb_check_availability_only) {
                         $vs_sql = "\n\t\t\t\t\t\t\t\t\tSELECT 1\n\t\t\t\t\t\t\t\t\tFROM " . $vs_browse_table_name . "\n\t\t\t\t\t\t\t\t\t{$vs_join_sql}\n\t\t\t\t\t\t\t\t\t" . ($vs_where_sql ? 'WHERE' : '') . "\n\t\t\t\t\t\t\t\t\t{$vs_where_sql}\n\t\t\t\t\t\t\t\t\tLIMIT 2";
                         $qr_res = $this->opo_db->query($vs_sql);
                         return (int) $qr_res->numRows() > 1 ? true : false;
                     } else {
                         $vs_sql = "\n\t\t\t\t\t\t\t\t\tSELECT DISTINCT " . $vs_browse_table_name . '.' . $vs_field_name . "\n\t\t\t\t\t\t\t\t\tFROM " . $vs_browse_table_name . "\n\t\t\t\t\t\t\t\t\t{$vs_join_sql}\n\t\t\t\t\t\t\t\t\t" . ($vs_where_sql ? 'WHERE' : '') . "\n\t\t\t\t\t\t\t\t\t\t{$vs_where_sql}";
                         //print $vs_sql." [$vs_list_name]";
                         $qr_res = $this->opo_db->query($vs_sql);
                         $va_values = array();
                         while ($qr_res->nextRow()) {
                             $vn_id = $qr_res->get($vs_field_name);
                             if ($va_criteria[$vn_id]) {
                                 continue;
                             }
                             // skip items that are used as browse critera - don't want to browse on something you're already browsing on
                             if (isset($va_list_items_by_value[$vn_id])) {
                                 $va_values[$vn_id] = array('id' => $vn_id, 'label' => $va_list_items_by_value[$vn_id]);
                                 if (!is_null($vs_single_value) && $vn_id == $vs_single_value) {
                                     $vb_single_value_is_present = true;
                                 }
                             }
                         }
                         if (!is_null($vs_single_value) && !$vb_single_value_is_present) {
                             return array();
                         }
                         return $va_values;
                     }
                 } else {
                     if ($t_browse_table = $this->opo_datamodel->getInstanceByTableName($vs_facet_table = $va_facet_info['table'], true)) {
                         // Handle fields containing ca_list_item.item_id's
                         $va_joins = array('INNER JOIN ' . $vs_browse_table_name . ' ON ' . $vs_browse_table_name . '.' . $vs_field_name . ' = ' . $vs_facet_table . '.' . $t_browse_table->primaryKey());
                         $vs_display_field_name = null;
                         if (method_exists($t_browse_table, 'getLabelTableInstance')) {
                             $t_label_instance = $t_browse_table->getLabelTableInstance();
                             $vs_display_field_name = isset($va_facet_info['display']) && $va_facet_info['display'] ? $va_facet_info['display'] : $t_label_instance->getDisplayField();
                             $va_joins[] = 'INNER JOIN ' . $t_label_instance->tableName() . " AS lab ON lab." . $t_browse_table->primaryKey() . ' = ' . $t_browse_table->tableName() . '.' . $t_browse_table->primaryKey();
                         }
                         if (sizeof($va_results) && $this->numCriteria() > 0) {
                             $va_wheres[] = "(" . $t_subject->tableName() . '.' . $t_subject->primaryKey() . " IN (" . join(',', $va_results) . "))";
                         }
                         if (isset($pa_options['checkAccess']) && is_array($pa_options['checkAccess']) && sizeof($pa_options['checkAccess']) && $t_item->hasField('access')) {
                             $va_wheres[] = "(" . $vs_browse_table_name . ".access IN (" . join(',', $pa_options['checkAccess']) . "))";
                         }
                         if ($vs_browse_type_limit_sql) {
                             $va_wheres[] = $vs_browse_type_limit_sql;
                         }
                         if ($va_facet_info['relative_to']) {
                             if ($t_subject->hasField('deleted')) {
                                 $va_wheres[] = "(" . $t_subject->tableName() . ".deleted = 0)";
                             }
                             if ($va_relative_sql_data = $this->_getRelativeFacetSQLData($va_facet_info['relative_to'], $pa_options)) {
                                 $va_joins = array_merge($va_joins, $va_relative_sql_data['joins']);
                                 $va_wheres = array_merge($va_wheres, $va_relative_sql_data['wheres']);
                             }
                         }
                         if ($this->opo_config->get('perform_item_level_access_checking')) {
                             if ($t_item = $this->opo_datamodel->getInstanceByTableName($vs_browse_table_name, true)) {
                                 // Join to limit what browse table items are used to generate facet
                                 $va_joins[] = 'LEFT JOIN ca_acl ON ' . $vs_browse_table_name . '.' . $t_item->primaryKey() . ' = ca_acl.row_id AND ca_acl.table_num = ' . $t_item->tableNum() . "\n";
                                 $va_wheres[] = "(\n\t\t\t\t\t\t\t\t\t\t\t((\n\t\t\t\t\t\t\t\t\t\t\t\t(ca_acl.user_id = " . (int) $vn_user_id . ")\n\t\t\t\t\t\t\t\t\t\t\t\t" . (sizeof($va_group_ids) > 0 ? "OR\n\t\t\t\t\t\t\t\t\t\t\t\t(ca_acl.group_id IN (" . join(",", $va_group_ids) . "))" : "") . "\n\t\t\t\t\t\t\t\t\t\t\t\tOR\n\t\t\t\t\t\t\t\t\t\t\t\t(ca_acl.user_id IS NULL and ca_acl.group_id IS NULL)\n\t\t\t\t\t\t\t\t\t\t\t) AND ca_acl.access >= " . __CA_ACL_READONLY_ACCESS__ . ")\n\t\t\t\t\t\t\t\t\t\t\t" . ($vb_show_if_no_acl ? "OR ca_acl.acl_id IS NULL" : "") . "\n\t\t\t\t\t\t\t\t\t\t)";
                             }
                         }
                         $vs_join_sql = join("\n", $va_joins);
                         if (is_array($va_wheres) && sizeof($va_wheres) && ($vs_where_sql = join(' AND ', $va_wheres))) {
                             $vs_where_sql = 'WHERE (' . $vs_where_sql . ')';
                         }
                         if ($vb_check_availability_only) {
                             $vs_sql = "\n\t\t\t\t\t\t\t\t\t\tSELECT 1\n\t\t\t\t\t\t\t\t\t\tFROM {$vs_facet_table}\n\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t{$vs_join_sql}\n\t\t\t\t\t\t\t\t\t\t{$vs_where_sql}\n\t\t\t\t\t\t\t\t\t\tLIMIT 1";
                             $qr_res = $this->opo_db->query($vs_sql);
                             return (int) $qr_res->numRows() > 0 ? true : false;
                         } else {
                             $vs_sql = "\n\t\t\t\t\t\t\t\t\t\tSELECT DISTINCT *\n\t\t\t\t\t\t\t\t\t\tFROM {$vs_facet_table}\n\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t{$vs_join_sql}\n\t\t\t\t\t\t\t\t\t\t{$vs_where_sql}";
                             //print $vs_sql;
                             $qr_res = $this->opo_db->query($vs_sql);
                             $va_values = array();
                             $vs_pk = $t_browse_table->primaryKey();
                             while ($qr_res->nextRow()) {
                                 $vn_id = $qr_res->get($vs_pk);
                                 if ($va_criteria[$vn_id]) {
                                     continue;
                                 }
                                 // skip items that are used as browse critera - don't want to browse on something you're already browsing on
                                 $va_values[$vn_id][$qr_res->get('locale_id')] = array('id' => $vn_id, 'label' => $qr_res->get($vs_display_field_name));
                                 if (!is_null($vs_single_value) && $vn_id == $vs_single_value) {
                                     $vb_single_value_is_present = true;
                                 }
                             }
                             if (!is_null($vs_single_value) && !$vb_single_value_is_present) {
                                 return array();
                             }
                             return caExtractValuesByUserLocale($va_values);
                         }
                     }
                 }
             }
             return array();
             break;
             # -----------------------------------------------------
         # -----------------------------------------------------
         case 'field':
             $t_item = $this->opo_datamodel->getInstanceByTableName($vs_browse_table_name, true);
             if (!is_array($va_restrict_to_types = $va_facet_info['restrict_to_types'])) {
                 $va_restrict_to_types = array();
             }
             if (!is_array($va_restrict_to_types = $this->_convertTypeCodesToIDs($va_restrict_to_types, array('instance' => $t_item, 'dontExpandHierarchically' => true)))) {
                 $va_restrict_to_types = array();
             }
             $va_restrict_to_types_expanded = $this->_convertTypeCodesToIDs($va_restrict_to_types, array('instance' => $t_item));
             $vs_field_name = $va_facet_info['field'];
             $va_field_info = $t_item->getFieldInfo($vs_field_name);
             $vs_sort_field = null;
             if ($t_item->getProperty('ID_NUMBERING_ID_FIELD') == $vs_field_name) {
                 $vs_sort_field = $vs_browse_table_name . '.' . $t_item->getProperty('ID_NUMBERING_SORT_FIELD');
             }
             $t_list = new ca_lists();
             $t_list_item = new ca_list_items();
             $va_joins = array();
             $va_wheres = array();
             $vs_where_sql = '';
             $va_facet_values = null;
             if ($vb_is_bit = $va_field_info['FIELD_TYPE'] == FT_BIT) {
                 $vs_yes_text = caGetOption('label_yes', $va_facet_info, _t('Yes'));
                 $vs_no_text = caGetOption('label_no', $va_facet_info, _t('No'));
                 $va_facet_values = array(1 => array('id' => 1, 'label' => $vs_yes_text), 0 => array('id' => 0, 'label' => $vs_no_text));
             }
             if (is_array($va_restrict_to_types) && sizeof($va_restrict_to_types) > 0 && method_exists($t_rel_item, "getTypeList")) {
                 $va_wheres[] = "{$va_restrict_to_types_expanded}.type_id IN (" . join(',', caGetOption('dont_include_subtypes', $va_facet_info, false) ? $va_restrict_to_types : $va_restrict_to_types_expanded) . ")";
                 $va_selects[] = "{$va_restrict_to_types_expanded}.type_id";
             }
             if (sizeof($va_results) && $this->numCriteria() > 0) {
                 $va_wheres[] = "(" . $t_subject->tableName() . '.' . $t_subject->primaryKey() . " IN (" . join(',', $va_results) . "))";
             }
             if (isset($pa_options['checkAccess']) && is_array($pa_options['checkAccess']) && sizeof($pa_options['checkAccess']) && $t_item->hasField('access')) {
                 $va_wheres[] = "(" . $vs_browse_table_name . ".access IN (" . join(',', $pa_options['checkAccess']) . "))";
             }
             if ($vs_browse_type_limit_sql) {
                 $va_wheres[] = $vs_browse_type_limit_sql;
             }
             if ($t_item->hasField('deleted')) {
                 $va_wheres[] = "(" . $vs_browse_table_name . ".deleted = 0)";
             }
             if ($va_facet_info['relative_to']) {
                 if ($t_subject->hasField('deleted')) {
                     $va_wheres[] = "(" . $t_subject->tableName() . ".deleted = 0)";
                 }
                 if ($va_relative_sql_data = $this->_getRelativeFacetSQLData($va_facet_info['relative_to'], $pa_options)) {
                     $va_joins = array_merge($va_joins, $va_relative_sql_data['joins']);
                     $va_wheres = array_merge($va_wheres, $va_relative_sql_data['wheres']);
                 }
             }
             if ($this->opo_config->get('perform_item_level_access_checking')) {
                 if ($t_item = $this->opo_datamodel->getInstanceByTableName($vs_browse_table_name, true)) {
                     // Join to limit what browse table items are used to generate facet
                     $va_joins[] = 'LEFT JOIN ca_acl ON ' . $vs_browse_table_name . '.' . $t_item->primaryKey() . ' = ca_acl.row_id AND ca_acl.table_num = ' . $t_item->tableNum() . "\n";
                     $va_wheres[] = "(\n\t\t\t\t\t\t\t\t((\n\t\t\t\t\t\t\t\t\t(ca_acl.user_id = " . (int) $vn_user_id . ")\n\t\t\t\t\t\t\t\t\t" . (sizeof($va_group_ids) > 0 ? "OR\n\t\t\t\t\t\t\t\t\t(ca_acl.group_id IN (" . join(",", $va_group_ids) . "))" : "") . "\n\t\t\t\t\t\t\t\t\tOR\n\t\t\t\t\t\t\t\t\t(ca_acl.user_id IS NULL and ca_acl.group_id IS NULL)\n\t\t\t\t\t\t\t\t) AND ca_acl.access >= " . __CA_ACL_READONLY_ACCESS__ . ")\n\t\t\t\t\t\t\t\t" . ($vb_show_if_no_acl ? "OR ca_acl.acl_id IS NULL" : "") . "\n\t\t\t\t\t\t\t)";
                 }
             }
             $vs_join_sql = join("\n", $va_joins);
             if (is_array($va_wheres) && sizeof($va_wheres) && ($vs_where_sql = join(' AND ', $va_wheres))) {
                 $vs_where_sql = '(' . $vs_where_sql . ')';
             }
             if ($vb_check_availability_only) {
                 $vs_sql = "\n\t\t\t\t\t\t\tSELECT DISTINCT {$vs_browse_table_name}.{$vs_field_name}\n\t\t\t\t\t\t\tFROM {$vs_browse_table_name}\n\t\t\t\t\t\t\t{$vs_join_sql}\n\t\t\t\t\t\t\tWHERE\n\t\t\t\t\t\t\t\t{$vs_where_sql}\n\t\t\t\t\t\t\tLIMIT 2";
                 $qr_res = $this->opo_db->query($vs_sql);
                 if ($qr_res->numRows() > 1) {
                     return true;
                 }
                 return false;
             } else {
                 $vs_pk = $t_item->primaryKey();
                 $vs_sql = "\n\t\t\t\t\t\t\tSELECT DISTINCT {$vs_browse_table_name}.{$vs_field_name}\n\t\t\t\t\t\t\tFROM {$vs_browse_table_name}\n\t\t\t\t\t\t\t{$vs_join_sql}\n\t\t\t\t\t\t\tWHERE\n\t\t\t\t\t\t\t\t{$vs_where_sql}";
                 if ($vs_sort_field) {
                     $vs_sql .= " ORDER BY {$vs_sort_field}";
                 }
                 $qr_res = $this->opo_db->query($vs_sql);
                 $va_values = array();
                 while ($qr_res->nextRow()) {
                     if (!($vs_val = trim($qr_res->get($vs_field_name))) && !$vb_is_bit) {
                         continue;
                     }
                     if ($va_criteria[$vs_val]) {
                         continue;
                     }
                     // skip items that are used as browse critera - don't want to browse on something you're already browsing on
                     if ($vb_is_bit && isset($va_facet_values[$vs_val])) {
                         $va_values[$vs_val] = $va_facet_values[$vs_val];
                     } else {
                         $va_values[$vs_val] = array('id' => str_replace('/', '&#47;', $vs_val), 'label' => $vs_val);
                     }
                     if (!is_null($vs_single_value) && $vs_val == $vs_single_value) {
                         $vb_single_value_is_present = true;
                     }
                 }
                 if (!is_null($vs_single_value) && !$vb_single_value_is_present) {
                     return array();
                 }
                 return $va_values;
             }
             return array();
             break;
             # -----------------------------------------------------
         # -----------------------------------------------------
         case 'violations':
             $t_item = $this->opo_datamodel->getInstanceByTableName($vs_browse_table_name, true);
             $vs_field_name = $va_facet_info['field'];
             $va_field_info = $t_item->getFieldInfo($vs_field_name);
             $va_joins = array();
             $va_wheres = array();
             $vs_where_sql = '';
             $va_facet_values = null;
             if (sizeof($va_results) && $this->numCriteria() > 0) {
                 $va_wheres[] = "(" . $t_subject->tableName() . '.' . $t_subject->primaryKey() . " IN (" . join(',', $va_results) . "))";
             }
             if (isset($pa_options['checkAccess']) && is_array($pa_options['checkAccess']) && sizeof($pa_options['checkAccess']) && $t_item->hasField('access')) {
                 $va_wheres[] = "(" . $vs_browse_table_name . ".access IN (" . join(',', $pa_options['checkAccess']) . "))";
             }
             if ($vs_browse_type_limit_sql) {
                 $va_wheres[] = $vs_browse_type_limit_sql;
             }
             if ($t_item->hasField('deleted')) {
                 $va_wheres[] = "(" . $vs_browse_table_name . ".deleted = 0)";
             }
             if ($va_facet_info['relative_to']) {
                 if ($t_subject->hasField('deleted')) {
                     $va_wheres[] = "(" . $t_subject->tableName() . ".deleted = 0)";
                 }
                 if ($va_relative_sql_data = $this->_getRelativeFacetSQLData($va_facet_info['relative_to'], $pa_options)) {
                     $va_joins = array_merge($va_joins, $va_relative_sql_data['joins']);
                     $va_wheres = array_merge($va_wheres, $va_relative_sql_data['wheres']);
                 }
             }
             if ($this->opo_config->get('perform_item_level_access_checking')) {
                 if ($t_item = $this->opo_datamodel->getInstanceByTableName($vs_browse_table_name, true)) {
                     // Join to limit what browse table items are used to generate facet
                     $va_joins[] = 'LEFT JOIN ca_acl ON ' . $vs_browse_table_name . '.' . $t_item->primaryKey() . ' = ca_acl.row_id AND ca_acl.table_num = ' . $t_item->tableNum() . "\n";
                     $va_wheres[] = "(\n\t\t\t\t\t\t\t\t((\n\t\t\t\t\t\t\t\t\t(ca_acl.user_id = " . (int) $vn_user_id . ")\n\t\t\t\t\t\t\t\t\t" . (sizeof($va_group_ids) > 0 ? "OR\n\t\t\t\t\t\t\t\t\t(ca_acl.group_id IN (" . join(",", $va_group_ids) . "))" : "") . "\n\t\t\t\t\t\t\t\t\tOR\n\t\t\t\t\t\t\t\t\t(ca_acl.user_id IS NULL and ca_acl.group_id IS NULL)\n\t\t\t\t\t\t\t\t) AND ca_acl.access >= " . __CA_ACL_READONLY_ACCESS__ . ")\n\t\t\t\t\t\t\t\t" . ($vb_show_if_no_acl ? "OR ca_acl.acl_id IS NULL" : "") . "\n\t\t\t\t\t\t\t)";
                 }
             }
             $vs_join_sql = join("\n", $va_joins);
             if (is_array($va_wheres) && sizeof($va_wheres) && ($vs_where_sql = join(' AND ', $va_wheres))) {
                 $vs_where_sql = '(' . $vs_where_sql . ')';
             }
             if ($vb_check_availability_only) {
                 $vs_sql = "\n\t\t\t\t\t\t\tSELECT 1\n\t\t\t\t\t\t\tFROM {$vs_browse_table_name}\n\t\t\t\t\t\t\tINNER JOIN ca_metadata_dictionary_rule_violations ON ca_metadata_dictionary_rule_violations.row_id = {$vs_browse_table_name}." . $t_item->primaryKey() . " AND ca_metadata_dictionary_rule_violations.table_num = {$vs_browse_table_num}\n\t\t\t\t\t\t\t{$vs_join_sql}\n\t\t\t\t\t\t\tWHERE\n\t\t\t\t\t\t\t\t{$vs_where_sql}\n\t\t\t\t\t\t\tLIMIT 2";
                 $qr_res = $this->opo_db->query($vs_sql);
                 if ($qr_res->nextRow()) {
                     return (int) $qr_res->numRows() > 0 ? true : false;
                 }
                 return false;
             } else {
                 $vs_pk = $t_item->primaryKey();
                 $vs_sql = "\n\t\t\t\t\t\t\tSELECT DISTINCT ca_metadata_dictionary_rules.rule_id\n\t\t\t\t\t\t\tFROM {$vs_browse_table_name}\n\t\t\t\t\t\t\tINNER JOIN ca_metadata_dictionary_rule_violations ON ca_metadata_dictionary_rule_violations.row_id = {$vs_browse_table_name}." . $t_item->primaryKey() . " AND ca_metadata_dictionary_rule_violations.table_num = {$vs_browse_table_num}\n\t\t\t\t\t\t\tINNER JOIN ca_metadata_dictionary_rules ON ca_metadata_dictionary_rules.rule_id = ca_metadata_dictionary_rule_violations.rule_id\n\t\t\t\t\t\t\t{$vs_join_sql}\n\t\t\t\t\t\t\tWHERE\n\t\t\t\t\t\t\t\t{$vs_where_sql}";
                 $qr_res = $this->opo_db->query($vs_sql);
                 $va_values = array();
                 $t_rule = new ca_metadata_dictionary_rules();
                 while ($qr_res->nextRow()) {
                     if ($t_rule->load($qr_res->get('rule_id'))) {
                         if (!($vs_val = trim($t_rule->getSetting('label')))) {
                             continue;
                         }
                         $vs_code = $t_rule->get('rule_code');
                         if ($va_criteria[$vs_val]) {
                             continue;
                         }
                         // skip items that are used as browse critera - don't want to browse on something you're already browsing on
                         if (isset($va_facet_values[$vs_code])) {
                             $va_values[$vs_code] = $va_facet_values[$vs_code];
                         } else {
                             $va_values[$vs_code] = array('id' => $vs_code, 'label' => $vs_val);
                         }
                         if (!is_null($vs_single_value) && $vs_code == $vs_single_value) {
                             $vb_single_value_is_present = true;
                         }
                     }
                 }
                 if (!is_null($vs_single_value) && !$vb_single_value_is_present) {
                     return array();
                 }
                 return $va_values;
             }
             return array();
             break;
             # -----------------------------------------------------
         # -----------------------------------------------------
         case 'checkouts':
             if ($vs_browse_table_name != 'ca_objects') {
                 return array();
             }
             $t_item = new ca_objects();
             $va_joins = array();
             $va_wheres = array();
             $vs_where_sql = '';
             $va_facet_values = null;
             if (sizeof($va_results) && $this->numCriteria() > 0) {
                 $va_wheres[] = "(" . $t_subject->tableName() . '.' . $t_subject->primaryKey() . " IN (" . join(',', $va_results) . "))";
             }
             if (isset($pa_options['checkAccess']) && is_array($pa_options['checkAccess']) && sizeof($pa_options['checkAccess']) && $t_item->hasField('access')) {
                 $va_wheres[] = "(" . $vs_browse_table_name . ".access IN (" . join(',', $pa_options['checkAccess']) . "))";
             }
             if ($vs_browse_type_limit_sql) {
                 $va_wheres[] = $vs_browse_type_limit_sql;
             }
             if ($t_item->hasField('deleted')) {
                 $va_wheres[] = "(" . $vs_browse_table_name . ".deleted = 0)";
             }
             if ($va_facet_info['relative_to']) {
                 if ($t_subject->hasField('deleted')) {
                     $va_wheres[] = "(" . $t_subject->tableName() . ".deleted = 0)";
                 }
                 if ($va_relative_sql_data = $this->_getRelativeFacetSQLData($va_facet_info['relative_to'], $pa_options)) {
                     $va_joins = array_merge($va_joins, $va_relative_sql_data['joins']);
                     $va_wheres = array_merge($va_wheres, $va_relative_sql_data['wheres']);
                 }
             }
             $vs_checkout_join_sql = "INNER JOIN ca_object_checkouts ON ca_object_checkouts.object_id = ca_objects.object_id";
             $vn_current_time = time();
             switch ($va_facet_info['status']) {
                 case 'overdue':
                     $va_wheres[] = "((ca_object_checkouts.checkout_date <= {$vn_current_time}) AND (ca_object_checkouts.return_date IS NULL) AND (ca_object_checkouts.due_date <= {$vn_current_time}))";
                     break;
                 case 'reserved':
                     $va_wheres[] = "((ca_object_checkouts.checkout_date IS NULL) AND (ca_object_checkouts.return_date IS NULL))";
                     break;
                 case 'available':
                     $vs_checkout_join_sql = '';
                     $va_wheres[] = "(ca_objects.object_id NOT IN (SELECT object_id FROM ca_object_checkouts WHERE (ca_object_checkouts.checkout_date <= {$vn_current_time}) AND (ca_object_checkouts.return_date IS NULL)))";
                     break;
                 default:
                 case 'out':
                     $va_wheres[] = "((ca_object_checkouts.checkout_date <= {$vn_current_time}) AND (ca_object_checkouts.return_date IS NULL))";
                     break;
             }
             if ($vs_checkout_join_sql) {
                 $va_joins[] = $vs_checkout_join_sql;
                 $va_joins[] = "INNER JOIN ca_users ON ca_object_checkouts.user_id = ca_users.user_id";
             }
             if ($this->opo_config->get('perform_item_level_access_checking')) {
                 if ($t_item = $this->opo_datamodel->getInstanceByTableName($vs_browse_table_name, true)) {
                     // Join to limit what browse table items are used to generate facet
                     $va_joins[] = 'LEFT JOIN ca_acl ON ' . $vs_browse_table_name . '.' . $t_item->primaryKey() . ' = ca_acl.row_id AND ca_acl.table_num = ' . $t_item->tableNum() . "\n";
                     $va_wheres[] = "(\n\t\t\t\t\t\t\t\t((\n\t\t\t\t\t\t\t\t\t(ca_acl.user_id = " . (int) $vn_user_id . ")\n\t\t\t\t\t\t\t\t\t" . (sizeof($va_group_ids) > 0 ? "OR\n\t\t\t\t\t\t\t\t\t(ca_acl.group_id IN (" . join(",", $va_group_ids) . "))" : "") . "\n\t\t\t\t\t\t\t\t\tOR\n\t\t\t\t\t\t\t\t\t(ca_acl.user_id IS NULL and ca_acl.group_id IS NULL)\n\t\t\t\t\t\t\t\t) AND ca_acl.access >= " . __CA_ACL_READONLY_ACCESS__ . ")\n\t\t\t\t\t\t\t\t" . ($vb_show_if_no_acl ? "OR ca_acl.acl_id IS NULL" : "") . "\n\t\t\t\t\t\t\t)";
                 }
             }
             $vs_join_sql = join("\n", $va_joins);
             if (is_array($va_wheres) && sizeof($va_wheres) && ($vs_where_sql = join(' AND ', $va_wheres))) {
                 $vs_where_sql = '(' . $vs_where_sql . ')';
             }
             if ($vb_check_availability_only) {
                 switch ($va_facet_info['mode']) {
                     case 'user':
                         $vs_sql = "\n\t\t\t\t\t\t\t\t\tSELECT 1\n\t\t\t\t\t\t\t\t\tFROM ca_objects\n\t\t\t\t\t\t\t\t\t{$vs_join_sql}\n\t\t\t\t\t\t\t\t\tWHERE\n\t\t\t\t\t\t\t\t\t\t{$vs_where_sql} AND ca_objects.deleted = 0\n\t\t\t\t\t\t\t\t\tLIMIT 2";
                         break;
                     default:
                     case 'all':
                         $vs_sql = "\n\t\t\t\t\t\t\t\t\tSELECT 1\n\t\t\t\t\t\t\t\t\tFROM ca_objects\n\t\t\t\t\t\t\t\t\t{$vs_join_sql}\n\t\t\t\t\t\t\t\t\tWHERE\n\t\t\t\t\t\t\t\t\t\tca_objects.deleted = 0 " . (sizeof($va_results) ? "AND (" . $t_subject->tableName() . '.' . $t_subject->primaryKey() . " IN (" . join(',', $va_results) . "))" : "") . "\n\t\t\t\t\t\t\t\t\tLIMIT 2";
                         break;
                 }
                 $qr_res = $this->opo_db->query($vs_sql);
                 if ($qr_res->nextRow()) {
                     return (int) $qr_res->numRows() > 0 ? true : false;
                 }
                 return false;
             } else {
                 $va_values = array();
                 $vs_pk = $t_item->primaryKey();
                 switch ($va_facet_info['mode']) {
                     case 'user':
                         $vs_sql = "\n\t\t\t\t\t\t\t\t\tSELECT DISTINCT ca_object_checkouts.user_id, ca_users.fname, ca_users.lname, ca_users.email\n\t\t\t\t\t\t\t\t\tFROM ca_objects\n\t\t\t\t\t\t\t\t\t{$vs_join_sql}\n\t\t\t\t\t\t\t\t\tWHERE\n\t\t\t\t\t\t\t\t\t\t{$vs_where_sql} " . (sizeof($va_results) ? " AND (" . $t_subject->tableName() . '.' . $t_subject->primaryKey() . " IN (" . join(',', $va_results) . "))" : "");
                         $qr_res = $this->opo_db->query($vs_sql);
                         while ($qr_res->nextRow()) {
                             $vn_user_id = $qr_res->get('user_id');
                             $vs_val = $qr_res->get('fname') . ' ' . $qr_res->get('lname') . (($vs_email = $qr_res->get('email')) ? "({$vs_email})" : '');
                             if ($va_criteria[$vs_val]) {
                                 continue;
                             }
                             // skip items that are used as browse critera - don't want to browse on something you're already browsing on
                             if (isset($va_facet_values[$vn_user_id])) {
                                 $va_values[$vn_user_id] = $va_facet_values[$vn_user_id];
                             } else {
                                 $va_values[$vn_user_id] = array('id' => $vn_user_id, 'label' => $vs_val);
                             }
                             if (!is_null($vs_single_value) && $vn_user_id == $vs_single_value) {
                                 $vb_single_value_is_present = true;
                             }
                         }
                         break;
                     case 'all':
                     default:
                         foreach (array(_t('Available') => 'available', _t('Out') => 'out', _t('Reserved') => 'reserved', _t('Overdue') => 'overdue') as $vs_status_text => $vs_status) {
                             $vs_join_sql = "INNER JOIN ca_object_checkouts ON ca_object_checkouts.object_id = ca_objects.object_id";
                             switch ($vs_status) {
                                 case 'overdue':
                                     $vs_where = "((ca_object_checkouts.checkout_date <= {$vn_current_time}) AND (ca_object_checkouts.return_date IS NULL) AND (ca_object_checkouts.due_date <= {$vn_current_time}))";
                                     break;
                                 case 'reserved':
                                     $vs_where = "((ca_object_checkouts.checkout_date IS NULL) AND (ca_object_checkouts.return_date IS NULL))";
                                     break;
                                 case 'available':
                                     $vs_join_sql = '';
                                     $vs_where = "(ca_objects.object_id NOT IN (SELECT object_id FROM ca_object_checkouts WHERE (ca_object_checkouts.checkout_date <= {$vn_current_time}) AND (ca_object_checkouts.return_date IS NULL)))";
                                     break;
                                 default:
                                 case 'out':
                                     $vs_where = "((ca_object_checkouts.checkout_date <= {$vn_current_time}) AND (ca_object_checkouts.return_date IS NULL))";
                                     break;
                             }
                             if (sizeof($va_results) && $this->numCriteria() > 0) {
                                 $vs_where .= " AND (" . $t_subject->tableName() . '.' . $t_subject->primaryKey() . " IN (" . join(',', $va_results) . "))";
                             }
                             $vs_sql = "\n\t\t\t\t\t\t\t\t\t\tSELECT count(*) c\n\t\t\t\t\t\t\t\t\t\tFROM ca_objects\n\t\t\t\t\t\t\t\t\t\t{$vs_join_sql}\n\t\t\t\t\t\t\t\t\t\tWHERE\n\t\t\t\t\t\t\t\t\t\t\t{$vs_where}\n\t\t\t\t\t\t\t\t\t";
                             $qr_res = $this->opo_db->query($vs_sql);
                             $qr_res->nextRow();
                             if (!$qr_res->get('c')) {
                                 continue;
                             }
                             $va_values[$vs_status] = array('id' => $vs_status, 'label' => $vs_status_text);
                             if (!is_null($vs_single_value) && $vs_status == $vs_single_value) {
                                 $vb_single_value_is_present = true;
                             }
                         }
                         break;
                 }
                 if (!is_null($vs_single_value) && !$vb_single_value_is_present) {
                     return array();
                 }
                 return $va_values;
             }
             return array();
             break;
             # -----------------------------------------------------
         # -----------------------------------------------------
         case 'normalizedDates':
             $t_item = $this->opo_datamodel->getInstanceByTableName($vs_browse_table_name, true);
             $t_element = new ca_metadata_elements();
             $vb_is_element = $vb_is_field = false;
             if (!($vb_is_element = $t_element->load(array('element_code' => $va_facet_info['element_code']))) && !($vb_is_field = $t_item->hasField($va_facet_info['element_code']) && $t_item->getFieldInfo($va_facet_info['element_code'], 'FIELD_TYPE') === FT_HISTORIC_DATERANGE)) {
                 return array();
             }
             if ($vb_is_element) {
                 $va_joins = array('INNER JOIN ca_attribute_values ON ca_attributes.attribute_id = ca_attribute_values.attribute_id', 'INNER JOIN ' . $vs_browse_table_name . ' ON ' . $vs_browse_table_name . '.' . $t_item->primaryKey() . ' = ca_attributes.row_id AND ca_attributes.table_num = ' . intval($vs_browse_table_num));
             } else {
                 $va_joins = array();
             }
             $va_wheres = array();
             $vs_normalization = $va_facet_info['normalization'];
             // how do we construct the date ranges presented to uses. In other words - how do we want to allow users to browse dates? By year, decade, century?
             if (sizeof($va_results) && $this->numCriteria() > 0) {
                 $va_wheres[] = "(" . $t_subject->tableName() . '.' . $t_subject->primaryKey() . " IN (" . join(',', $va_results) . "))";
             }
             if (isset($pa_options['checkAccess']) && is_array($pa_options['checkAccess']) && sizeof($pa_options['checkAccess']) && $t_item->hasField('access')) {
                 $va_wheres[] = "(" . $vs_browse_table_name . ".access IN (" . join(',', $pa_options['checkAccess']) . "))";
             }
             if ($vs_browse_type_limit_sql) {
                 $va_wheres[] = $vs_browse_type_limit_sql;
             }
             if ($t_item->hasField('deleted')) {
                 $va_wheres[] = "(" . $vs_browse_table_name . ".deleted = 0)";
             }
             if ($va_facet_info['relative_to']) {
                 if ($t_subject->hasField('deleted')) {
                     $va_wheres[] = "(" . $t_subject->tableName() . ".deleted = 0)";
                 }
                 if ($va_relative_sql_data = $this->_getRelativeFacetSQLData($va_facet_info['relative_to'], $pa_options)) {
                     $va_joins = array_merge($va_joins, $va_relative_sql_data['joins']);
                     $va_wheres = array_merge($va_wheres, $va_relative_sql_data['wheres']);
                 }
             }
             if ($this->opo_config->get('perform_item_level_access_checking')) {
                 if ($t_item = $this->opo_datamodel->getInstanceByTableName($vs_browse_table_name, true)) {
                     // Join to limit what browse table items are used to generate facet
                     $va_joins[] = 'LEFT JOIN ca_acl ON ' . $vs_browse_table_name . '.' . $t_item->primaryKey() . ' = ca_acl.row_id AND ca_acl.table_num = ' . $t_item->tableNum() . "\n";
                     $va_wheres[] = "(\n\t\t\t\t\t\t\t\t((\n\t\t\t\t\t\t\t\t\t(ca_acl.user_id = " . (int) $vn_user_id . ")\n\t\t\t\t\t\t\t\t\t" . (sizeof($va_group_ids) > 0 ? "OR\n\t\t\t\t\t\t\t\t\t(ca_acl.group_id IN (" . join(",", $va_group_ids) . "))" : "") . "\n\t\t\t\t\t\t\t\t\tOR\n\t\t\t\t\t\t\t\t\t(ca_acl.user_id IS NULL and ca_acl.group_id IS NULL)\n\t\t\t\t\t\t\t\t) AND ca_acl.access >= " . __CA_ACL_READONLY_ACCESS__ . ")\n\t\t\t\t\t\t\t\t" . ($vb_show_if_no_acl ? "OR ca_acl.acl_id IS NULL" : "") . "\n\t\t\t\t\t\t\t)";
                 }
             }
             $vs_where_sql = '';
             if (is_array($va_wheres) && sizeof($va_wheres) && ($vs_where_sql = join(' AND ', $va_wheres))) {
                 $vs_where_sql = ' AND (' . $vs_where_sql . ')';
             }
             $vs_join_sql = join("\n", $va_joins);
             if ($vb_is_element) {
                 $vn_element_id = $t_element->getPrimaryKey();
                 $vs_dir = strtoupper($va_facet_info['sort']) === 'DESC' ? "DESC" : "ASC";
                 $o_tep = new TimeExpressionParser();
                 $vn_min_date = $vn_max_date = null;
                 $vs_min_sql = $vs_max_sql = '';
                 if (isset($va_facet_info['minimum_date'])) {
                     if ($o_tep->parse($va_facet_info['minimum_date'])) {
                         $va_tmp = $o_tep->getHistoricTimestamps();
                         $vn_min_date = (double) $va_tmp['start'];
                         $vs_min_sql = " AND (ca_attribute_values.value_decimal1 >= {$vn_min_date})";
                     }
                 }
                 if (isset($va_facet_info['maximum_date'])) {
                     if ($o_tep->parse($va_facet_info['maximum_date'])) {
                         $va_tmp = $o_tep->getHistoricTimestamps();
                         $vn_max_date = (double) $va_tmp['end'];
                         $vs_max_sql = " AND (ca_attribute_values.value_decimal2 <= {$vn_max_date})";
                     }
                 }
                 if ($vb_check_availability_only) {
                     $vs_sql = "\n\t\t\t\t\t\t\t\tSELECT 1\n\t\t\t\t\t\t\t\tFROM ca_attributes\n\t\t\t\t\t\t\t\t{$vs_join_sql}\n\t\t\t\t\t\t\t\tWHERE\n\t\t\t\t\t\t\t\t\tca_attribute_values.element_id = ? \n\t\t\t\t\t\t\t\t\t{$vs_min_sql}\n\t\t\t\t\t\t\t\t\t{$vs_max_sql}\n\t\t\t\t\t\t\t\t\t{$vs_where_sql}\n\t\t\t\t\t\t\t\t\tLIMIT 1";
                     //print $vs_sql;
                     $qr_res = $this->opo_db->query($vs_sql, $vn_element_id);
                     return (int) $qr_res->numRows() > 0 ? true : false;
                 } else {
                     $vs_sql = "\n\t\t\t\t\t\t\t\tSELECT DISTINCT ca_attribute_values.value_decimal1, ca_attribute_values.value_decimal2\n\t\t\t\t\t\t\t\tFROM ca_attributes\n\t\t\t\t\t\t\t\t{$vs_join_sql}\n\t\t\t\t\t\t\t\tWHERE\n\t\t\t\t\t\t\t\t\tca_attribute_values.element_id = ? \n\t\t\t\t\t\t\t\t\t{$vs_min_sql}\n\t\t\t\t\t\t\t\t\t{$vs_max_sql}\n\t\t\t\t\t\t\t\t\t{$vs_where_sql}\n\t\t\t\t\t\t\t";
                     //print $vs_sql;
                     $qr_res = $this->opo_db->query($vs_sql, $vn_element_id);
                     $vn_current_year = (int) date("Y");
                     $va_values = array();
                     $vb_include_unknown = (bool) caGetOption('include_unknown', $va_facet_info, false);
                     $vb_unknown_is_set = false;
                     while ($qr_res->nextRow()) {
                         $vn_start = $qr_res->get('value_decimal1');
                         $vn_end = $qr_res->get('value_decimal2');
                         if (!($vn_start && $vn_end)) {
                             if ($vb_include_unknown) {
                                 $vb_unknown_is_set = true;
                             }
                             continue;
                         }
                         if ($vn_end > $vn_current_year + 50) {
                             continue;
                         }
                         // bad years can make for large facets that cause timeouts so cut it off 50 years into the future
                         $va_normalized_values = $o_tep->normalizeDateRange($vn_start, $vn_end, $vs_normalization);
                         foreach ($va_normalized_values as $vn_sort_value => $vs_normalized_value) {
                             if ($va_criteria[$vs_normalized_value]) {
                                 continue;
                             }
                             // skip items that are used as browse critera - don't want to browse on something you're already browsing on
                             if (is_numeric($vs_normalized_value) && (int) $vs_normalized_value === 0) {
                                 continue;
                             }
                             // don't include year=0
                             $va_values[$vn_sort_value][$vs_normalized_value] = array('id' => $vs_normalized_value, 'label' => $vs_normalized_value);
                             if (!is_null($vs_single_value) && $vs_normalized_value == $vs_single_value) {
                                 $vb_single_value_is_present = true;
                             }
                         }
                     }
                     if ($vb_include_unknown && !$vb_unknown_is_set) {
                         // Check for rows where no data is set at all as opposed to null dates
                         $vs_sql = "\n\t\t\t\t\t\t\t\t\tSELECT DISTINCT ca_attributes.row_id\n\t\t\t\t\t\t\t\t\tFROM ca_attributes\n\t\t\t\t\t\t\t\t\t{$vs_join_sql}\n\t\t\t\t\t\t\t\t\tWHERE\n\t\t\t\t\t\t\t\t\t\tca_attribute_values.element_id = ? \n\t\t\t\t\t\t\t\t\t\t{$vs_min_sql}\n\t\t\t\t\t\t\t\t\t\t{$vs_max_sql}\n\t\t\t\t\t\t\t\t\t\t{$vs_where_sql}\n\t\t\t\t\t\t\t\t";
                         //print $vs_sql;
                         $qr_res = $this->opo_db->query($vs_sql, $vn_element_id);
                         if ($qr_res->numRows() < sizeof($va_results)) {
                             $vb_unknown_is_set = true;
                         }
                     }
                     if ($vb_unknown_is_set && sizeof($va_values) > 0) {
                         $va_values['999999999'][_t('Date unknown')] = array('id' => 'null', 'label' => _t('Date unknown'));
                     }
                     if (!is_null($vs_single_value) && !$vb_single_value_is_present) {
                         return array();
                     }
                     ksort($va_values);
                     if ($vs_dir == 'DESC') {
                         $va_values = array_reverse($va_values);
                     }
                     $va_sorted_values = array();
                     foreach ($va_values as $vn_sort_value => $va_values_for_sort_value) {
                         $va_sorted_values = array_merge($va_sorted_values, $va_values_for_sort_value);
                     }
                     return $va_sorted_values;
                 }
             } else {
                 // is intrinsic
                 $vs_dir = strtoupper($va_facet_info['sort']) === 'DESC' ? "DESC" : "ASC";
                 $vs_browse_start_fld = $t_item->getFieldInfo($va_facet_info['element_code'], 'START');
                 $vs_browse_end_fld = $t_item->getFieldInfo($va_facet_info['element_code'], 'END');
                 $o_tep = new TimeExpressionParser();
                 $vn_min_date = $vn_max_date = null;
                 $vs_min_sql = $vs_max_sql = '';
                 if (isset($va_facet_info['minimum_date'])) {
                     if ($o_tep->parse($va_facet_info['minimum_date'])) {
                         $va_tmp = $o_tep->getHistoricTimestamps();
                         $vn_min_date = (double) $va_tmp['start'];
                         $vs_min_sql = " AND ({$vs_browse_table_name}.{$vs_browse_start_fld} >= {$vn_min_date})";
                     }
                 }
                 if (isset($va_facet_info['maximum_date'])) {
                     if ($o_tep->parse($va_facet_info['maximum_date'])) {
                         $va_tmp = $o_tep->getHistoricTimestamps();
                         $vn_max_date = (double) $va_tmp['end'];
                         $vs_max_sql = " AND ({$vs_browse_table_name}.{$vs_browse_end_fld} <= {$vn_max_date})";
                     }
                 }
                 if ($vb_check_availability_only) {
                     $vs_sql = "\n\t\t\t\t\t\t\t\tSELECT 1\n\t\t\t\t\t\t\t\tFROM {$vs_browse_table_name}\n\t\t\t\t\t\t\t\t{$vs_join_sql}\n\t\t\t\t\t\t\t\tWHERE\n\t\t\t\t\t\t\t\t\t1 = 1\n\t\t\t\t\t\t\t\t\t{$vs_min_sql}\n\t\t\t\t\t\t\t\t\t{$vs_max_sql}\n\t\t\t\t\t\t\t\t\t{$vs_where_sql}\n\t\t\t\t\t\t\t\t\tLIMIT 1";
                     //print $vs_sql;
                     $qr_res = $this->opo_db->query($vs_sql);
                     return (int) $qr_res->numRows() > 0 ? true : false;
                 } else {
                     $vs_sql = "\n\t\t\t\t\t\t\t\tSELECT DISTINCT {$vs_browse_table_name}.{$vs_browse_start_fld}, {$vs_browse_table_name}.{$vs_browse_end_fld}\n\t\t\t\t\t\t\t\tFROM {$vs_browse_table_name}\n\t\t\t\t\t\t\t\t{$vs_join_sql}\n\t\t\t\t\t\t\t\tWHERE\n\t\t\t\t\t\t\t\t\t1 = 1\n\t\t\t\t\t\t\t\t\t{$vs_min_sql}\n\t\t\t\t\t\t\t\t\t{$vs_max_sql}\n\t\t\t\t\t\t\t\t\t{$vs_where_sql}\n\t\t\t\t\t\t\t";
                     //print $vs_sql;
                     $qr_res = $this->opo_db->query($vs_sql);
                     $va_values = array();
                     while ($qr_res->nextRow()) {
                         $vn_start = $qr_res->get($vs_browse_start_fld);
                         $vn_end = $qr_res->get($vs_browse_end_fld);
                         if (!($vn_start && $vn_end)) {
                             continue;
                         }
                         $va_normalized_values = $o_tep->normalizeDateRange($vn_start, $vn_end, $vs_normalization);
                         foreach ($va_normalized_values as $vn_sort_value => $vs_normalized_value) {
                             if ($va_criteria[$vs_normalized_value]) {
                                 continue;
                             }
                             // skip items that are used as browse critera - don't want to browse on something you're already browsing on
                             if (is_numeric($vs_normalized_value) && (int) $vs_normalized_value === 0) {
                                 continue;
                             }
                             // don't include year=0
                             $va_values[$vn_sort_value][$vs_normalized_value] = array('id' => $vs_normalized_value, 'label' => $vs_normalized_value);
                             if (!is_null($vs_single_value) && $vs_normalized_value == $vs_single_value) {
                                 $vb_single_value_is_present = true;
                             }
                         }
                     }
                     if (!is_null($vs_single_value) && !$vb_single_value_is_present) {
                         return array();
                     }
                     ksort($va_values);
                     if ($vs_dir == 'DESC') {
                         $va_values = array_reverse($va_values);
                     }
                     $va_sorted_values = array();
                     foreach ($va_values as $vn_sort_value => $va_values_for_sort_value) {
                         $va_sorted_values = array_merge($va_sorted_values, $va_values_for_sort_value);
                     }
                     return $va_sorted_values;
                 }
             }
             break;
             # -----------------------------------------------------
         # -----------------------------------------------------
         case 'normalizedLength':
             $t_item = $this->opo_datamodel->getInstanceByTableName($vs_browse_table_name, true);
             $t_element = new ca_metadata_elements();
             $vb_is_element = $vb_is_field = false;
             if (!($vb_is_element = $t_element->load(array('element_code' => $va_facet_info['element_code']))) && !($vb_is_field = $t_item->hasField($va_facet_info['element_code']) && $t_item->getFieldInfo($va_facet_info['element_code'], 'FIELD_TYPE') === FT_HISTORIC_DATERANGE)) {
                 return array();
             }
             if ($vb_is_element) {
                 $va_joins = array('INNER JOIN ca_attribute_values ON ca_attributes.attribute_id = ca_attribute_values.attribute_id', 'INNER JOIN ' . $vs_browse_table_name . ' ON ' . $vs_browse_table_name . '.' . $t_item->primaryKey() . ' = ca_attributes.row_id AND ca_attributes.table_num = ' . intval($vs_browse_table_num));
             } else {
                 $va_joins = array();
             }
             $va_wheres = array();
             $vs_normalization = $va_facet_info['normalization'];
             // how do we construct the dimensions ranges presented to users. In other words - what increments do we can to use to  browse measurments?
             if (sizeof($va_results) && $this->numCriteria() > 0) {
                 $va_wheres[] = "(" . $t_subject->tableName() . '.' . $t_subject->primaryKey() . " IN (" . join(',', $va_results) . "))";
             }
             if (isset($pa_options['checkAccess']) && is_array($pa_options['checkAccess']) && sizeof($pa_options['checkAccess']) && $t_item->hasField('access')) {
                 $va_wheres[] = "(" . $vs_browse_table_name . ".access IN (" . join(',', $pa_options['checkAccess']) . "))";
             }
             if ($vs_browse_type_limit_sql) {
                 $va_wheres[] = $vs_browse_type_limit_sql;
             }
             if ($t_item->hasField('deleted')) {
                 $va_wheres[] = "(" . $vs_browse_table_name . ".deleted = 0)";
             }
             if ($va_facet_info['relative_to']) {
                 if ($t_subject->hasField('deleted')) {
                     $va_wheres[] = "(" . $t_subject->tableName() . ".deleted = 0)";
                 }
                 if ($va_relative_sql_data = $this->_getRelativeFacetSQLData($va_facet_info['relative_to'], $pa_options)) {
                     $va_joins = array_merge($va_joins, $va_relative_sql_data['joins']);
                     $va_wheres = array_merge($va_wheres, $va_relative_sql_data['wheres']);
                 }
             }
             if ($this->opo_config->get('perform_item_level_access_checking')) {
                 if ($t_item = $this->opo_datamodel->getInstanceByTableName($vs_browse_table_name, true)) {
                     // Join to limit what browse table items are used to generate facet
                     $va_joins[] = 'LEFT JOIN ca_acl ON ' . $vs_browse_table_name . '.' . $t_item->primaryKey() . ' = ca_acl.row_id AND ca_acl.table_num = ' . $t_item->tableNum() . "\n";
                     $va_wheres[] = "(\n\t\t\t\t\t\t\t\t((\n\t\t\t\t\t\t\t\t\t(ca_acl.user_id = " . (int) $vn_user_id . ")\n\t\t\t\t\t\t\t\t\t" . (sizeof($va_group_ids) > 0 ? "OR\n\t\t\t\t\t\t\t\t\t(ca_acl.group_id IN (" . join(",", $va_group_ids) . "))" : "") . "\n\t\t\t\t\t\t\t\t\tOR\n\t\t\t\t\t\t\t\t\t(ca_acl.user_id IS NULL and ca_acl.group_id IS NULL)\n\t\t\t\t\t\t\t\t) AND ca_acl.access >= " . __CA_ACL_READONLY_ACCESS__ . ")\n\t\t\t\t\t\t\t\t" . ($vb_show_if_no_acl ? "OR ca_acl.acl_id IS NULL" : "") . "\n\t\t\t\t\t\t\t)";
                 }
             }
             $vs_where_sql = '';
             if (is_array($va_wheres) && sizeof($va_wheres) && ($vs_where_sql = join(' AND ', $va_wheres))) {
                 $vs_where_sql = ' AND (' . $vs_where_sql . ')';
             }
             $vs_join_sql = join("\n", $va_joins);
             $vn_element_id = $t_element->getPrimaryKey();
             $vs_dir = strtoupper($va_facet_info['sort']) === 'DESC' ? "DESC" : "ASC";
             $vs_min_sql = $vs_max_sql = '';
             $vo_minimum_dimension = caParseLengthDimension(caGetOption('minimum_dimension', $va_facet_info, "0 in"));
             $vo_maximum_dimension = caParseLengthDimension(caGetOption('maximum_dimension', $va_facet_info, "0 in"));
             if ($vo_minimum_dimension) {
                 $vn_tmp = (double) $vo_minimum_dimension->convertTo('METER', 6, 'en_US');
                 $vs_min_sql = " AND (ca_attribute_values.value_decimal1 >= {$vn_tmp})";
             }
             if (caGetOption('maximum_dimension', $va_facet_info, null) && $vo_maximum_dimension) {
                 $vn_tmp = (double) $vo_maximum_dimension->convertTo('METER', 6, 'en_US');
                 $vs_max_sql = " AND (ca_attribute_values.value_decimal1 <= {$vn_tmp})";
             }
             if ($vb_check_availability_only) {
                 $vs_sql = "\n\t\t\t\t\t\t\tSELECT 1\n\t\t\t\t\t\t\tFROM ca_attributes\n\t\t\t\t\t\t\t{$vs_join_sql}\n\t\t\t\t\t\t\tWHERE\n\t\t\t\t\t\t\t\tca_attribute_values.element_id = ? \n\t\t\t\t\t\t\t\t{$vs_min_sql}\n\t\t\t\t\t\t\t\t{$vs_max_sql}\n\t\t\t\t\t\t\t\t{$vs_where_sql}\n\t\t\t\t\t\t\t\tLIMIT 1";
                 //print $vs_sql;
                 $qr_res = $this->opo_db->query($vs_sql, $vn_element_id);
                 return (int) $qr_res->numRows() > 0 ? true : false;
             } else {
                 $vs_sql = "\n\t\t\t\t\t\t\tSELECT DISTINCT ca_attribute_values.value_decimal1, ca_attribute_values.value_decimal2, ca_attribute_values.value_longtext1, ca_attribute_values.value_longtext2\n\t\t\t\t\t\t\tFROM ca_attributes\n\t\t\t\t\t\t\t{$vs_join_sql}\n\t\t\t\t\t\t\tWHERE\n\t\t\t\t\t\t\t\tca_attribute_values.element_id = ? \n\t\t\t\t\t\t\t\t{$vs_min_sql}\n\t\t\t\t\t\t\t\t{$vs_max_sql}\n\t\t\t\t\t\t\t\t{$vs_where_sql}\n\t\t\t\t\t\t";
                 //print $vs_sql;
                 $qr_res = $this->opo_db->query($vs_sql, $vn_element_id);
                 $va_values = array();
                 if (!($vs_output_units = caGetLengthUnitType($vs_units = caGetOption('units', $va_facet_info, 'm')))) {
                     $vs_output_units = Zend_Measure_Length::METER;
                 }
                 $vs_increment = caGetOption('increment', $va_facet_info, '1 m');
                 $vo_increment = caParseLengthDimension($vs_increment);
                 $vn_increment_in_current_units = (double) $vo_increment->convertTo($vs_output_units, 6, 'en_US');
                 while ($qr_res->nextRow()) {
                     $vn_meters = $qr_res->get('value_decimal1');
                     // measurement in meters
                     // convert to target dimensions
                     // normalize
                     $vo_dim = new Zend_Measure_Length($vn_meters, Zend_Measure_Length::METER, 'en_US');
                     $vs_dim = $vo_dim->convertTo($vs_output_units, 6, 'en_US');
                     $vn_dim = (double) $vs_dim;
                     $vn_normalized = floor($vn_dim / $vn_increment_in_current_units) * $vn_increment_in_current_units;
                     if (isset($va_criteria[$vn_normalized])) {
                         continue;
                     }
                     $vs_normalized_range_with_units = "{$vn_normalized} {$vs_units} - " . ($vn_normalized + $vn_increment_in_current_units) . " {$vs_units}";
                     $va_values[$vn_normalized][$vn_normalized] = array('id' => $vn_normalized, 'label' => $vs_normalized_range_with_units);
                     if (!is_null($vs_single_value) && $vn_normalized == $vs_single_value) {
                         $vb_single_value_is_present = true;
                     }
                 }
                 if (!is_null($vs_single_value) && !$vb_single_value_is_present) {
                     return array();
                 }
                 ksort($va_values);
                 if ($vs_dir == 'DESC') {
                     $va_values = array_reverse($va_values);
                 }
                 $va_sorted_values = array();
                 foreach ($va_values as $vn_sort_value => $va_values_for_sort_value) {
                     $va_sorted_values = array_merge($va_sorted_values, $va_values_for_sort_value);
                 }
                 return $va_sorted_values;
             }
             break;
             # -----------------------------------------------------
         # -----------------------------------------------------
         case 'authority':
             $vs_rel_table_name = $va_facet_info['table'];
             $va_params = $this->opo_ca_browse_cache->getParameters();
             // Make sure we honor type restrictions for the related authority
             $va_user_type_restrictions = caGetTypeRestrictionsForUser($vs_rel_table_name);
             $va_restrict_to_types = $va_facet_info['restrict_to_types'];
             if (is_array($va_user_type_restrictions)) {
                 if (!is_array($va_restrict_to_types)) {
                     $va_restrict_to_types = $va_user_type_restrictions;
                 } else {
                     $va_restrict_to_types = array_intersect($va_restrict_to_types, $va_user_type_restrictions);
                 }
             }
             if (!is_array($va_exclude_types = $va_facet_info['exclude_types'])) {
                 $va_exclude_types = array();
             }
             if (!is_array($va_restrict_to_relationship_types = $va_facet_info['restrict_to_relationship_types'])) {
                 $va_restrict_to_relationship_types = array();
             }
             if (!is_array($va_exclude_relationship_types = $va_facet_info['exclude_relationship_types'])) {
                 $va_exclude_relationship_types = array();
             }
             $t_item = $this->opo_datamodel->getInstanceByTableName($vs_browse_table_name, true);
             if ($vs_browse_table_name == $vs_rel_table_name) {
                 // browsing on self-relations not supported
                 break;
             } else {
                 switch (sizeof($va_path = array_keys($this->opo_datamodel->getPath($vs_browse_table_name, $vs_rel_table_name)))) {
                     case __CA_ATTRIBUTE_VALUE_LIST__:
                         $t_item_rel = $this->opo_datamodel->getInstanceByTableName($va_path[1], true);
                         $t_rel_item = $this->opo_datamodel->getInstanceByTableName($va_path[2], true);
                         $vs_key = 'relation_id';
                         break;
                     case __CA_ATTRIBUTE_VALUE_DATERANGE__:
                         $t_item_rel = null;
                         $t_rel_item = $this->opo_datamodel->getInstanceByTableName($va_path[1], true);
                         $vs_key = $t_rel_item->primaryKey();
                         break;
                     default:
                         // bad related table
                         return null;
                         break;
                 }
             }
             $vb_rel_is_hierarchical = (bool) $t_rel_item->isHierarchical();
             //
             // Convert related item type_code specs in restrict_to_types and exclude_types lists to numeric type_ids we need for the query
             //
             if (!is_array($va_restrict_to_types = $this->_convertTypeCodesToIDs($va_restrict_to_types, array('instance' => $t_rel_item, 'dontExpandHierarchically' => true)))) {
                 $va_restrict_to_types = array();
             }
             if (!is_array($va_exclude_types = $this->_convertTypeCodesToIDs($va_exclude_types, array('instance' => $t_rel_item, 'dontExpandHierarchically' => true)))) {
                 $va_exclude_types = array();
             }
             $va_restrict_to_types_expanded = $this->_convertTypeCodesToIDs($va_restrict_to_types, array('instance' => $t_rel_item));
             $va_exclude_types_expanded = $this->_convertTypeCodesToIDs($va_exclude_types, array('instance' => $t_rel_item));
             // look up relationship type restrictions
             $va_restrict_to_relationship_types = $this->_getRelationshipTypeIDs($va_restrict_to_relationship_types, $va_facet_info['relationship_table']);
             $va_exclude_relationship_types = $this->_getRelationshipTypeIDs($va_exclude_relationship_types, $va_facet_info['relationship_table']);
             $va_joins = array();
             $va_selects = array();
             $va_wheres = array();
             $va_orderbys = array();
             if (!$va_facet_info['show_all_when_first_facet'] || $this->numCriteria() > 0) {
                 $vs_cur_table = array_shift($va_path);
                 foreach ($va_path as $vs_join_table) {
                     $va_rel_info = $this->opo_datamodel->getRelationships($vs_cur_table, $vs_join_table);
                     $va_joins[] = 'INNER JOIN ' . $vs_join_table . ' ON ' . $vs_cur_table . '.' . $va_rel_info[$vs_cur_table][$vs_join_table][0][0] . ' = ' . $vs_join_table . '.' . $va_rel_info[$vs_cur_table][$vs_join_table][0][1] . "\n";
                     $vs_cur_table = $vs_join_table;
                 }
             } else {
                 if ($va_facet_info['show_all_when_first_facet']) {
                     $va_path = array_reverse($va_path);
                     // in "show_all" mode we turn the browse on it's head and grab records by the "subject" table, rather than the browse table
                     $vs_cur_table = array_shift($va_path);
                     $vs_join_table = $va_path[0];
                     $va_rel_info = $this->opo_datamodel->getRelationships($vs_cur_table, $vs_join_table);
                     $va_joins[] = 'LEFT JOIN ' . $vs_join_table . ' ON ' . $vs_cur_table . '.' . $va_rel_info[$vs_cur_table][$vs_join_table][0][0] . ' = ' . $vs_join_table . '.' . $va_rel_info[$vs_cur_table][$vs_join_table][0][1] . "\n";
                 }
             }
             if (sizeof($va_results) && $this->numCriteria() > 0) {
                 $va_wheres[] = "(" . $t_subject->tableName() . '.' . $t_subject->primaryKey() . " IN (" . join(',', $va_results) . "))";
             }
             if (!is_array($va_restrict_to_lists = $va_facet_info['restrict_to_lists'])) {
                 $va_restrict_to_lists = array();
             }
             if (is_array($va_restrict_to_lists) && sizeof($va_restrict_to_lists) > 0 && $t_rel_item->tableName() == 'ca_list_items') {
                 $va_list_ids = array();
                 foreach ($va_restrict_to_lists as $vm_list) {
                     if (is_numeric($vm_list)) {
                         $vn_list_id = (int) $vm_list;
                     } else {
                         $vn_list_id = (int) ca_lists::getListID($vm_list);
                     }
                     if ($vn_list_id) {
                         $va_list_ids[] = $vn_list_id;
                     }
                 }
                 if (sizeof($va_list_ids) > 0) {
                     $va_wheres[] = "{$vs_rel_table_name}.list_id IN (" . join(',', $va_list_ids) . ")";
                 }
             }
             if (is_array($va_restrict_to_types) && sizeof($va_restrict_to_types) > 0 && method_exists($t_rel_item, "getTypeList")) {
                 $va_wheres[] = "{$vs_rel_table_name}.type_id IN (" . join(',', caGetOption('dont_include_subtypes', $va_facet_info, false) ? $va_restrict_to_types : $va_restrict_to_types_expanded) . ")" . ($t_rel_item->getFieldInfo('type_id', 'IS_NULL') ? " OR ({$vs_rel_table_name}.type_id IS NULL)" : '');
                 $va_selects[] = "{$vs_rel_table_name}.type_id";
             }
             if (is_array($va_exclude_types) && sizeof($va_exclude_types) > 0 && method_exists($t_rel_item, "getTypeList")) {
                 $va_wheres[] = "{$vs_rel_table_name}.type_id NOT IN (" . join(',', caGetOption('dont_include_subtypes', $va_facet_info, false) ? $va_exclude_types : $va_exclude_types_expanded) . ")";
             }
             if (isset($pa_options['checkAccess']) && is_array($pa_options['checkAccess']) && sizeof($pa_options['checkAccess']) && $t_rel_item->hasField('access')) {
                 $va_wheres[] = "(" . $t_rel_item->tableName() . ".access IN (" . join(',', $pa_options['checkAccess']) . "))";
                 // exclude non-accessible authority items
                 if (!$va_facet_info['show_all_when_first_facet'] || $this->numCriteria() > 0) {
                     $va_wheres[] = "(" . $vs_browse_table_name . ".access IN (" . join(',', $pa_options['checkAccess']) . "))";
                     // exclude non-accessible browse items
                 }
             }
             if ($t_item->hasField('deleted') && !$va_facet_info['show_all_when_first_facet']) {
                 $va_wheres[] = "(" . $t_item->tableName() . ".deleted = 0)";
             }
             if ($t_rel_item->hasField('deleted')) {
                 $va_wheres[] = "(" . $t_rel_item->tableName() . ".deleted = 0)";
             }
             $vs_rel_pk = $t_rel_item->primaryKey();
             $va_rel_attr_elements = $t_rel_item->getApplicableElementCodes(null, true, false);
             $va_attrs_to_fetch = array();
             if (!$va_facet_info['show_all_when_first_facet'] || $this->numCriteria() > 0) {
                 //$va_selects[] = $t_item->tableName().'.'.$t_item->primaryKey();			// get primary key of subject
             }
             $va_selects[] = $t_rel_item->tableName() . '.' . $vs_rel_pk;
             // get primary key of related
             $vs_hier_parent_id_fld = $vs_hier_id_fld = null;
             if ($vb_rel_is_hierarchical) {
                 $vs_hier_parent_id_fld = $t_rel_item->getProperty('HIERARCHY_PARENT_ID_FLD');
                 $va_selects[] = $t_rel_item->tableName() . '.' . $vs_hier_parent_id_fld;
                 if ($vs_hier_id_fld = $t_rel_item->getProperty('HIERARCHY_ID_FLD')) {
                     $va_selects[] = $t_rel_item->tableName() . '.' . $vs_hier_id_fld;
                 }
             }
             // analyze group_fields (if defined) and add them to the query
             $va_groupings_to_fetch = array();
             if (isset($va_facet_info['groupings']) && is_array($va_facet_info['groupings']) && sizeof($va_facet_info['groupings'])) {
                 foreach ($va_facet_info['groupings'] as $vs_grouping => $vs_grouping_name) {
                     // is grouping type_id?
                     if ($vs_grouping === 'type' && $t_rel_item->hasField('type_id')) {
                         $va_selects[] = $t_rel_item->tableName() . '.type_id';
                         $va_groupings_to_fetch[] = 'type_id';
                     }
                     // is group field a relationship type?
                     if ($vs_grouping === 'relationship_types') {
                         $va_selects[] = $va_facet_info['relationship_table'] . '.type_id rel_type_id';
                         $va_groupings_to_fetch[] = 'rel_type_id';
                     }
                     // is group field an attribute?
                     if (preg_match('!^ca_attribute_([^:]*)!', $vs_grouping, $va_matches)) {
                         if ($vn_element_id = array_search($va_matches[1], $va_rel_attr_elements)) {
                             $va_attrs_to_fetch[] = $vn_element_id;
                         }
                     }
                 }
             }
             if ($va_facet_info['relative_to']) {
                 // TODO: do this everywhere
                 $va_restrict_to_relationship_types = array();
                 $vs_browse_type_limit_sql = '';
                 if ($t_subject->hasField('deleted')) {
                     $va_wheres[] = "(" . $t_subject->tableName() . ".deleted = 0)";
                 }
                 if ($va_relative_sql_data = $this->_getRelativeFacetSQLData($va_facet_info['relative_to'], $pa_options)) {
                     $va_joins = array_merge($va_joins, $va_relative_sql_data['joins']);
                     $va_wheres = array_merge($va_wheres, $va_relative_sql_data['wheres']);
                 }
             }
             if (sizeof($va_restrict_to_relationship_types) > 0 && is_object($t_item_rel)) {
                 $va_wheres[] = $t_item_rel->tableName() . ".type_id IN (" . join(',', $va_restrict_to_relationship_types) . ")";
             }
             if (sizeof($va_exclude_relationship_types) > 0 && is_object($t_item_rel)) {
                 $va_wheres[] = $t_item_rel->tableName() . ".type_id NOT IN (" . join(',', $va_exclude_relationship_types) . ")";
             }
             if ($vs_browse_type_limit_sql) {
                 $va_wheres[] = $vs_browse_type_limit_sql;
             }
             if ($this->opo_config->get('perform_item_level_access_checking')) {
                 if ($t_item = $this->opo_datamodel->getInstanceByTableName($vs_browse_table_name, true)) {
                     // Join to limit what browse table items are used to generate facet
                     $va_joins[] = 'LEFT JOIN ca_acl ON ' . $vs_browse_table_name . '.' . $t_item->primaryKey() . ' = ca_acl.row_id AND ca_acl.table_num = ' . $t_item->tableNum() . "\n";
                     $va_wheres[] = "(\n\t\t\t\t\t\t\t\t((\n\t\t\t\t\t\t\t\t\t(ca_acl.user_id = " . (int) $vn_user_id . ")\n\t\t\t\t\t\t\t\t\t" . (sizeof($va_group_ids) > 0 ? "OR\n\t\t\t\t\t\t\t\t\t(ca_acl.group_id IN (" . join(",", $va_group_ids) . "))" : "") . "\n\t\t\t\t\t\t\t\t\tOR\n\t\t\t\t\t\t\t\t\t(ca_acl.user_id IS NULL and ca_acl.group_id IS NULL)\n\t\t\t\t\t\t\t\t) AND ca_acl.access >= " . __CA_ACL_READONLY_ACCESS__ . ")\n\t\t\t\t\t\t\t\t" . ($vb_show_if_no_acl ? "OR ca_acl.acl_id IS NULL" : "") . "\n\t\t\t\t\t\t\t)";
                     // Join to limit what related items are used to generate facet
                     $va_joins[] = 'LEFT JOIN ca_acl AS rel_acl ON ' . $t_rel_item->tableName() . '.' . $t_rel_item->primaryKey() . ' = rel_acl.row_id AND rel_acl.table_num = ' . $t_rel_item->tableNum() . "\n";
                     $va_wheres[] = "(\n\t\t\t\t\t\t\t\t((\n\t\t\t\t\t\t\t\t\t(rel_acl.user_id = " . (int) $vn_user_id . ")\n\t\t\t\t\t\t\t\t\t" . (sizeof($va_group_ids) > 0 ? "OR\n\t\t\t\t\t\t\t\t\t(rel_acl.group_id IN (" . join(",", $va_group_ids) . "))" : "") . "\n\t\t\t\t\t\t\t\t\tOR\n\t\t\t\t\t\t\t\t\t(rel_acl.user_id IS NULL and rel_acl.group_id IS NULL)\n\t\t\t\t\t\t\t\t) AND rel_acl.access >= " . __CA_ACL_READONLY_ACCESS__ . ")\n\t\t\t\t\t\t\t\t" . ($vb_show_if_no_acl ? "OR rel_acl.acl_id IS NULL" : "") . "\n\t\t\t\t\t\t\t)";
                 }
             }
             $vs_join_sql = join("\n", $va_joins);
             if ($vb_check_availability_only) {
                 if (!$va_facet_info['show_all_when_first_facet'] || $this->numCriteria() > 0) {
                     $vs_sql = "\n\t\t\t\t\t\t\tSELECT 1\n\t\t\t\t\t\t\tFROM " . $vs_browse_table_name . "\n\t\t\t\t\t\t\t{$vs_join_sql}\n\t\t\t\t\t\t\t\t" . (sizeof($va_wheres) ? ' WHERE ' : '') . join(" AND ", $va_wheres) . " LIMIT 1";
                 } else {
                     $vs_sql = "\n\t\t\t\t\t\t\tSELECT 1\n\t\t\t\t\t\t\tFROM " . $t_rel_item->tableName() . "\n\t\t\t\t\t\t\t{$vs_join_sql}\n\t\t\t\t\t\t\t\t" . (sizeof($va_wheres) ? ' WHERE ' : '') . join(" AND ", $va_wheres) . " LIMIT 1";
                 }
                 $qr_res = $this->opo_db->query($vs_sql);
                 //print "<hr>$vs_sql<hr>\n";
                 return (int) $qr_res->numRows() > 0 ? true : false;
             } else {
                 if (!$va_facet_info['show_all_when_first_facet'] || $this->numCriteria() > 0) {
                     $vs_sql = "\n\t\t\t\t\t\t\tSELECT DISTINCT " . join(', ', $va_selects) . "\n\t\t\t\t\t\t\tFROM " . $vs_browse_table_name . "\n\t\t\t\t\t\t\t{$vs_join_sql}\n\t\t\t\t\t\t\t\t" . (sizeof($va_wheres) ? ' WHERE ' : '') . join(" AND ", $va_wheres) . "\n\t\t\t\t\t\t\t\t" . (sizeof($va_orderbys) ? "ORDER BY " . join(', ', $va_orderbys) : '');
                 } else {
                     $vs_sql = "\n\t\t\t\t\t\t\tSELECT DISTINCT " . join(', ', $va_selects) . "\n\t\t\t\t\t\t\tFROM " . $t_rel_item->tableName() . "\n\t\t\t\t\t\t\t{$vs_join_sql}\n\t\t\t\t\t\t\t\t" . (sizeof($va_wheres) ? ' WHERE ' : '') . join(" AND ", $va_wheres) . "\n\t\t\t\t\t\t\t\t" . (sizeof($va_orderbys) ? "ORDER BY " . join(', ', $va_orderbys) : '');
                 }
                 //print "<hr>$vs_sql<hr>\n";
                 $qr_res = $this->opo_db->query($vs_sql);
                 $va_facet = $va_facet_items = array();
                 $vs_rel_pk = $t_rel_item->primaryKey();
                 // First get related ids with type and relationship type values
                 // (You could get all of the data we need for the facet in a single query but it turns out to be faster for very large facets to
                 // do it in separate queries, one for the primary ids and another for the labels; a third is done if attributes need to be fetched.
                 // There appears to be a significant [~10%] performance for smaller facets and a larger one [~20-25%] for very large facets)
                 $vn_max_level = caGetOption('maximum_levels', $va_facet_info, null);
                 while ($qr_res->nextRow()) {
                     $va_fetched_row = $qr_res->getRow();
                     $vn_id = $va_fetched_row[$vs_rel_pk];
                     //if (isset($va_facet_items[$vn_id])) { continue; } --- we can't do this as then we don't detect items that have multiple rel_type_ids... argh.
                     if (isset($va_criteria[$vn_id])) {
                         continue;
                     }
                     // skip items that are used as browse critera - don't want to browse on something you're already browsing on
                     if (!$va_facet_items[$va_fetched_row[$vs_rel_pk]]) {
                         // if(!is_null($vn_max_level)) {
                         // 									if (sizeof($va_ancestors) + 1 > $vn_max_level) {
                         // 										if ($va_tmp = $va_ancestors[sizeof($va_ancestors) - $vn_max_level]) {
                         // 											$va_ancestors = array();
                         // 											$va_fetched_row = $va_tmp['NODE'];
                         // 										}
                         // 									}
                         // 								}
                         if (is_array($va_restrict_to_types) && sizeof($va_restrict_to_types) && $va_fetched_row['type_id'] && !in_array($va_fetched_row['type_id'], $va_restrict_to_types)) {
                             continue;
                         }
                         $va_facet_items[$va_fetched_row[$vs_rel_pk]] = array('id' => $va_fetched_row[$vs_rel_pk], 'type_id' => array(), 'parent_id' => $vb_rel_is_hierarchical ? $va_fetched_row[$vs_hier_parent_id_fld] : null, 'hierarchy_id' => $vb_rel_is_hierarchical ? $va_fetched_row[$vs_hier_id_fld] : null, 'rel_type_id' => array(), 'child_count' => 0);
                         if (!is_null($vs_single_value) && $va_fetched_row[$vs_rel_pk] == $vs_single_value) {
                             $vb_single_value_is_present = true;
                         }
                     }
                     if ($va_fetched_row['type_id']) {
                         $va_facet_items[$va_fetched_row[$vs_rel_pk]]['type_id'][] = $va_fetched_row['type_id'];
                     }
                     if ($va_fetched_row['rel_type_id']) {
                         $va_facet_items[$va_fetched_row[$vs_rel_pk]]['rel_type_id'][] = $va_fetched_row['rel_type_id'];
                     }
                 }
                 if (!isset($va_facet_info['dont_expand_hierarchically']) || !$va_facet_info['dont_expand_hierarchically']) {
                     $qr_res->seek(0);
                     $va_ids = $qr_res->getAllFieldValues($vs_rel_pk);
                     $qr_ancestors = call_user_func($t_rel_item->tableName() . '::getHierarchyAncestorsForIDs', $va_ids, array('returnAs' => 'SearchResult'));
                     $vs_rel_table = $t_rel_item->tableName();
                     $vs_rel_pk = $t_rel_item->primaryKey();
                     $vb_check_ancestor_access = (bool) (isset($pa_options['checkAccess']) && is_array($pa_options['checkAccess']) && sizeof($pa_options['checkAccess']) && $t_rel_item->hasField('access'));
                     if ($qr_ancestors) {
                         while ($qr_ancestors->nextHit()) {
                             $vn_parent_type_id = $qr_ancestors->get('type_id');
                             if (sizeof($va_exclude_types) > 0 && in_array($vn_parent_type_id, $va_exclude_types)) {
                                 continue;
                             }
                             if (sizeof($va_restrict_to_types) > 0 && !in_array($vn_parent_type_id, $va_restrict_to_types)) {
                                 continue;
                             }
                             if ($vb_check_ancestor_access && !in_array($qr_ancestors->get('access'), $pa_options['checkAccess'])) {
                                 continue;
                             }
                             $va_facet_items[$vn_ancestor_id = (int) $qr_ancestors->get("{$vs_rel_pk}")] = array('id' => $vn_ancestor_id, 'type_id' => array(), 'parent_id' => $vb_rel_is_hierarchical ? $qr_ancestors->get("{$vs_hier_parent_id_fld}") : null, 'hierarchy_id' => $vb_rel_is_hierarchical && $vs_hier_id_fld ? $qr_ancestors->get($vs_hier_id_fld) : null, 'rel_type_id' => array(), 'child_count' => 0);
                         }
                     }
                 }
                 // Set child counts
                 foreach ($va_facet_items as $vn_i => $va_item) {
                     if ($va_item['parent_id'] && isset($va_facet_items[$va_item['parent_id']])) {
                         $va_facet_items[$va_item['parent_id']]['child_count']++;
                     }
                 }
                 // Get labels for facet items
                 if (sizeof($va_row_ids = array_keys($va_facet_items))) {
                     if ($vs_label_table_name = $t_rel_item->getLabelTableName()) {
                         $t_rel_item_label = $this->opo_datamodel->getInstanceByTableName($vs_label_table_name, true);
                         $vs_label_display_field = $t_rel_item_label->getDisplayField();
                         $vs_rel_pk = $t_rel_item->primaryKey();
                         $va_label_wheres = array();
                         if ($t_rel_item_label->hasField('is_preferred')) {
                             $va_label_wheres[] = "({$vs_label_table_name}.is_preferred = 1)";
                         }
                         $va_label_wheres[] = "({$vs_label_table_name}.{$vs_rel_pk} IN (" . join(",", $va_row_ids) . "))";
                         $va_label_selects[] = "{$vs_label_table_name}.{$vs_rel_pk}";
                         $va_label_selects[] = "{$vs_label_table_name}.locale_id";
                         $va_label_fields = $t_rel_item->getLabelUIFields();
                         foreach ($va_label_fields as $vs_label_field) {
                             $va_label_selects[] = "{$vs_label_table_name}.{$vs_label_field}";
                         }
                         // Get label ordering fields
                         $va_ordering_fields_to_fetch = isset($va_facet_info['order_by_label_fields']) && is_array($va_facet_info['order_by_label_fields']) ? $va_facet_info['order_by_label_fields'] : array();
                         $va_orderbys = array();
                         foreach ($va_ordering_fields_to_fetch as $vs_sort_by_field) {
                             if (!$t_rel_item_label->hasField($vs_sort_by_field)) {
                                 continue;
                             }
                             $va_orderbys[] = $va_label_selects[] = $vs_label_table_name . '.' . $vs_sort_by_field;
                         }
                         // get labels
                         $vs_sql = "\n\t\t\t\t\t\t\t\t\tSELECT " . join(', ', $va_label_selects) . "\n\t\t\t\t\t\t\t\t\tFROM " . $vs_label_table_name . "\n\t\t\t\t\t\t\t\t\t\t" . (sizeof($va_label_wheres) ? ' WHERE ' : '') . join(" AND ", $va_label_wheres) . "\n\t\t\t\t\t\t\t\t\t\t" . (sizeof($va_orderbys) ? "ORDER BY " . join(', ', $va_orderbys) : '') . "";
                         //print $vs_sql;
                         $qr_labels = $this->opo_db->query($vs_sql);
                         while ($qr_labels->nextRow()) {
                             $va_fetched_row = $qr_labels->getRow();
                             $va_facet_item = array_merge($va_facet_items[$va_fetched_row[$vs_rel_pk]], array('label' => $va_fetched_row[$vs_label_display_field]));
                             foreach ($va_ordering_fields_to_fetch as $vs_to_fetch) {
                                 $va_facet_item[$vs_to_fetch] = $va_fetched_row[$vs_to_fetch];
                             }
                             $va_facet[$va_fetched_row[$vs_rel_pk]][$va_fetched_row['locale_id']] = $va_facet_item;
                         }
                     }
                     // get attributes for facet items
                     if (sizeof($va_attrs_to_fetch)) {
                         $qr_attrs = $this->opo_db->query("\n\t\t\t\t\t\t\t\t\tSELECT c_av.*, c_a.locale_id, c_a.row_id\n\t\t\t\t\t\t\t\t\tFROM ca_attributes c_a\n\t\t\t\t\t\t\t\t\tINNER JOIN ca_attribute_values c_av ON c_a.attribute_id = c_av.attribute_id\n\t\t\t\t\t\t\t\t\tWHERE\n\t\t\t\t\t\t\t\t\t\tc_av.element_id IN (" . join(',', $va_attrs_to_fetch) . ")\n\t\t\t\t\t\t\t\t\t\tAND\n\t\t\t\t\t\t\t\t\t\tc_a.table_num = ? \n\t\t\t\t\t\t\t\t\t\tAND \n\t\t\t\t\t\t\t\t\t\tc_a.row_id IN (" . join(',', $va_row_ids) . ")\n\t\t\t\t\t\t\t\t", $t_rel_item->tableNum());
                         while ($qr_attrs->nextRow()) {
                             $va_fetched_row = $qr_attrs->getRow();
                             $vn_id = $va_fetched_row['row_id'];
                             // if no locale is set for the attribute default it to whatever the locale for the item is
                             if (!($vn_locale_id = $va_fetched_row['locale_id'])) {
                                 $va_tmp = array_keys($va_facet[$vn_id]);
                                 $vn_locale_id = $va_tmp[0];
                             }
                             $va_facet[$vn_id][$vn_locale_id]['ca_attribute_' . $va_fetched_row['element_id']][] = $va_fetched_row;
                         }
                     }
                 }
                 if (!is_null($vs_single_value) && !$vb_single_value_is_present) {
                     return array();
                 }
                 return caExtractValuesByUserLocale($va_facet);
             }
             break;
             # -----------------------------------------------------
         # -----------------------------------------------------
         default:
             return null;
             break;
             # -----------------------------------------------------
     }
 }
 /**
  * Given a item_id (request parameter 'id') returns a list of ancestors for use in the hierarchy browser
  * Returned data is JSON format
  */
 public function getFacetHierarchyAncestorList()
 {
     $pn_id = $this->request->getParameter('id', pInteger);
     $ps_facet_name = $this->request->getParameter('facet', pString);
     if (!is_array($va_facet_info = $this->opo_browse->getInfoForFacet($ps_facet_name))) {
         return null;
     }
     $va_ancestors = array();
     switch ($va_facet_info['type']) {
         case 'attribute':
             // is it a list attribute?
             $t_element = new ca_metadata_elements();
             if ($t_element->load(array('element_code' => $va_facet_info['element_code']))) {
                 if ($t_element->get('datatype') == 3) {
                     // 3=list
                     if (!$pn_id) {
                         $t_list = new ca_lists();
                         $pn_id = $t_list->getRootListItemID($t_element->get('list_id'));
                     }
                     $t_item = new ca_list_items($pn_id);
                     if ($t_item->getPrimaryKey()) {
                         $va_ancestors = array_reverse($t_item->getHierarchyAncestors(null, array('includeSelf' => true, 'idsOnly' => true)));
                         array_shift($va_ancestors);
                     }
                 }
             }
             break;
         case 'label':
             // label facet
             $va_facet_info['table'] = $this->ops_tablename;
             // fall through to default case
         // fall through to default case
         default:
             $t_item = $this->opo_datamodel->getInstanceByTableName($va_facet_info['table']);
             $t_item->load($pn_id);
             if (method_exists($t_item, "getHierarchyList")) {
                 $va_access_values = caGetUserAccessValues($this->request);
                 $va_facet = $this->opo_browse->getFacet($ps_facet_name, array('sort' => 'name', 'checkAccess' => $va_access_values));
                 $va_hierarchy_list = $t_item->getHierarchyList(true);
                 $vn_hierarchies_in_use = 0;
                 foreach ($va_hierarchy_list as $vn_i => $va_item) {
                     if (isset($va_facet[$va_item[$t_item->primaryKey()]])) {
                         $vn_hierarchies_in_use++;
                         if ($vn_hierarchies_in_use > 1) {
                             break;
                         }
                     }
                 }
             }
             if ($t_item->getPrimaryKey()) {
                 $va_ancestors = array_reverse($t_item->getHierarchyAncestors(null, array('includeSelf' => true, 'idsOnly' => true)));
                 if (!is_array($va_ancestors)) {
                     $va_ancestors = array();
                 }
             }
             if ($vn_hierarchies_in_use <= 1) {
                 array_shift($va_ancestors);
             }
             break;
     }
     $this->view->setVar('ancestors', $va_ancestors);
     return $this->render('Browse/facet_hierarchy_ancestors_json.php');
 }
Example #11
0
 private function processMetadataElement($po_element, $pn_parent_id)
 {
     require_once __CA_MODELS_DIR__ . "/ca_metadata_elements.php";
     require_once __CA_MODELS_DIR__ . "/ca_lists.php";
     if (($vn_datatype = ca_metadata_elements::getAttributeTypeCode(self::getAttribute($po_element, "datatype"))) === false) {
         return false;
         // should not happen due to XSD restrictions, but just in case
     }
     $vs_element_code = self::getAttribute($po_element, "code");
     $t_lists = new ca_lists();
     if ($this->opb_updating) {
         $t_md_element = ca_metadata_elements::getInstance($vs_element_code) ? ca_metadata_elements::getInstance($vs_element_code) : new ca_metadata_elements();
     } else {
         $t_md_element = new ca_metadata_elements();
     }
     $t_md_element->setMode(ACCESS_WRITE);
     $t_md_element->set('element_code', $vs_element_code);
     $t_md_element->set('parent_id', $pn_parent_id);
     $t_md_element->set('documentation_url', (string) $po_element->documentationUrl);
     $t_md_element->set('datatype', $vn_datatype);
     $vs_list = self::getAttribute($po_element, "list");
     if (isset($vs_list) && $vs_list && $t_lists->load(array('list_code' => $vs_list))) {
         $vn_list_id = $t_lists->getPrimaryKey();
     } else {
         $vn_list_id = null;
     }
     $t_md_element->set('list_id', $vn_list_id);
     $this->_processSettings($t_md_element, $po_element->settings);
     if ($t_md_element->getPrimaryKey()) {
         $t_md_element->update();
     } else {
         $t_md_element->insert();
     }
     if ($t_md_element->numErrors()) {
         $this->addError("There was an error while inserting metadata element {$vs_element_code}: " . join(" ", $t_md_element->getErrors()));
         return false;
     }
     $vn_element_id = $t_md_element->getPrimaryKey();
     // add element labels
     self::addLabelsFromXMLElement($t_md_element, $po_element->labels, $this->opa_locales);
     if ($po_element->elements) {
         foreach ($po_element->elements->children() as $vo_child) {
             $this->processMetadataElement($vo_child, $vn_element_id);
         }
     }
     return $vn_element_id;
 }
        print caNavUrl($this->request, 'administrate/setup', 'Elements', 'Edit', array('parent_id' => $vn_element_id, 'element_id' => $va_sub_element['element_id']));
        ?>
" class="caDeleteLabelButton"><?php 
        print caNavIcon($this->request, __CA_NAV_BUTTON_EDIT__);
        ?>
</a>
			<a href="<?php 
        print caNavUrl($this->request, 'administrate/setup', 'Elements', 'Delete', array('parent_id' => $vn_element_id, 'element_id' => $va_sub_element['element_id']));
        ?>
" class="caDeleteLabelButton"><?php 
        print caNavIcon($this->request, __CA_NAV_BUTTON_DEL_BUNDLE__);
        ?>
</a>
			<span class="labelDisplay">
				<?php 
        print $va_sub_element['name'] . ' (' . $va_sub_element['element_code'] . ') [' . ca_metadata_elements::getAttributeNameForTypeCode($va_sub_element['datatype']) . ']';
        ?>
			</span>
		</div>
<?php 
    }
    ?>
		</div>
		<div class="button labelInfo caAddLabelButton">
			<a href="<?php 
    print caNavUrl($this->request, 'administrate/setup', 'Elements', 'Edit', array('parent_id' => $vn_element_id, 'element_id' => 0));
    ?>
">
				<?php 
    print caNavIcon($this->request, __CA_NAV_BUTTON_ADD__);
    ?>
Example #13
0
 /**
  * Return HTML form element for editing.
  *
  * @param array $pa_element_info An array of information about the metadata element being edited
  * @param array $pa_options array Options include:
  *			usewysiwygeditor = overrides element level setting for visual text editor [Default=false]
  *			forSearch = settings and options regarding visual text editor are ignored [Default=false]
  *			class = the CSS class to apply to all visible form elements [Default=null]
  *			width = the width of the form element [Default=field width defined in metadata element definition]
  *			height = the height of the form element [Default=field height defined in metadata element definition]
  *			t_subject = an instance of the model to which the attribute belongs; required if suggestExistingValues lookups are enabled [Default is null]
  *			request = the RequestHTTP object for the current request; required if suggestExistingValues lookups are enabled [Default is null]
  *			suggestExistingValues = suggest values based on existing input for this element as user types [Default is false]		
  *
  * @return string
  */
 public function htmlFormElement($pa_element_info, $pa_options = null)
 {
     $va_settings = $this->getSettingValuesFromElementArray($pa_element_info, array('fieldWidth', 'fieldHeight', 'minChars', 'maxChars', 'suggestExistingValues', 'usewysiwygeditor', 'isDependentValue', 'dependentValueTemplate'));
     if (isset($pa_options['usewysiwygeditor'])) {
         $va_settings['usewysiwygeditor'] = $pa_options['usewysiwygeditor'];
     }
     if (isset($pa_options['forSearch']) && $pa_options['forSearch']) {
         unset($va_settings['usewysiwygeditor']);
     }
     $vs_width = trim(isset($pa_options['width']) && $pa_options['width'] > 0 ? $pa_options['width'] : $va_settings['fieldWidth']);
     $vs_height = trim(isset($pa_options['height']) && $pa_options['height'] > 0 ? $pa_options['height'] : $va_settings['fieldHeight']);
     $vs_class = trim(isset($pa_options['class']) && $pa_options['class'] ? $pa_options['class'] : '');
     $vs_element = '';
     if (!preg_match("!^[\\d\\.]+px\$!i", $vs_width)) {
         $vs_width = (int) $vs_width * 6 . "px";
     }
     if (!preg_match("!^[\\d\\.]+px\$!i", $vs_height)) {
         $vs_height = (int) $vs_height * 16 . "px";
     }
     if ($va_settings['usewysiwygeditor']) {
         $o_config = Configuration::load();
         if (!is_array($va_toolbar_config = $o_config->getAssoc('wysiwyg_editor_toolbar'))) {
             $va_toolbar_config = array();
         }
         AssetLoadManager::register("ckeditor");
         $vs_element = "<script type='text/javascript'>jQuery(document).ready(function() {\n\t\t\t\t\t\tvar ckEditor = CKEDITOR.replace( '{fieldNamePrefix}" . $pa_element_info['element_id'] . "_{n}',\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttoolbar : " . json_encode(array_values($va_toolbar_config)) . ", /* this does the magic */\n\t\t\t\t\t\t\twidth: '{$vs_width}',\n\t\t\t\t\t\t\theight: '{$vs_height}',\n\t\t\t\t\t\t\ttoolbarLocation: 'top',\n\t\t\t\t\t\t\tenterMode: CKEDITOR.ENTER_BR\n\t\t\t\t\t\t});\n\t\t\t\t\t\t\n\t\t\t\t\t\tckEditor.on('instanceReady', function(){ \n\t\t\t\t\t\t\t ckEditor.document.on( 'keydown', function(e) {if (caUI && caUI.utils) { caUI.utils.showUnsavedChangesWarning(true); } });\n\t\t\t\t\t\t});\n \t});\t\t\t\t\t\t\t\t\t\n</script>";
     }
     $va_opts = array('size' => $vs_width, 'height' => $vs_height, 'value' => '{{' . $pa_element_info['element_id'] . '}}', 'maxlength' => $va_settings['maxChars'], 'class' => $vs_class, 'id' => '{fieldNamePrefix}' . $pa_element_info['element_id'] . '_{n}', 'class' => "{$vs_class}" . ($va_settings['usewysiwygeditor'] ? " ckeditor" : ''));
     if (caGetOption('readonly', $pa_options, false)) {
         $va_opts['disabled'] = 1;
     }
     $vs_element .= caHTMLTextInput('{fieldNamePrefix}' . $pa_element_info['element_id'] . '_{n}', $va_opts);
     if ($va_settings['isDependentValue']) {
         AssetLoadManager::register('displayTemplateParser');
         $t_element = new ca_metadata_elements($pa_element_info['element_id']);
         $va_elements = $t_element->getElementsInSet($t_element->getHierarchyRootID());
         $va_element_dom_ids = array();
         foreach ($va_elements as $vn_i => $va_element) {
             if ($va_element['datatype'] == __CA_ATTRIBUTE_VALUE_CONTAINER__) {
                 continue;
             }
             $va_element_dom_ids[$va_element['element_code']] = "#{fieldNamePrefix}" . $va_element['element_id'] . "_{n}";
         }
         $vs_element .= "<script type='text/javascript'>jQuery(document).ready(function() {\n \t\t\t\t\tjQuery('#{fieldNamePrefix}" . $pa_element_info['element_id'] . "_{n}').html(caDisplayTemplateParser.processDependentTemplate('" . addslashes($va_settings['dependentValueTemplate']) . "', " . json_encode($va_element_dom_ids, JSON_FORCE_OBJECT) . "));\n \t\t\t\t";
         $vs_element .= "jQuery('" . join(", ", $va_element_dom_ids) . "').bind('keyup', function(e) { \n \t\t\t\t\tjQuery('#{fieldNamePrefix}" . $pa_element_info['element_id'] . "_{n}').html(caDisplayTemplateParser.processDependentTemplate('" . addslashes($va_settings['dependentValueTemplate']) . "', " . json_encode($va_element_dom_ids, JSON_FORCE_OBJECT) . "));\n \t\t\t\t});";
         $vs_element .= "});</script>";
     }
     $vs_bundle_name = $vs_lookup_url = null;
     if (isset($pa_options['t_subject']) && is_object($pa_options['t_subject'])) {
         $vs_bundle_name = $pa_options['t_subject']->tableName() . '.' . $pa_element_info['element_code'];
         if ($pa_options['request']) {
             if (isset($pa_options['lookupUrl']) && $pa_options['lookupUrl']) {
                 $vs_lookup_url = $pa_options['lookupUrl'];
             } else {
                 $vs_lookup_url = caNavUrl($pa_options['request'], 'lookup', 'AttributeValue', 'Get', array('max' => 500, 'bundle' => $vs_bundle_name));
             }
         }
     }
     if ($va_settings['suggestExistingValues'] && $vs_lookup_url && $vs_bundle_name) {
         $vs_element .= "<script type='text/javascript'>\n \t\t\t\t\tjQuery('#{fieldNamePrefix}" . $pa_element_info['element_id'] . "_{n}').autocomplete( \n\t\t\t\t\t\t{ \n\t\t\t\t\t\t\tsource: '{$vs_lookup_url}',\n\t\t\t\t\t\t\tminLength: 3, delay: 800\n\t\t\t\t\t\t}\n\t\t\t\t\t);\n \t\t\t\t</script>\n";
     }
     return $vs_element;
 }
Example #14
0
 private function _doQueriesForSqlSearch($po_rewritten_query, $pn_subject_tablenum, $ps_dest_table, $pn_level = 0)
 {
     // query is always of type Zend_Search_Lucene_Search_Query_Boolean
     $vn_i = 0;
     $va_old_signs = $po_rewritten_query->getSigns();
     foreach ($po_rewritten_query->getSubqueries() as $o_lucene_query_element) {
         $vb_is_blank_search = false;
         if (is_null($va_old_signs)) {
             // if array is null then according to Zend Lucene all subqueries should be "are required"... so we AND them
             $vs_op = "AND";
         } else {
             if (is_null($va_old_signs[$vn_i])) {
                 // is the sign for a particular query is null then OR is (it is "neither required nor prohibited")
                 $vs_op = 'OR';
             } else {
                 $vs_op = $va_old_signs[$vn_i] === false ? 'NOT' : 'AND';
                 // true sign indicated "required" (AND) operation, false indicated "prohibited" (NOT) operation
             }
         }
         if ($vn_i == 0) {
             $vs_op = 'OR';
         }
         $va_direct_query_temp_tables = array();
         // List of temporary tables created by direct search queries; tables listed here are dropped at the end of processing for the query element
         switch (get_class($o_lucene_query_element)) {
             case 'Zend_Search_Lucene_Search_Query_Boolean':
                 $this->_createTempTable('ca_sql_search_temp_' . $pn_level);
                 $this->_doQueriesForSqlSearch($o_lucene_query_element, $pn_subject_tablenum, 'ca_sql_search_temp_' . $pn_level, $pn_level + 1);
                 // merge with current destination
                 switch ($vs_op) {
                     case 'AND':
                         // and
                         $this->_createTempTable($ps_dest_table . '_acc');
                         if ($vn_i == 0) {
                             $vs_sql = "\n\t\t\t\t\t\t\t\t\tINSERT IGNORE INTO {$ps_dest_table}\n\t\t\t\t\t\t\t\t\tSELECT DISTINCT row_id, boost\n\t\t\t\t\t\t\t\t\tFROM ca_sql_search_temp_{$pn_level}\n\t\t\t\t\t\t\t\t";
                             //print "$vs_sql<hr>";
                             $qr_res = $this->opo_db->query($vs_sql);
                         } else {
                             $vs_sql = "\n\t\t\t\t\t\t\t\t\tINSERT IGNORE INTO {$ps_dest_table}_acc\n\t\t\t\t\t\t\t\t\tSELECT mfs.row_id, SUM(mfs.boost)\n\t\t\t\t\t\t\t\t\tFROM {$ps_dest_table} mfs\n\t\t\t\t\t\t\t\t\tINNER JOIN ca_sql_search_temp_{$pn_level} AS ftmp1 ON ftmp1.row_id = mfs.row_id\n\t\t\t\t\t\t\t\t\tGROUP BY mfs.row_id\n\t\t\t\t\t\t\t\t";
                             //print "$vs_sql<hr>";
                             $qr_res = $this->opo_db->query($vs_sql);
                             $qr_res = $this->opo_db->query("TRUNCATE TABLE {$ps_dest_table}");
                             $qr_res = $this->opo_db->query("INSERT INTO {$ps_dest_table} SELECT row_id, boost FROM {$ps_dest_table}_acc");
                         }
                         $this->_dropTempTable($ps_dest_table . '_acc');
                         break;
                     case 'NOT':
                         $vs_sql = "\n\t\t\t\t\t\t\t\tDELETE FROM {$ps_dest_table} WHERE row_id IN\n\t\t\t\t\t\t\t\t(SELECT row_id FROM ca_sql_search_temp_{$pn_level})\n\t\t\t\t\t\t\t";
                         //print "$vs_sql<hr>";
                         $qr_res = $this->opo_db->query($vs_sql);
                         break;
                     default:
                     case 'OR':
                         // or
                         $vs_sql = "\n\t\t\t\t\t\t\t\tINSERT IGNORE INTO {$ps_dest_table}\n\t\t\t\t\t\t\t\tSELECT row_id, SUM(boost)\n\t\t\t\t\t\t\t\tFROM ca_sql_search_temp_{$pn_level}\n\t\t\t\t\t\t\t\tGROUP BY row_id\n\t\t\t\t\t\t\t";
                         //print "$vs_sql<hr>";
                         $qr_res = $this->opo_db->query($vs_sql);
                         break;
                 }
                 $this->_dropTempTable('ca_sql_search_temp_' . $pn_level);
                 break;
             case 'Zend_Search_Lucene_Search_Query_Term':
             case 'Zend_Search_Lucene_Search_Query_MultiTerm':
             case 'Zend_Search_Lucene_Search_Query_Phrase':
             case 'Zend_Search_Lucene_Search_Query_Range':
                 $va_ft_terms = array();
                 $va_ft_like_terms = array();
                 $va_ft_stem_terms = array();
                 $vs_direct_sql_query = null;
                 $pa_direct_sql_query_params = null;
                 // set to array with values to use with direct SQL query placeholders or null to pass single standard table_num value as param (most queries just need this single value)
                 $va_tmp = array();
                 $vs_access_point = '';
                 $va_raw_terms = array();
                 switch (get_class($o_lucene_query_element)) {
                     case 'Zend_Search_Lucene_Search_Query_Range':
                         $va_lower_term = $o_lucene_query_element->getLowerTerm();
                         $va_upper_term = $o_lucene_query_element->getUpperTerm();
                         $va_element = $this->_getElementIDForAccessPoint($va_lower_term->field);
                         switch ($va_element['datatype']) {
                             case 4:
                                 // geocode
                                 $t_geocode = new GeocodeAttributeValue();
                                 $va_parsed_value = $t_geocode->parseValue($va_lower_term->text, $va_element['element_info']);
                                 $vs_lower_lat = $va_parsed_value['value_decimal1'];
                                 $vs_lower_long = $va_parsed_value['value_decimal2'];
                                 $va_parsed_value = $t_geocode->parseValue($va_upper_term->text, $va_element['element_info']);
                                 $vs_upper_lat = $va_parsed_value['value_decimal1'];
                                 $vs_upper_long = $va_parsed_value['value_decimal2'];
                                 $vs_direct_sql_query = "\n\t\t\t\t\t\t\t\t\t\tSELECT ca.row_id, 1\n\t\t\t\t\t\t\t\t\t\tFROM ca_attribute_values cav\n\t\t\t\t\t\t\t\t\t\tINNER JOIN ca_attributes AS ca ON ca.attribute_id = cav.attribute_id\n\t\t\t\t\t\t\t\t\t\t^JOIN\n\t\t\t\t\t\t\t\t\t\tWHERE\n\t\t\t\t\t\t\t\t\t\t\t(cav.element_id = " . intval($va_element['element_id']) . ") AND (ca.table_num = ?)\n\t\t\t\t\t\t\t\t\t\t\tAND\n\t\t\t\t\t\t\t\t\t\t\t(cav.value_decimal1 BETWEEN " . floatval($vs_lower_lat) . " AND " . floatval($vs_upper_lat) . ")\n\t\t\t\t\t\t\t\t\t\t\tAND\n\t\t\t\t\t\t\t\t\t\t\t(cav.value_decimal2 BETWEEN " . floatval($vs_lower_long) . " AND " . floatval($vs_upper_long) . ")\t\n\t\t\t\t\t\t\t\t\t";
                                 break;
                             case 6:
                                 // currency
                                 $t_cur = new CurrencyAttributeValue();
                                 $va_parsed_value = $t_cur->parseValue($va_lower_term->text, $va_element['element_info']);
                                 $vs_currency = preg_replace('![^A-Z0-9]+!', '', $va_parsed_value['value_longtext1']);
                                 $vn_lower_val = $va_parsed_value['value_decimal1'];
                                 $va_parsed_value = $t_cur->parseValue($va_upper_term->text, $va_element['element_info']);
                                 $vn_upper_val = $va_parsed_value['value_decimal1'];
                                 $vs_direct_sql_query = "\n\t\t\t\t\t\t\t\t\t\tSELECT ca.row_id, 1\n\t\t\t\t\t\t\t\t\t\tFROM ca_attribute_values cav\n\t\t\t\t\t\t\t\t\t\tINNER JOIN ca_attributes AS ca ON ca.attribute_id = cav.attribute_id\n\t\t\t\t\t\t\t\t\t\t^JOIN\n\t\t\t\t\t\t\t\t\t\tWHERE\n\t\t\t\t\t\t\t\t\t\t\t(cav.element_id = " . intval($va_element['element_id']) . ") AND (ca.table_num = ?)\n\t\t\t\t\t\t\t\t\t\t\tAND\n\t\t\t\t\t\t\t\t\t\t\t(cav.value_decimal1 BETWEEN " . floatval($vn_lower_val) . " AND " . floatval($vn_upper_val) . ")\n\t\t\t\t\t\t\t\t\t\t\tAND\n\t\t\t\t\t\t\t\t\t\t\t(cav.value_longtext1 = '" . $this->opo_db->escape($vs_currency) . "')\n\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t";
                                 break;
                             case 10:
                                 // timecode
                                 $t_timecode = new TimecodeAttributeValue();
                                 $va_parsed_value = $t_timecode->parseValue($va_lower_term->text, $va_element['element_info']);
                                 $vn_lower_val = $va_parsed_value['value_decimal1'];
                                 $va_parsed_value = $t_timecode->parseValue($va_upper_term->text, $va_element['element_info']);
                                 $vn_upper_val = $va_parsed_value['value_decimal1'];
                                 break;
                             case 8:
                                 // length
                                 $t_len = new LengthAttributeValue();
                                 $va_parsed_value = $t_len->parseValue($va_lower_term->text, $va_element['element_info']);
                                 $vn_lower_val = $va_parsed_value['value_decimal1'];
                                 $va_parsed_value = $t_len->parseValue($va_upper_term->text, $va_element['element_info']);
                                 $vn_upper_val = $va_parsed_value['value_decimal1'];
                                 break;
                             case 9:
                                 // weight
                                 $t_weight = new WeightAttributeValue();
                                 $va_parsed_value = $t_weight->parseValue($va_lower_term->text, $va_element['element_info']);
                                 $vn_lower_val = $va_parsed_value['value_decimal1'];
                                 $va_parsed_value = $t_weight->parseValue($va_upper_term->text, $va_element['element_info']);
                                 $vn_upper_val = $va_parsed_value['value_decimal1'];
                                 break;
                             case 11:
                                 // integer
                                 $vn_lower_val = intval($va_lower_term->text);
                                 $vn_upper_val = intval($va_upper_term->text);
                                 $vs_direct_sql_query = "\n\t\t\t\t\t\t\t\t\t\tSELECT ca.row_id, 1\n\t\t\t\t\t\t\t\t\t\tFROM ca_attribute_values cav\n\t\t\t\t\t\t\t\t\t\tINNER JOIN ca_attributes AS ca ON ca.attribute_id = cav.attribute_id\n\t\t\t\t\t\t\t\t\t\t^JOIN\n\t\t\t\t\t\t\t\t\t\tWHERE\n\t\t\t\t\t\t\t\t\t\t\t(cav.element_id = " . intval($va_element['element_id']) . ") AND (ca.table_num = ?)\n\t\t\t\t\t\t\t\t\t\t\tAND\n\t\t\t\t\t\t\t\t\t\t\t(cav.value_integer1 BETWEEN " . floatval($vn_lower_val) . " AND " . floatval($vn_upper_val) . ")\n\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t";
                                 break;
                             case 12:
                                 // decimal
                                 $vn_lower_val = floatval($va_lower_term->text);
                                 $vn_upper_val = floatval($va_upper_term->text);
                                 break;
                         }
                         if (!$vs_direct_sql_query) {
                             $vs_direct_sql_query = "\n\t\t\t\t\t\t\t\t\tSELECT ca.row_id, 1\n\t\t\t\t\t\t\t\t\tFROM ca_attribute_values cav\n\t\t\t\t\t\t\t\t\tINNER JOIN ca_attributes AS ca ON ca.attribute_id = cav.attribute_id\n\t\t\t\t\t\t\t\t\t^JOIN\n\t\t\t\t\t\t\t\t\tWHERE\n\t\t\t\t\t\t\t\t\t\t(cav.element_id = " . intval($va_element['element_id']) . ") AND (ca.table_num = ?)\n\t\t\t\t\t\t\t\t\t\tAND\n\t\t\t\t\t\t\t\t\t\t(cav.value_decimal1 BETWEEN " . floatval($vn_lower_val) . " AND " . floatval($vn_upper_val) . ")\n\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t";
                         }
                         break;
                     case 'Zend_Search_Lucene_Search_Query_Phrase':
                         $va_words = array();
                         foreach ($o_lucene_query_element->getQueryTerms() as $o_term) {
                             if (!$vs_access_point && ($vs_field = $o_term->field)) {
                                 $vs_access_point = $vs_field;
                             }
                             $va_raw_terms[] = $vs_text = (string) $o_term->text;
                             if (strlen($vs_escaped_text = $this->opo_db->escape($vs_text))) {
                                 $va_words[] = $vs_escaped_text;
                             }
                         }
                         if (!sizeof($va_words)) {
                             continue 3;
                         }
                         $va_ap_tmp = explode(".", $vs_access_point);
                         $vn_fld_table = $vn_fld_num = null;
                         if (sizeof($va_ap_tmp) == 2) {
                             $va_element = $this->_getElementIDForAccessPoint($vs_access_point);
                             if ($va_element) {
                                 $vs_fld_num = $va_element['field_num'];
                                 $vs_fld_table_num = $va_element['table_num'];
                                 $vs_fld_limit_sql = " AND (swi.field_table_num = {$vs_fld_table_num} AND swi.field_num = '{$vs_fld_num}')";
                             }
                         }
                         $va_temp_tables = array();
                         $vn_w = 0;
                         foreach ($va_words as $vs_word) {
                             $vn_w++;
                             $vs_temp_table = 'ca_sql_search_phrase_' . md5($pn_subject_tablenum . "/" . $vs_word . "/" . $vn_w);
                             $this->_createTempTable($vs_temp_table);
                             $vs_sql = "\n\t\t\t\t\t\t\t\t\tINSERT INTO {$vs_temp_table}\n\t\t\t\t\t\t\t\t\tSELECT swi.index_id + 1, 1\n\t\t\t\t\t\t\t\t\tFROM ca_sql_search_words sw \n\t\t\t\t\t\t\t\t\tINNER JOIN ca_sql_search_word_index AS swi ON sw.word_id = swi.word_id \n\t\t\t\t\t\t\t\t\t" . (sizeof($va_temp_tables) ? " INNER JOIN " . $va_temp_tables[sizeof($va_temp_tables) - 1] . " AS tt ON swi.index_id = tt.row_id" : "") . "\n\t\t\t\t\t\t\t\t\tWHERE \n\t\t\t\t\t\t\t\t\t\tsw.word = ? AND swi.table_num = ? {$vs_fld_limit_sql}\n \t\t\t\t\t\t\t\t\t\t" . ($this->getOption('omitPrivateIndexing') ? " AND swi.access = 0" : '') . "\n\t\t\t\t\t\t\t\t";
                             $qr_res = $this->opo_db->query($vs_sql, $vs_word, (int) $pn_subject_tablenum);
                             $qr_count = $this->opo_db->query("SELECT count(*) c FROM {$vs_temp_table}");
                             if (!$qr_count->nextRow() || !(int) $qr_count->get('c')) {
                                 foreach ($va_temp_tables as $vs_temp_table) {
                                     $this->_dropTempTable($vs_temp_table);
                                 }
                                 break 2;
                             }
                             $va_temp_tables[] = $vs_temp_table;
                         }
                         $vs_results_temp_table = array_pop($va_temp_tables);
                         $this->opo_db->query("UPDATE {$vs_results_temp_table} SET row_id = row_id - 1");
                         $va_direct_query_temp_tables[$vs_results_temp_table] = true;
                         $vs_direct_sql_query = "SELECT swi.row_id, ca.boost \n\t\t\t\t\t\t\t\t\t\t\t\t\tFROM {$vs_results_temp_table} ca\n\t\t\t\t\t\t\t\t\t\t\t\t\tINNER JOIN ca_sql_search_word_index AS swi ON swi.index_id = ca.row_id \n\t\t\t\t\t\t\t";
                         $pa_direct_sql_query_params = array();
                         // don't pass any params
                         foreach ($va_temp_tables as $vs_temp_table) {
                             $this->_dropTempTable($vs_temp_table);
                         }
                         break;
                     case 'Zend_Search_Lucene_Search_Query_MultiTerm':
                         $va_ft_like_term_list = array();
                         foreach ($o_lucene_query_element->getTerms() as $o_term) {
                             $va_raw_terms[] = $vs_term = (string) (method_exists($o_term, "getTerm") ? $o_term->getTerm()->text : $o_term->text);
                             if (!$vs_access_point && ($vs_field = method_exists($o_term, "getTerm") ? $o_term->getTerm()->field : $o_term->field)) {
                                 $vs_access_point = $vs_field;
                             }
                             $vs_stripped_term = preg_replace('!\\*+$!u', '', $vs_term);
                             $va_ft_like_terms[] = $vs_stripped_term . ($vb_had_wildcard ? '%' : '');
                         }
                         break;
                     default:
                         $vs_access_point = $o_lucene_query_element->getTerm()->field;
                         $vs_term = $o_lucene_query_element->getTerm()->text;
                         if ($vs_access_point && mb_strtoupper($vs_term) == _t('[BLANK]')) {
                             $vb_is_blank_search = true;
                             break;
                         }
                         $va_terms = $this->_tokenize($vs_term, true, $vn_i);
                         $vb_output_term = false;
                         foreach ($va_terms as $vs_term) {
                             if (in_array(trim(mb_strtolower($vs_term, 'UTF-8')), WLPlugSearchEngineSqlSearch::$s_stop_words)) {
                                 continue;
                             }
                             if (get_class($o_lucene_query_element) != 'Zend_Search_Lucene_Search_Query_MultiTerm') {
                                 $vs_stripped_term = preg_replace('!\\*+$!u', '', $vs_term);
                                 // do stemming
                                 if ($this->opb_do_stemming) {
                                     $vs_to_stem = preg_replace('!\\*$!u', '', $vs_term);
                                     if (!preg_match('!y$!u', $vs_to_stem) && !preg_match('![0-9]+!', $vs_to_stem)) {
                                         // don't stem things ending in 'y' as that can cause problems (eg "Bowery" becomes "Boweri")
                                         if (!($vs_stem = trim($this->opo_stemmer->stem($vs_to_stem)))) {
                                             $vs_stem = (string) $vs_term;
                                         }
                                         $va_ft_stem_terms[] = "'" . $this->opo_db->escape($vs_stem) . "'";
                                     } else {
                                         $va_ft_terms[] = '"' . $this->opo_db->escape($vs_term) . '"';
                                     }
                                 } else {
                                     $va_ft_terms[] = '"' . $this->opo_db->escape($vs_term) . '"';
                                 }
                                 $vb_output_term = true;
                             }
                         }
                         if ($vb_output_term) {
                             $va_raw_terms[] = $vs_term;
                         } else {
                             $vn_i--;
                         }
                         break;
                 }
                 $vs_fld_num = $vs_table_num = $t_table = null;
                 $vb_ft_bit_optimization = false;
                 if ($vs_access_point) {
                     list($vs_table, $vs_field, $vs_sub_field) = explode('.', $vs_access_point);
                     if (in_array($vs_table, array('created', 'modified'))) {
                         $o_tep = new TimeExpressionParser();
                         $vs_date = join(' ', $va_raw_terms);
                         if (!$o_tep->parse($vs_date)) {
                             break;
                         }
                         $va_range = $o_tep->getUnixTimestamps();
                         $vn_user_id = null;
                         if ($vs_field = trim($vs_field)) {
                             if (!is_int($vs_field)) {
                                 $t_user = new ca_users();
                                 if ($t_user->load(array("user_name" => $vs_field))) {
                                     $vn_user_id = (int) $t_user->getPrimaryKey();
                                 }
                             } else {
                                 $vn_user_id = (int) $vs_field;
                             }
                         }
                         $vs_user_sql = $vn_user_id ? " AND (ccl.user_id = " . (int) $vn_user_id . ")" : "";
                         switch ($vs_table) {
                             case 'created':
                                 $vs_direct_sql_query = "\n\t\t\t\t\t\t\t\t\t\t\tSELECT ccl.logged_row_id, 1\n\t\t\t\t\t\t\t\t\t\t\tFROM ca_change_log ccl\n\t\t\t\t\t\t\t\t\t\t\tWHERE\n\t\t\t\t\t\t\t\t\t\t\t\t(ccl.log_datetime BETWEEN " . (int) $va_range['start'] . " AND " . (int) $va_range['end'] . ")\n\t\t\t\t\t\t\t\t\t\t\t\tAND\n\t\t\t\t\t\t\t\t\t\t\t\t(ccl.logged_table_num = ?)\n\t\t\t\t\t\t\t\t\t\t\t\tAND\n\t\t\t\t\t\t\t\t\t\t\t\t(ccl.changetype = 'I')\n\t\t\t\t\t\t\t\t\t\t\t\t{$vs_user_sql}\n\t\t\t\t\t\t\t\t\t\t";
                                 break;
                             case 'modified':
                                 $vs_direct_sql_query = "\n\t\t\t\t\t\t\t\t\t\t\tSELECT ccl.logged_row_id, 1\n\t\t\t\t\t\t\t\t\t\t\tFROM ca_change_log ccl\n\t\t\t\t\t\t\t\t\t\t\tWHERE\n\t\t\t\t\t\t\t\t\t\t\t\t(ccl.log_datetime BETWEEN " . (int) $va_range['start'] . " AND " . (int) $va_range['end'] . ")\n\t\t\t\t\t\t\t\t\t\t\t\tAND\n\t\t\t\t\t\t\t\t\t\t\t\t(ccl.logged_table_num = ?)\n\t\t\t\t\t\t\t\t\t\t\t\tAND\n\t\t\t\t\t\t\t\t\t\t\t\t(ccl.changetype = 'U')\n\t\t\t\t\t\t\t\t\t\t\t\t{$vs_user_sql}\n\t\t\t\t\t\t\t\t\t\tUNION\n\t\t\t\t\t\t\t\t\t\t\tSELECT ccls.subject_row_id, 1\n\t\t\t\t\t\t\t\t\t\t\tFROM ca_change_log ccl\n\t\t\t\t\t\t\t\t\t\t\tINNER JOIN ca_change_log_subjects AS ccls ON ccls.log_id = ccl.log_id\n\t\t\t\t\t\t\t\t\t\t\tWHERE\n\t\t\t\t\t\t\t\t\t\t\t\t(ccl.log_datetime BETWEEN " . (int) $va_range['start'] . " AND " . (int) $va_range['end'] . ")\n\t\t\t\t\t\t\t\t\t\t\t\tAND\n\t\t\t\t\t\t\t\t\t\t\t\t(ccls.subject_table_num = {$pn_subject_tablenum})\n\t\t\t\t\t\t\t\t\t\t\t\t{$vs_user_sql}\n\t\t\t\t\t\t\t\t\t\t";
                                 break;
                         }
                     } else {
                         if ($vs_table && $vs_field) {
                             $t_table = $this->opo_datamodel->getInstanceByTableName($vs_table, true);
                             if ($t_table) {
                                 $vs_table_num = $t_table->tableNum();
                                 if (is_numeric($vs_field)) {
                                     $vs_fld_num = 'I' . $vs_field;
                                     $vn_fld_num = (int) $vs_field;
                                 } else {
                                     $vn_fld_num = $this->getFieldNum($vs_table, $vs_field);
                                     $vs_fld_num = 'I' . $vn_fld_num;
                                     if (!strlen($vn_fld_num)) {
                                         $t_element = new ca_metadata_elements();
                                         if ($t_element->load(array('element_code' => $vs_sub_field ? $vs_sub_field : $vs_field))) {
                                             $vn_fld_num = $t_element->getPrimaryKey();
                                             $vs_fld_num = 'A' . $vn_fld_num;
                                             if (!$vb_is_blank_search) {
                                                 //
                                                 // For certain types of attributes we can directly query the
                                                 // attributes in the database rather than using the full text index
                                                 // This allows us to do "intelligent" querying... for example on date ranges
                                                 // parsed from natural language input and for length dimensions using unit conversion
                                                 //
                                                 switch ($t_element->get('datatype')) {
                                                     case 2:
                                                         // dates
                                                         $vb_all_numbers = true;
                                                         foreach ($va_raw_terms as $vs_term) {
                                                             if (!is_numeric($vs_term)) {
                                                                 $vb_all_numbers = false;
                                                                 break;
                                                             }
                                                         }
                                                         $vs_raw_term = join(' ', $va_raw_terms);
                                                         $vb_exact = $vs_raw_term[0] == "#" ? true : false;
                                                         // dates prepended by "#" are considered "exact" or "contained - the matched dates must be wholly contained by the search term
                                                         if ($vb_exact) {
                                                             $vs_raw_term = substr($vs_raw_term, 1);
                                                             if ($this->opo_tep->parse($vs_raw_term)) {
                                                                 $va_dates = $this->opo_tep->getHistoricTimestamps();
                                                                 $vs_direct_sql_query = "\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSELECT ca.row_id, 1\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tFROM ca_attribute_values cav\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tINNER JOIN ca_attributes AS ca ON ca.attribute_id = cav.attribute_id\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t^JOIN\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tWHERE\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t(cav.element_id = {$vn_fld_num}) AND (ca.table_num = ?)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tAND\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t(\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t(cav.value_decimal1 BETWEEN " . floatval($va_dates['start']) . " AND " . floatval($va_dates['end']) . ")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tAND\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t(cav.value_decimal2 BETWEEN " . floatval($va_dates['start']) . " AND " . floatval($va_dates['end']) . ")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t";
                                                             }
                                                         } else {
                                                             if ($this->opo_tep->parse($vs_raw_term)) {
                                                                 $va_dates = $this->opo_tep->getHistoricTimestamps();
                                                                 $vs_direct_sql_query = "\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSELECT ca.row_id, 1\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tFROM ca_attribute_values cav\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tINNER JOIN ca_attributes AS ca ON ca.attribute_id = cav.attribute_id\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t^JOIN\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tWHERE\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t(cav.element_id = {$vn_fld_num}) AND (ca.table_num = ?)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tAND\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t(\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t(cav.value_decimal1 BETWEEN " . floatval($va_dates['start']) . " AND " . floatval($va_dates['end']) . ")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tOR\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t(cav.value_decimal2 BETWEEN " . floatval($va_dates['start']) . " AND " . floatval($va_dates['end']) . ")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tOR\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t(cav.value_decimal1 <= " . floatval($va_dates['start']) . " AND cav.value_decimal2 >= " . floatval($va_dates['end']) . ")\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t";
                                                             }
                                                         }
                                                         break;
                                                     case 4:
                                                         // geocode
                                                         $t_geocode = new GeocodeAttributeValue();
                                                         // If it looks like a lat/long pair that has been tokenized by Lucene
                                                         // into oblivion rehydrate it here.
                                                         if ($va_coords = caParseGISSearch(join(' ', $va_raw_terms))) {
                                                             $vs_direct_sql_query = "\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSELECT ca.row_id, 1\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tFROM ca_attribute_values cav\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tINNER JOIN ca_attributes AS ca ON ca.attribute_id = cav.attribute_id\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t^JOIN\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tWHERE\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t(cav.element_id = {$vn_fld_num}) AND (ca.table_num = ?)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tAND\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t(cav.value_decimal1 BETWEEN {$va_coords['min_latitude']} AND {$va_coords['max_latitude']})\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tAND\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t(cav.value_decimal2 BETWEEN {$va_coords['min_longitude']} AND {$va_coords['max_longitude']})\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t";
                                                         }
                                                         break;
                                                     case 6:
                                                         // currency
                                                         $t_cur = new CurrencyAttributeValue();
                                                         $va_parsed_value = $t_cur->parseValue(join(' ', $va_raw_terms), $t_element->getFieldValuesArray());
                                                         $vn_amount = $va_parsed_value['value_decimal1'];
                                                         $vs_currency = preg_replace('![^A-Z0-9]+!', '', $va_parsed_value['value_longtext1']);
                                                         $vs_direct_sql_query = "\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSELECT ca.row_id, 1\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tFROM ca_attribute_values cav\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tINNER JOIN ca_attributes AS ca ON ca.attribute_id = cav.attribute_id\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t^JOIN\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tWHERE\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t(cav.element_id = {$vn_fld_num}) AND (ca.table_num = ?)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tAND\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t(cav.value_decimal1 = " . floatval($vn_amount) . ")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tAND\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t(cav.value_longtext1 = '" . $this->opo_db->escape($vs_currency) . "')\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t";
                                                         break;
                                                     case 8:
                                                         // length
                                                         $t_len = new LengthAttributeValue();
                                                         $va_parsed_value = $t_len->parseValue(array_shift($va_raw_terms), $t_element->getFieldValuesArray());
                                                         $vn_len = $va_parsed_value['value_decimal1'];
                                                         // this is always in meters so we can compare this value to the one in the database
                                                         $vs_direct_sql_query = "\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSELECT ca.row_id, 1\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tFROM ca_attribute_values cav\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tINNER JOIN ca_attributes AS ca ON ca.attribute_id = cav.attribute_id\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t^JOIN\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tWHERE\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t(cav.element_id = {$vn_fld_num}) AND (ca.table_num = ?)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tAND\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t(cav.value_decimal1 = " . floatval($vn_len) . ")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t";
                                                         break;
                                                     case 9:
                                                         // weight
                                                         $t_weight = new WeightAttributeValue();
                                                         $va_parsed_value = $t_weight->parseValue(array_shift($va_raw_terms), $t_element->getFieldValuesArray());
                                                         $vn_weight = $va_parsed_value['value_decimal1'];
                                                         // this is always in kilograms so we can compare this value to the one in the database
                                                         $vs_direct_sql_query = "\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSELECT ca.row_id, 1\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tFROM ca_attribute_values cav\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tINNER JOIN ca_attributes AS ca ON ca.attribute_id = cav.attribute_id\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t^JOIN\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tWHERE\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t(cav.element_id = {$vn_fld_num}) AND (ca.table_num = ?)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tAND\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t(cav.value_decimal1 = " . floatval($vn_weight) . ")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t";
                                                         break;
                                                     case 10:
                                                         // timecode
                                                         $t_timecode = new TimecodeAttributeValue();
                                                         $va_parsed_value = $t_timecode->parseValue(join(' ', $va_raw_terms), $t_element->getFieldValuesArray());
                                                         $vn_timecode = $va_parsed_value['value_decimal1'];
                                                         $vs_direct_sql_query = "\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSELECT ca.row_id, 1\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tFROM ca_attribute_values cav\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tINNER JOIN ca_attributes AS ca ON ca.attribute_id = cav.attribute_id\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t^JOIN\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tWHERE\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t(cav.element_id = {$vn_fld_num}) AND (ca.table_num = ?)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tAND\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t(cav.value_decimal1 = " . floatval($vn_timecode) . ")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t";
                                                         break;
                                                     case 11:
                                                         // integer
                                                         $vs_direct_sql_query = "\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSELECT ca.row_id, 1\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tFROM ca_attribute_values cav\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tINNER JOIN ca_attributes AS ca ON ca.attribute_id = cav.attribute_id\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t^JOIN\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tWHERE\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t(cav.element_id = {$vn_fld_num}) AND (ca.table_num = ?)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tAND\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t(cav.value_integer1 = " . intval(array_shift($va_raw_terms)) . ")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t";
                                                         break;
                                                     case 12:
                                                         // decimal
                                                         $vs_direct_sql_query = "\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tSELECT ca.row_id, 1\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tFROM ca_attribute_values cav\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tINNER JOIN ca_attributes AS ca ON ca.attribute_id = cav.attribute_id\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t^JOIN\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tWHERE\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t(cav.element_id = {$vn_fld_num}) AND (ca.table_num = ?)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tAND\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t(cav.value_decimal1 = " . floatval(array_shift($va_raw_terms)) . ")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t";
                                                         break;
                                                 }
                                             }
                                         } else {
                                             // neither table fields nor elements, i.e. 'virtual' fields like _count should
                                             $vn_fld_num = false;
                                             $vs_fld_num = $vs_field;
                                         }
                                     }
                                 }
                                 if ($t_table->getFieldInfo($t_table->fieldName($vn_fld_num), 'FIELD_TYPE') == FT_BIT) {
                                     $vb_ft_bit_optimization = true;
                                 }
                             }
                         }
                     }
                 }
                 //
                 // If we're querying on the fulltext index then we need to construct
                 // the query here... if we already have a direct SQL query to run then we can skip this
                 //
                 if ($vb_is_blank_search) {
                     $va_sql_where[] = "((swi.field_table_num = " . intval($vs_table_num) . ") AND (swi.field_num = '{$vs_fld_num}') AND (swi.word_id = 0))";
                     if (!sizeof($va_sql_where)) {
                         continue;
                     }
                     $vs_sql_where = join(' OR ', $va_sql_where);
                 } elseif (!$vs_direct_sql_query) {
                     $va_sql_where = array();
                     if (sizeof($va_ft_terms)) {
                         if ($t_table && strlen($vs_fld_num) > 1) {
                             $va_sql_where[] = "((swi.field_table_num = " . intval($vs_table_num) . ") AND (swi.field_num = '{$vs_fld_num}') AND (sw.word IN (" . join(',', $va_ft_terms) . ")))";
                         } else {
                             if (sizeof($va_ft_terms) == 1) {
                                 $va_sql_where[] = "(sw.word = " . $va_ft_terms[0] . ")";
                             } else {
                                 $va_sql_where[] = "(sw.word IN (" . join(',', $va_ft_terms) . "))";
                             }
                         }
                     }
                     if (sizeof($va_ft_like_terms)) {
                         $va_tmp = array();
                         foreach ($va_ft_like_terms as $vs_term) {
                             if ($vb_ft_bit_optimization) {
                                 $va_tmp[] = '(sw.word = \' ' . $this->opo_db->escape(trim($vs_term)) . ' \')';
                             } else {
                                 $va_tmp[] = '(sw.word LIKE \'' . $this->opo_db->escape(trim($vs_term)) . '%\')';
                             }
                         }
                         if ($t_table && strlen($vs_fld_num) > 1) {
                             $va_sql_where[] = "((swi.field_table_num = " . intval($vs_table_num) . ") AND (swi.field_num = '{$vs_fld_num}') AND (" . join(' AND ', $va_tmp) . "))";
                         } else {
                             $va_sql_where[] = "(" . join(' AND ', $va_tmp) . ")";
                         }
                     }
                     if (sizeof($va_ft_stem_terms)) {
                         if ($t_table && strlen($vs_fld_num) > 1) {
                             $va_sql_where[] = "((swi.field_table_num = " . intval($vs_table_num) . ") AND (swi.field_num = '{$vs_fld_num}') AND (sw.stem IN (" . join(',', $va_ft_stem_terms) . ")))";
                         } else {
                             $va_sql_where[] = "(sw.stem IN (" . join(',', $va_ft_stem_terms) . "))";
                         }
                     }
                     if (!sizeof($va_sql_where)) {
                         continue;
                     }
                     $vs_sql_where = join(' OR ', $va_sql_where);
                 } else {
                     $va_ft_terms = $va_ft_like_terms = $va_ft_like_terms = array();
                 }
                 //print "OP=$vs_op<br>";
                 if ($vn_i == 0) {
                     if ($vs_direct_sql_query) {
                         $vs_direct_sql_query = str_replace('^JOIN', "", $vs_direct_sql_query);
                     }
                     $vs_sql = $vs_direct_sql_query ? "INSERT IGNORE INTO {$ps_dest_table} {$vs_direct_sql_query}" : "\n\t\t\t\t\t\t\tINSERT IGNORE INTO {$ps_dest_table}\n\t\t\t\t\t\t\tSELECT swi.row_id, SUM(swi.boost)\n\t\t\t\t\t\t\tFROM ca_sql_search_word_index swi\n\t\t\t\t\t\t\t" . (!$vb_is_blank_search ? "INNER JOIN ca_sql_search_words AS sw ON sw.word_id = swi.word_id" : '') . "\n\t\t\t\t\t\t\tWHERE\n\t\t\t\t\t\t\t\t{$vs_sql_where}\n\t\t\t\t\t\t\t\tAND\n\t\t\t\t\t\t\t\tswi.table_num = ?\n\t\t\t\t\t\t\t\t" . ($this->getOption('omitPrivateIndexing') ? " AND swi.access = 0" : '') . "\n\t\t\t\t\t\t\tGROUP BY swi.row_id \n\t\t\t\t\t\t";
                     if (($vn_num_terms = sizeof($va_ft_terms) + sizeof($va_ft_like_terms) + sizeof($va_ft_stem_terms)) > 1 && !$vs_direct_sql_query) {
                         $vs_sql .= " HAVING count(distinct sw.word_id) = {$vn_num_terms}";
                     }
                     if ($this->debug) {
                         print 'FIRST: ' . $vs_sql . " [{$pn_subject_tablenum}]<hr>\n";
                     }
                     //print $vs_sql;
                     $qr_res = $this->opo_db->query($vs_sql, is_array($pa_direct_sql_query_params) ? $pa_direct_sql_query_params : array((int) $pn_subject_tablenum));
                 } else {
                     switch ($vs_op) {
                         case 'AND':
                             if ($vs_direct_sql_query) {
                                 $vs_direct_sql_query = str_replace('^JOIN', "INNER JOIN {$ps_dest_table} AS ftmp1 ON ftmp1.row_id = ca.row_id", $vs_direct_sql_query);
                             }
                             $this->_createTempTable($ps_dest_table . '_acc');
                             $vs_sql = $vs_direct_sql_query ? "INSERT IGNORE INTO {$ps_dest_table}_acc {$vs_direct_sql_query}" : "\n\t\t\t\t\t\t\t\t\tINSERT IGNORE INTO {$ps_dest_table}_acc\n\t\t\t\t\t\t\t\t\tSELECT swi.row_id, SUM(swi.boost)\n\t\t\t\t\t\t\t\t\tFROM ca_sql_search_word_index swi\n\t\t\t\t\t\t\t\t\tINNER JOIN ca_sql_search_words AS sw ON sw.word_id = swi.word_id\n\t\t\t\t\t\t\t\t\tINNER JOIN {$ps_dest_table} AS ftmp1 ON ftmp1.row_id = swi.row_id\n\t\t\t\t\t\t\t\t\tWHERE\n\t\t\t\t\t\t\t\t\t\t{$vs_sql_where}\n\t\t\t\t\t\t\t\t\t\tAND\n\t\t\t\t\t\t\t\t\t\tswi.table_num = ?\n\t\t\t\t\t\t\t\t\t\t" . ($this->getOption('omitPrivateIndexing') ? " AND swi.access = 0" : '') . "\n\t\t\t\t\t\t\t\t\tGROUP BY\n\t\t\t\t\t\t\t\t\t\tswi.row_id\n\t\t\t\t\t\t\t\t";
                             if (($vn_num_terms = sizeof($va_ft_terms) + sizeof($va_ft_like_terms) + sizeof($va_ft_stem_terms)) > 1) {
                                 $vs_sql .= " HAVING count(distinct sw.word_id) = {$vn_num_terms}";
                             }
                             if ($this->debug) {
                                 print 'AND:' . $vs_sql . "<hr>\n";
                             }
                             $qr_res = $this->opo_db->query($vs_sql, is_array($pa_direct_sql_query_params) ? $pa_direct_sql_query_params : array((int) $pn_subject_tablenum));
                             $qr_res = $this->opo_db->query("TRUNCATE TABLE {$ps_dest_table}");
                             $qr_res = $this->opo_db->query("INSERT INTO {$ps_dest_table} SELECT row_id, boost FROM {$ps_dest_table}_acc");
                             //$qr_res = $this->opo_db->query("TRUNCATE TABLE ca_sql_search_temp_2");
                             $this->_dropTempTable($ps_dest_table . '_acc');
                             break;
                         case 'NOT':
                             if ($vs_direct_sql_query) {
                                 $vs_direct_sql_query = str_replace('^JOIN', "", $vs_direct_sql_query);
                             }
                             $vs_sql = "\n\t\t\t\t\t\t\t\t\tSELECT row_id\n\t\t\t\t\t\t\t\t\tFROM ca_sql_search_words sw\n\t\t\t\t\t\t\t\t\tINNER JOIN ca_sql_search_word_index AS swi ON sw.word_id = swi.word_id\n\t\t\t\t\t\t\t\t\tWHERE \n\t\t\t\t\t\t\t\t\t\t" . ($vs_sql_where ? "{$vs_sql_where} AND " : "") . " swi.table_num = ? \n\t\t\t\t\t\t\t\t\t\t" . ($this->getOption('omitPrivateIndexing') ? " AND swi.access = 0" : '');
                             //print "$vs_sql<hr>";
                             $qr_res = $this->opo_db->query($vs_sql, is_array($pa_direct_sql_query_params) ? $pa_direct_sql_query_params : array((int) $pn_subject_tablenum));
                             $va_ids = $qr_res->getAllFieldValues("row_id");
                             $vs_sql = "\n\t\t\t\t\t\t\t\t\tDELETE FROM {$ps_dest_table} \n\t\t\t\t\t\t\t\t\tWHERE \n\t\t\t\t\t\t\t\t\t\trow_id IN (?)\n\t\t\t\t\t\t\t\t";
                             $qr_res = $this->opo_db->query($vs_sql, array($va_ids));
                             //print "$vs_sql<hr>";
                             break;
                         default:
                         case 'OR':
                             if ($vs_direct_sql_query) {
                                 $vs_direct_sql_query = str_replace('^JOIN', "", $vs_direct_sql_query);
                             }
                             $vs_sql = $vs_direct_sql_query ? "INSERT IGNORE INTO {$ps_dest_table} {$vs_direct_sql_query}" : "\n\t\t\t\t\t\t\t\t\tINSERT IGNORE INTO {$ps_dest_table}\n\t\t\t\t\t\t\t\t\tSELECT swi.row_id, SUM(swi.boost)\n\t\t\t\t\t\t\t\t\tFROM ca_sql_search_word_index swi\n\t\t\t\t\t\t\t\t\tINNER JOIN ca_sql_search_words AS sw ON sw.word_id = swi.word_id\n\t\t\t\t\t\t\t\t\tWHERE\n\t\t\t\t\t\t\t\t\t\t{$vs_sql_where}\n\t\t\t\t\t\t\t\t\t\tAND\n\t\t\t\t\t\t\t\t\t\tswi.table_num = ?\n\t\t\t\t\t\t\t\t\t\t" . ($this->getOption('omitPrivateIndexing') ? " AND swi.access = 0" : '') . "\n\t\t\t\t\t\t\t\t\tGROUP BY\n\t\t\t\t\t\t\t\t\t\tswi.row_id\n\t\t\t\t\t\t\t\t";
                             if ($this->debug) {
                                 print 'OR' . $vs_sql . "<hr>\n";
                             }
                             $qr_res = $this->opo_db->query($vs_sql, is_array($pa_direct_sql_query_params) ? $pa_direct_sql_query_params : array((int) $pn_subject_tablenum));
                             break;
                     }
                 }
                 // Drop any temporary tables created by direct search queries
                 foreach (array_keys($va_direct_query_temp_tables) as $vs_temp_table_to_drop) {
                     $this->_dropTempTable($vs_temp_table_to_drop);
                 }
                 break;
             default:
                 //print get_class($o_lucene_query_element);
                 break;
         }
         $vn_i++;
     }
 }
 /**
  * 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 getFacetHierarchyLevel()
 {
     $va_access_values = caGetUserAccessValues($this->request);
     $ps_facet_name = $this->request->getParameter('facet', pString);
     $this->opo_browse->setTypeRestrictions(array($this->opn_type_restriction_id));
     if (!is_array($va_facet_info = $this->opo_browse->getInfoForFacet($ps_facet_name))) {
         return null;
     }
     $va_facet = $this->opo_browse->getFacet($ps_facet_name, array('sort' => 'name', 'checkAccess' => $va_access_values));
     $pa_ids = explode(";", $ps_ids = $this->request->getParameter('id', pString));
     if (!sizeof($pa_ids)) {
         $pa_ids = array(null);
     }
     $va_level_data = 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;
     }
     $t_model = $this->opo_datamodel->getInstanceByTableName($this->ops_tablename, true);
     $o_config = Configuration::load();
     if (!is_array($va_sorts = $o_config->getList($this->ops_tablename . '_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_tablename . '_hierarchy_browser_sort_direction')), array('asc', 'desc'))) {
         $vs_sort_dir = 'asc';
     }
     $va_expanded_facet = array();
     $t_item = new ca_list_items();
     foreach ($va_facet as $vn_id => $va_facet_item) {
         $va_expanded_facet[$vn_id] = true;
         $va_ancestors = $t_item->getHierarchyAncestors($vn_id, array('idsOnly' => true));
         if (is_array($va_ancestors)) {
             foreach ($va_ancestors as $vn_ancestor_id) {
                 $va_expanded_facet[$vn_ancestor_id] = true;
             }
         }
     }
     foreach ($pa_ids as $pn_id) {
         $va_json_data = array('_primaryKey' => 'item_id');
         $va_tmp = explode(":", $pn_id);
         $vn_id = $va_tmp[0];
         $vn_start = (int) $va_tmp[1];
         if ($vn_start < 0) {
             $vn_start = 0;
         }
         switch ($va_facet_info['type']) {
             case 'attribute':
                 // is it a list attribute?
                 $t_element = new ca_metadata_elements();
                 if ($t_element->load(array('element_code' => $va_facet_info['element_code']))) {
                     if ($t_element->get('datatype') == 3) {
                         // 3=list
                         $t_list = new ca_lists();
                         if (!$vn_id) {
                             $vn_id = $t_list->getRootListItemID($t_element->get('list_id'));
                         }
                         $t_item = new ca_list_items($vn_id);
                         $va_children = $t_item->getHierarchyChildren(null, array('idsOnly' => true));
                         $va_child_counts = $t_item->getHierarchyChildCountsForIDs($va_children);
                         $qr_res = caMakeSearchResult('ca_list_items', $va_children);
                         $vs_pk = $t_model->primaryKey();
                         if ($qr_res) {
                             while ($qr_res->nextHit()) {
                                 $vn_parent_id = $qr_res->get('ca_list_items.parent_id');
                                 $vn_item_id = $qr_res->get('ca_list_items.item_id');
                                 if (!isset($va_expanded_facet[$vn_item_id])) {
                                     continue;
                                 }
                                 $va_item = array();
                                 $va_item['item_id'] = $vn_item_id;
                                 $va_item['name'] = $qr_res->get('ca_list_items.preferred_labels');
                                 $va_item['children'] = isset($va_child_counts[$vn_item_id]) && $va_child_counts[$vn_item_id] ? $va_child_counts[$vn_item_id] : 0;
                                 $va_json_data[$vn_item_id] = $va_item;
                             }
                         }
                     }
                 }
                 break;
             case 'label':
                 // label facet
                 $va_facet_info['table'] = $this->ops_tablename;
                 // fall through to default case
             // fall through to default case
             default:
                 if (!$vn_id) {
                     $va_hier_ids = $this->opo_browse->getHierarchyIDsForFacet($ps_facet_name, array('checkAccess' => $va_access_values));
                     $t_item = $this->opo_datamodel->getInstanceByTableName($va_facet_info['table']);
                     $t_item->load($vn_id);
                     $vn_id = $vn_root = $t_item->getHierarchyRootID();
                     $va_hierarchy_list = $t_item->getHierarchyList(true);
                     $vn_last_id = null;
                     $vn_c = 0;
                     foreach ($va_hierarchy_list as $vn_i => $va_item) {
                         if (!in_array($vn_i, $va_hier_ids)) {
                             continue;
                         }
                         // only show hierarchies that have items in browse result
                         if ($vn_start <= $vn_c) {
                             $va_item['item_id'] = $va_item[$t_item->primaryKey()];
                             if (!isset($va_facet[$va_item['item_id']]) && $vn_root == $va_item['item_id']) {
                                 continue;
                             }
                             unset($va_item['parent_id']);
                             unset($va_item['label']);
                             $va_json_data[$va_item['item_id']] = $va_item;
                             $vn_last_id = $va_item['item_id'];
                         }
                         $vn_c++;
                         if (!is_null($vn_max_items_per_page) && $vn_c >= $vn_max_items_per_page + $vn_start) {
                             break;
                         }
                     }
                     if (sizeof($va_json_data) == 2) {
                         // if only one hierarchy root (root +  _primaryKey in array) then don't bother showing it
                         $vn_id = $vn_last_id;
                         unset($va_json_data[$vn_last_id]);
                     }
                 }
                 if ($vn_id) {
                     $vn_c = 0;
                     foreach ($va_facet as $vn_i => $va_item) {
                         if ($va_item['parent_id'] == $vn_id) {
                             if ($vn_start <= $vn_c) {
                                 $va_item['item_id'] = $va_item['id'];
                                 $va_item['name'] = $va_item['label'];
                                 $va_item['children'] = $va_item['child_count'];
                                 unset($va_item['label']);
                                 unset($va_item['child_count']);
                                 unset($va_item['id']);
                                 $va_json_data[$va_item['item_id']] = $va_item;
                             }
                             $vn_c++;
                             if (!is_null($vn_max_items_per_page) && $vn_c >= $vn_max_items_per_page + $vn_start) {
                                 break;
                             }
                         }
                     }
                 }
                 break;
         }
         $vs_rank_fld = $t_item->getProperty('RANK');
         $va_sorted_items = array();
         foreach ($va_json_data as $vn_id => $va_node) {
             if (!is_array($va_node)) {
                 continue;
             }
             $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_json_data = 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_json_data = array_merge($va_json_data, $va_v);
         }
         $va_json_data['_itemCount'] = sizeof($va_json_data);
         $va_json_data['_sortOrder'] = array_keys($va_json_data);
         $va_json_data['_primaryKey'] = $t_model->primaryKey();
         // pass the name of the primary key so the hierbrowser knows where to look for item_id's
         $va_level_data[$pn_id] = $va_json_data;
     }
     if (!trim($this->request->getParameter('init', pString))) {
         $this->opo_result_context->setParameter($ps_facet_name . '_browse_last_id', $pn_id);
         $this->opo_result_context->saveContext();
     }
     $this->view->setVar('facet_list', $va_level_data);
     return $this->render('Browse/facet_hierarchy_level_json.php');
 }
 /**
  * Options:
  *		appendToSearch = optional text to be AND'ed wuth current search expression
  *		output_format = determines format out search result output. "PDF" and "HTML" are currently supported; "HTML" is the default
  *		view = view with path relative to controller to use overriding default ("search/<table_name>_search_basic_html.php")
  *		vars = associative array with key value pairs to assign to the view
  *
  * Callbacks:
  * 		hookBeforeNewSearch() is called just before executing a new search. The first parameter is the BrowseEngine object containing the search.
  */
 public function Index($pa_options = null)
 {
     $po_search = isset($pa_options['search']) ? $pa_options['search'] : null;
     if (isset($pa_options['saved_search']) && $pa_options['saved_search']) {
         $this->opo_result_context->setSearchExpression($pa_options['saved_search']['search']);
         $this->opo_result_context->isNewSearch(true);
     }
     parent::Index($pa_options);
     AssetLoadManager::register('hierBrowser');
     AssetLoadManager::register('browsable');
     // need this to support browse panel when filtering/refining search results
     $t_model = $this->opo_datamodel->getInstanceByTableName($this->ops_tablename, true);
     $va_access_values = caGetUserAccessValues($this->request);
     // Get elements of result context
     $vn_page_num = $this->opo_result_context->getCurrentResultsPageNumber();
     $vs_search = $this->opo_result_context->getSearchExpression();
     $vb_is_new_search = $this->opo_result_context->isNewSearch();
     if ((bool) $this->request->getParameter('reset', pString) && $this->request->getParameter('reset', pString) != 'save') {
         $vs_search = '';
         $vb_is_new_search = true;
     }
     if (!($vn_items_per_page = $this->opo_result_context->getItemsPerPage())) {
         $vn_items_per_page = $this->opn_items_per_page_default;
         $this->opo_result_context->setItemsPerPage($vn_items_per_page);
     }
     if (!($vs_view = $this->opo_result_context->getCurrentView())) {
         $va_tmp = array_keys($this->opa_views);
         $vs_view = $this->ops_view_default ? $this->ops_view_default : array_shift($va_tmp);
         $this->opo_result_context->setCurrentView($vs_view);
     }
     if (!isset($this->opa_views[$vs_view])) {
         $va_tmp = array_keys($this->opa_views);
         $vs_view = array_shift($va_tmp);
     }
     if (!($vs_sort = $this->opo_result_context->getCurrentSort())) {
         $va_tmp = array_keys($this->opa_sorts);
         $vs_sort = array_shift($va_tmp);
     }
     $vs_sort_direction = $this->opo_result_context->getCurrentSortDirection();
     $vb_sort_has_changed = $this->opo_result_context->sortHasChanged();
     if (!$this->opn_type_restriction_id) {
         $this->opn_type_restriction_id = '';
     }
     $this->view->setVar('type_id', $this->opn_type_restriction_id);
     MetaTagManager::setWindowTitle(_t('%1 search', $this->searchName('plural')));
     // Get attribute sorts
     $va_sortable_elements = ca_metadata_elements::getSortableElements($this->ops_tablename, $this->opn_type_restriction_id);
     if (!is_array($this->opa_sorts)) {
         $this->opa_sorts = array();
     }
     foreach ($va_sortable_elements as $va_sortable_element) {
         $this->opa_sorts[$this->ops_tablename . '.' . $va_sortable_element['element_code']] = $va_sortable_element['display_label'];
     }
     if ($pa_options['appendToSearch']) {
         $vs_append_to_search .= " AND (" . $pa_options['appendToSearch'] . ")";
     }
     //
     // Execute the search
     //
     if ($vs_search && $vs_search != "") {
         /* any request? */
         $va_search_opts = array('sort' => $vs_sort, 'sort_direction' => $vs_sort_direction, 'appendToSearch' => $vs_append_to_search, 'checkAccess' => $va_access_values, 'no_cache' => $vb_is_new_search, 'dontCheckFacetAvailability' => true, 'filterNonPrimaryRepresentations' => true);
         if ($vb_is_new_search || isset($pa_options['saved_search']) || is_subclass_of($po_search, "BrowseEngine") && !$po_search->numCriteria()) {
             $vs_browse_classname = get_class($po_search);
             $po_search = new $vs_browse_classname();
             if (is_subclass_of($po_search, "BrowseEngine")) {
                 $po_search->addCriteria('_search', $vs_search);
                 if (method_exists($this, "hookBeforeNewSearch")) {
                     $this->hookBeforeNewSearch($po_search);
                 }
             }
             $this->opo_result_context->setParameter('show_type_id', null);
         }
         if ($this->opn_type_restriction_id) {
             $po_search->setTypeRestrictions(array($this->opn_type_restriction_id), array('includeSubtypes' => false));
         }
         $vb_criteria_have_changed = false;
         if (is_subclass_of($po_search, "BrowseEngine")) {
             //
             // Restrict facets to specific group for main browse landing page (if set in app.conf config)
             //
             if ($vs_facet_group = $this->request->config->get($this->ops_tablename . '_search_refine_facet_group')) {
                 $po_search->setFacetGroup($vs_facet_group);
             }
             $vb_criteria_have_changed = $po_search->criteriaHaveChanged();
             $po_search->execute($va_search_opts);
             $this->opo_result_context->setParameter('browse_id', $po_search->getBrowseID());
             if ($vs_group_name = $this->request->config->get('browse_facet_group_for_' . $this->ops_tablename)) {
                 $po_search->setFacetGroup($vs_group_name);
             }
             $vo_result = $po_search->getResults($va_search_opts);
         } else {
             $vo_result = $po_search->search($vs_search, $va_search_opts);
         }
         $vo_result = isset($pa_options['result']) ? $pa_options['result'] : $vo_result;
         $this->opo_result_context->validateCache();
         // Only prefetch what we need
         $vo_result->setOption('prefetch', $vn_items_per_page);
         //
         // Handle details of partitioning search results by type, if required
         //
         if ((bool) $this->request->config->get('search_results_partition_by_type')) {
             $va_type_counts = $vo_result->getResultCountForFieldValues(array('ca_objects.type_id'));
             $va_type_counts_obj_type = $va_type_counts['ca_objects.type_id'];
             ksort($va_type_counts_obj_type);
             $this->view->setVar('counts_by_type', $va_type_counts_obj_type);
             $vn_show_type_id = $this->opo_result_context->getParameter('show_type_id');
             if (!isset($va_type_counts_obj_type[$vn_show_type_id])) {
                 $va_tmp = array_keys($va_type_counts_obj_type);
                 $vn_show_type_id = array_shift($va_tmp);
             }
             $this->view->setVar('show_type_id', $vn_show_type_id);
             $vo_result->filterResult('ca_objects.type_id', $vn_show_type_id);
         }
         if ($vb_is_new_search || $vb_criteria_have_changed || $vb_sort_has_changed) {
             $this->opo_result_context->setResultList($vo_result->getPrimaryKeyValues());
             $this->opo_result_context->setParameter('availableVisualizationChecked', 0);
             if ($this->opo_result_context->searchExpressionHasChanged()) {
                 $vn_page_num = 1;
             }
         }
         $this->view->setVar('num_hits', $vo_result->numHits());
         $this->view->setVar('num_pages', $vn_num_pages = ceil($vo_result->numHits() / $vn_items_per_page));
         if ($vn_page_num > $vn_num_pages) {
             $vn_page_num = 1;
         }
         $vo_result->seek(($vn_page_num - 1) * $vn_items_per_page);
         $this->view->setVar('page', $vn_page_num);
         $this->view->setVar('search', $vs_search);
         $this->view->setVar('result', $vo_result);
     }
     //
     // Set up view for display of results
     //
     $t_model = $this->opo_datamodel->getInstanceByTableName($this->ops_tablename, true);
     $this->view->setVar('views', $this->opa_views);
     // pass view list to view for rendering
     $this->view->setVar('current_view', $vs_view);
     $this->view->setVar('sorts', $this->opa_sorts);
     // pass sort list to view for rendering
     $this->view->setVar('current_sort', $vs_sort);
     $this->view->setVar('current_sort_direction', $vs_sort_direction);
     $this->view->setVar('current_items_per_page', $vn_items_per_page);
     $this->view->setVar('items_per_page', $this->opa_items_per_page);
     $this->view->setVar('t_subject', $t_model);
     $this->view->setVar('mode_name', _t('search'));
     $this->view->setVar('mode', 'search');
     $this->view->setVar('mode_type_singular', $this->searchName('singular'));
     $this->view->setVar('mode_type_plural', $this->searchName('plural'));
     $this->view->setVar('search_history', $this->opo_result_context->getSearchHistory());
     $this->view->setVar('result_context', $this->opo_result_context);
     $this->view->setVar('uses_hierarchy_browser', $this->usesHierarchyBrowser());
     $this->view->setVar('access_values', $va_access_values);
     $this->view->setVar('browse', $po_search);
     $t_display = $this->view->getVar('t_display');
     if (!is_array($va_display_list = $this->view->getVar('display_list'))) {
         $va_display_list = array();
     }
     if ($vs_view == 'editable') {
         $va_initial_data = array();
         $va_row_headers = array();
         $vn_item_count = 0;
         if ($vo_result) {
             $vs_pk = $vo_result->primaryKey();
             while ($vn_item_count < 100 && $vo_result->nextHit()) {
                 $va_result = array('item_id' => $vn_id = $vo_result->get($vs_pk));
                 foreach ($va_display_list as $vn_placement_id => $va_bundle_info) {
                     $va_result[str_replace(".", "-", $va_bundle_info['bundle_name'])] = $t_display->getDisplayValue($vo_result, $vn_placement_id, array('request' => $this->request));
                 }
                 $va_initial_data[] = $va_result;
                 $vn_item_count++;
                 $va_row_headers[] = $vn_item_count . " " . caEditorLink($this->request, caNavIcon($this->request, __CA_NAV_BUTTON_EDIT__), 'caResultsEditorEditLink', $this->ops_tablename, $vn_id);
             }
         }
         $this->view->setVar('initialData', $va_initial_data);
         $this->view->setVar('rowHeaders', $va_row_headers);
     }
     //
     // Bottom line
     //
     $va_bottom_line = array();
     $vb_bottom_line_is_set = false;
     foreach ($va_display_list as $vn_placement_id => $va_placement) {
         if (isset($va_placement['settings']['bottom_line']) && $va_placement['settings']['bottom_line']) {
             $va_bottom_line[$vn_placement_id] = caProcessBottomLineTemplate($this->request, $va_placement, $vo_result, array('pageStart' => ($vn_page_num - 1) * $vn_items_per_page, 'pageEnd' => ($vn_page_num - 1) * $vn_items_per_page + $vn_items_per_page));
             $vb_bottom_line_is_set = true;
         } else {
             $va_bottom_line[$vn_placement_id] = '';
         }
     }
     $this->view->setVar('bottom_line', $vb_bottom_line_is_set ? $va_bottom_line : null);
     switch ($pa_options['output_format']) {
         # ------------------------------------
         case 'LABELS':
             $this->_genLabels($vo_result, $this->request->getParameter("label_form", pString), $vs_search, $vs_search);
             break;
             # ------------------------------------
         # ------------------------------------
         case 'EXPORT':
             $this->_genExport($vo_result, $this->request->getParameter("export_format", pString), $vs_search, $vs_search);
             break;
             # ------------------------------------
         # ------------------------------------
         case 'HTML':
         default:
             // generate type menu and type value list
             if (method_exists($t_model, "getTypeList")) {
                 $this->view->setVar('type_list', $t_model->getTypeList());
             }
             if ($this->opb_uses_hierarchy_browser) {
                 AssetLoadManager::register('hierBrowser');
                 // only for interfaces that use the hierarchy browser
                 $t_list = new ca_lists();
                 if ($vs_type_list_code = $t_model->getTypeListCode()) {
                     $this->view->setVar('num_types', $t_list->numItemsInList($vs_type_list_code));
                     $this->view->setVar('type_menu', $t_list->getListAsHTMLFormElement($vs_type_list_code, 'type_id', array('id' => 'hierTypeList')));
                 }
                 // set last browse id for hierarchy browser
                 $this->view->setVar('browse_last_id', intval($this->request->session->getVar($this->ops_tablename . '_browse_last_id')));
             }
             $this->opo_result_context->setAsLastFind();
             $this->opo_result_context->saveContext();
             if (isset($pa_options['vars']) && is_array($pa_options['vars'])) {
                 foreach ($pa_options['vars'] as $vs_key => $vs_val) {
                     $this->view->setVar($vs_key, $vs_val);
                 }
             }
             if (isset($pa_options['view']) && $pa_options['view']) {
                 $this->render($pa_options['view']);
             } else {
                 $this->render('Search/' . $this->ops_tablename . '_search_basic_html.php');
             }
             break;
             # ------------------------------------
     }
 }
 /**
  * Options:
  * 		rawDate - if true, returns date as an array of start and end historic timestames
  *		sortable - if true a language-independent sortable representation is returned.
  *		getDirectDate - get underlying historic timestamp (floatval)
  */
 public function getDisplayValue($pa_options = null)
 {
     if (!is_array($pa_options)) {
         $pa_options = array();
     }
     if (isset($pa_options['rawDate']) && $pa_options['rawDate']) {
         return array(0 => $this->opn_start_date, 1 => $this->opn_end_date, 'start' => $this->opn_start_date, 'end' => $this->opn_end_date);
     }
     if (isset($pa_options['GET_DIRECT_DATE']) && $pa_options['GET_DIRECT_DATE'] || isset($pa_options['getDirectDate']) && $pa_options['getDirectDate']) {
         return $this->opn_start_date;
     }
     if (isset($pa_options['sortable']) && $pa_options['sortable']) {
         if (!$this->opn_start_date || !$this->opn_end_date) {
             return null;
         }
         return $this->opn_start_date . '/' . $this->opn_end_date;
     }
     $o_config = Configuration::load();
     $o_date_config = Configuration::load($o_config->get('datetime_config'));
     if ($o_date_config->get('dateFormat') == 'original') {
         return $this->ops_text_value;
     } else {
         $t_element = new ca_metadata_elements($this->getElementID());
         $va_settings = $this->getSettingValuesFromElementArray($t_element->getFieldValuesArray(), array('isLifespan'));
         $o_tep = new TimeExpressionParser();
         $o_tep->setHistoricTimestamps($this->opn_start_date, $this->opn_end_date);
         return $o_tep->getText(array_merge(array('isLifespan' => $va_settings['isLifespan']), $pa_options));
         //$this->ops_text_value;
     }
 }
Example #18
0
 /**
  * Reindex PDF media by content for in-PDF search
  */
 public static function reindex_pdfs($po_opts = null)
 {
     require_once __CA_LIB_DIR__ . "/core/Db.php";
     require_once __CA_MODELS_DIR__ . "/ca_object_representations.php";
     if (!caPDFMinerInstalled()) {
         CLIUtils::addError(_t("Can't reindex PDFs: PDFMiner is not installed."));
         return false;
     }
     $o_db = new Db();
     $t_rep = new ca_object_representations();
     $t_rep->setMode(ACCESS_WRITE);
     $va_versions = array("original");
     $va_kinds = ($vs_kinds = $po_opts->getOption("kinds")) ? explode(",", $vs_kinds) : array();
     if (!is_array($va_kinds) || !sizeof($va_kinds)) {
         $va_kinds = array('all');
     }
     $va_kinds = array_map('strtolower', $va_kinds);
     if (in_array('all', $va_kinds) || in_array('ca_object_representations', $va_kinds)) {
         if (!($vn_start = (int) $po_opts->getOption('start_id'))) {
             $vn_start = null;
         }
         if (!($vn_end = (int) $po_opts->getOption('end_id'))) {
             $vn_end = null;
         }
         if ($vn_id = (int) $po_opts->getOption('id')) {
             $vn_start = $vn_id;
             $vn_end = $vn_id;
         }
         $va_ids = array();
         if ($vs_ids = (string) $po_opts->getOption('ids')) {
             if (sizeof($va_tmp = explode(",", $vs_ids))) {
                 foreach ($va_tmp as $vn_id) {
                     if ((int) $vn_id > 0) {
                         $va_ids[] = (int) $vn_id;
                     }
                 }
             }
         }
         $vs_sql_where = null;
         $va_params = array();
         if (sizeof($va_ids)) {
             $vs_sql_where = "WHERE representation_id IN (?)";
             $va_params[] = $va_ids;
         } else {
             if ($vn_start > 0 && $vn_end > 0 && $vn_start <= $vn_end || $vn_start > 0 && $vn_end == null) {
                 $vs_sql_where = "WHERE representation_id >= ?";
                 $va_params[] = $vn_start;
                 if ($vn_end) {
                     $vs_sql_where .= " AND representation_id <= ?";
                     $va_params[] = $vn_end;
                 }
             }
         }
         if ($vs_sql_where) {
             $vs_sql_where .= " AND mimetype = 'application/pdf'";
         } else {
             $vs_sql_where = " WHERE mimetype = 'application/pdf'";
         }
         $qr_reps = $o_db->query("\n\t\t\t\t\tSELECT * \n\t\t\t\t\tFROM ca_object_representations \n\t\t\t\t\t{$vs_sql_where}\n\t\t\t\t\tORDER BY representation_id\n\t\t\t\t", $va_params);
         print CLIProgressBar::start($qr_reps->numRows(), _t('Reindexing PDF representations'));
         $vn_rep_table_num = $t_rep->tableNum();
         while ($qr_reps->nextRow()) {
             $va_media_info = $qr_reps->getMediaInfo('media');
             $vs_original_filename = $va_media_info['ORIGINAL_FILENAME'];
             print CLIProgressBar::next(1, _t("Reindexing PDF %1", $vs_original_filename ? $vs_original_filename . " (" . $qr_reps->get('representation_id') . ")" : $qr_reps->get('representation_id')));
             $t_rep->load($qr_reps->get('representation_id'));
             $vn_rep_id = $t_rep->getPrimaryKey();
             $m = new Media();
             if ($m->read($vs_path = $t_rep->getMediaPath('media', 'original')) && is_array($va_locs = $m->getExtractedTextLocations())) {
                 MediaContentLocationIndexer::clear($vn_rep_table_num, $vn_rep_id);
                 foreach ($va_locs as $vs_content => $va_loc_list) {
                     foreach ($va_loc_list as $va_loc) {
                         MediaContentLocationIndexer::index($vn_rep_table_num, $vn_rep_id, $vs_content, $va_loc['p'], $va_loc['x1'], $va_loc['y1'], $va_loc['x2'], $va_loc['y2']);
                     }
                 }
                 MediaContentLocationIndexer::write();
             } else {
                 //CLIUtils::addError(_t("[Warning] No content to reindex for PDF representation: %1", $vs_path));
             }
         }
         print CLIProgressBar::finish();
     }
     if (in_array('all', $va_kinds) || in_array('ca_attributes', $va_kinds)) {
         // get all Media elements
         $va_elements = ca_metadata_elements::getElementsAsList(false, null, null, true, false, true, array(16));
         // 16=media
         $qr_c = $o_db->query("\n\t\t\t\t\tSELECT count(*) c \n\t\t\t\t\tFROM ca_attribute_values\n\t\t\t\t\tWHERE\n\t\t\t\t\t\telement_id in (?)\n\t\t\t\t", caExtractValuesFromArrayList($va_elements, 'element_id', array('preserveKeys' => false)));
         if ($qr_c->nextRow()) {
             $vn_count = $qr_c->get('c');
         } else {
             $vn_count = 0;
         }
         $t_attr_val = new ca_attribute_values();
         $vn_attr_table_num = $t_attr_val->tableNum();
         print CLIProgressBar::start($vn_count, _t('Reindexing metadata attribute media'));
         foreach ($va_elements as $vs_element_code => $va_element_info) {
             $qr_vals = $o_db->query("SELECT value_id FROM ca_attribute_values WHERE element_id = ?", (int) $va_element_info['element_id']);
             $va_vals = $qr_vals->getAllFieldValues('value_id');
             foreach ($va_vals as $vn_value_id) {
                 $t_attr_val = new ca_attribute_values($vn_value_id);
                 if ($t_attr_val->getPrimaryKey()) {
                     $t_attr_val->setMode(ACCESS_WRITE);
                     $t_attr_val->useBlobAsMediaField(true);
                     $va_media_info = $t_attr_val->getMediaInfo('value_blob');
                     $vs_original_filename = $va_media_info['ORIGINAL_FILENAME'];
                     if (!is_array($va_media_info) || $va_media_info['MIMETYPE'] !== 'application/pdf') {
                         continue;
                     }
                     print CLIProgressBar::next(1, _t("Reindexing %1", $vs_original_filename ? $vs_original_filename . " ({$vn_value_id})" : $vn_value_id));
                     $m = new Media();
                     if ($m->read($vs_path = $t_attr_val->getMediaPath('value_blob', 'original')) && is_array($va_locs = $m->getExtractedTextLocations())) {
                         MediaContentLocationIndexer::clear($vn_attr_table_num, $vn_attr_table_num);
                         foreach ($va_locs as $vs_content => $va_loc_list) {
                             foreach ($va_loc_list as $va_loc) {
                                 MediaContentLocationIndexer::index($vn_attr_table_num, $vn_value_id, $vs_content, $va_loc['p'], $va_loc['x1'], $va_loc['y1'], $va_loc['x2'], $va_loc['y2']);
                             }
                         }
                         MediaContentLocationIndexer::write();
                     } else {
                         //CLIUtils::addError(_t("[Warning] No content to reindex for PDF in metadata attribute: %1", $vs_path));
                     }
                 }
             }
         }
         print CLIProgressBar::finish();
     }
     return true;
 }
 private function getElementAsDOM($pn_parent_id)
 {
     $t_element = new ca_metadata_elements();
     $t_list = new ca_lists();
     $qr_elements = $this->opo_db->query("SELECT * FROM ca_metadata_elements WHERE parent_id = ? ORDER BY element_id", $pn_parent_id);
     if (!$qr_elements->numRows()) {
         return null;
     }
     $vo_elements = $this->opo_dom->createElement("elements");
     while ($qr_elements->nextRow()) {
         $vo_element = $this->opo_dom->createElement("metadataElement");
         $vo_element->setAttribute("code", $this->makeIDNO($qr_elements->get("element_code")));
         $vo_element->setAttribute("datatype", ca_metadata_elements::getAttributeNameForTypeCode($qr_elements->get("datatype")));
         if ($qr_elements->get("list_id")) {
             $t_list->load($qr_elements->get("list_id"));
             $vo_element->setAttribute("list", $t_list->get("list_code"));
         }
         $vo_labels = $this->opo_dom->createElement("labels");
         $qr_element_labels = $this->opo_db->query("SELECT * FROM ca_metadata_element_labels WHERE element_id=?", $qr_elements->get("element_id"));
         while ($qr_element_labels->nextRow()) {
             $vo_label = $this->opo_dom->createElement("label");
             $vo_label->setAttribute("locale", $this->opt_locale->localeIDToCode($qr_element_labels->get("locale_id")));
             $vo_label->appendChild($this->opo_dom->createElement("name", caEscapeForXML($qr_element_labels->get("name"))));
             if (strlen(trim($qr_element_labels->get("description"))) > 0) {
                 $vo_label->appendChild($this->opo_dom->createElement("description", caEscapeForXML($qr_element_labels->get("description"))));
             }
             $vo_labels->appendChild($vo_label);
         }
         $vo_element->appendChild($vo_labels);
         $t_element->load($qr_elements->get("element_id"));
         $vo_settings = $this->opo_dom->createElement("settings");
         if (is_array($va_settings = $t_element->getSettings())) {
             foreach ($va_settings as $vs_setting => $va_values) {
                 if (is_null($va_values)) {
                     continue;
                 }
                 if (!is_array($va_values)) {
                     $va_values = array($va_values);
                 }
                 foreach ($va_values as $vs_value) {
                     $vo_setting = $this->opo_dom->createElement("setting", $vs_value);
                     $vo_setting->setAttribute("name", $vs_setting);
                     $vo_settings->appendChild($vo_setting);
                 }
             }
         }
         $vo_element->appendChild($vo_settings);
         $vo_sub_elements = $this->getElementAsDOM($qr_elements->get("element_id"));
         if ($vo_sub_elements) {
             $vo_element->appendChild($vo_sub_elements);
         }
         $vo_elements->appendChild($vo_element);
     }
     return $vo_elements;
 }
 /**
  * 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;
 }
 /**
  * Returns list of valid template placeholders for the specified bundle. These placeholders always begin
  * with a caret ("^") and will be replaced with content values when a bundle display is rendered by xxx()
  * 
  * @param $ps_bundle_name - name of bundle
  * @return array - list of placeholders as keys; values are text description of value; will return null if bundle name is invalid
  */
 public function getTemplatePlaceholderListForBundle($ps_bundle_name)
 {
     $o_dm = $this->getAppDatamodel();
     $t_instance = null;
     $va_tmp = explode('.', $ps_bundle_name);
     switch (sizeof($va_tmp)) {
         case 2:
             $vs_table = $va_tmp[0];
             $vs_bundle = $va_tmp[1];
             if ($vs_bundle == 'rel') {
                 $vs_bundle = 'preferred_labels';
             }
             break;
         case 1:
             if (!($t_instance = $o_dm->getInstanceByTableName($va_tmp[0], true))) {
                 $vs_table = $o_dm->getTableName($this->get('table_num'));
                 $vs_bundle = $va_tmp[0];
             } else {
                 $vs_table = $va_tmp[0];
                 $vs_bundle = 'preferred_labels';
             }
             break;
         default:
             return null;
             break;
     }
     if (!$t_instance) {
         if (!($t_instance = $o_dm->getInstanceByTableName($vs_table, true))) {
             return null;
         }
     }
     $va_key = array('^label' => array('label' => _t('Placement label'), 'description' => _t('The label for this placement as defined in the placements settings. The value used will be adjusted to reflect the current user&apos;s locale.')));
     if ($t_instance->hasField($vs_bundle)) {
         // is intrinsic field
         $va_key["^{$vs_bundle}"] = array('label' => $t_instance->getFieldInfo($vs_bundle, 'LABEL'), 'description' => $t_instance->getFieldInfo($vs_bundle, 'DESCRIPTION'));
         return $va_key;
     }
     $va_element_codes = array_flip($t_instance->getApplicableElementCodes(null, false, false));
     if ($va_element_codes[$vs_bundle]) {
         $t_element = new ca_metadata_elements();
         if ($this->inTransaction()) {
             $t_element->setTransaction($this->getTransaction());
         }
         if ($t_element->load(array('element_code' => $vs_bundle))) {
             // is attribute
             $va_hier = $t_element->getElementsInSet();
             if (is_array($va_hier) && sizeof($va_hier) > 0) {
                 // is container with children
                 foreach ($va_hier as $va_node) {
                     if ($va_node['datatype'] == 0) {
                         continue;
                     }
                     // skip containers
                     $va_key['^' . $va_node['element_code']] = array('label' => $t_instance->getAttributeLabel($va_node['element_code']), 'description' => $t_instance->getAttributeDescription($va_node['element_code']));
                 }
                 return $va_key;
             }
             // is simple single-element attribute
             $va_key["^{$vs_bundle}"] = array('label' => $t_instance->getAttributeLabel($vs_bundle), 'description' => $t_instance->getAttributeDescription($vs_bundle));
             return $va_key;
         }
     }
     if ($vs_bundle == 'preferred_labels') {
         if ($t_label = $t_instance->getLabelTableInstance()) {
             foreach ($t_label->getFormFields() as $vs_field => $va_field_info) {
                 $va_key['^' . $vs_field] = array('label' => $va_field_info['LABEL'], 'description' => $va_field_info['DESCRIPTION']);
             }
             return $va_key;
         }
     }
     if ($vs_bundle == 'nonpreferred_labels') {
         if ($t_label = $t_instance->getLabelTableInstance()) {
             foreach ($t_label->getFormFields() as $vs_field => $va_field_info) {
                 $va_key['^' . $vs_field] = array('label' => $va_field_info['LABEL'], 'description' => $va_field_info['DESCRIPTION']);
             }
             return $va_key;
         }
     }
     if ($vs_bundle == 'ca_object_representations') {
         if ($vs_table == 'ca_objects') {
             $t_rep = new ca_object_representations();
             foreach ($t_rep->getFormFields() as $vs_field => $va_field_info) {
                 $va_key['^' . $vs_field] = array('label' => $va_field_info['LABEL'], 'description' => $va_field_info['DESCRIPTION']);
             }
             $va_key['^media:{version name}'] = array('label' => _t('Specified version of media'), 'description' => _t('The version of the media representation specified by {version name} for display.'));
             return $va_key;
         }
     }
     return null;
 }
Example #22
0
 /**
  * @param $pa_hits Array of row_ids to sort. *MUST HAVE row_ids AS KEYS, NOT VALUES*
  */
 public function sortHits($pa_hits, $ps_field, $ps_direction = 'asc', $pa_options = null)
 {
     if (!in_array(strtolower($ps_direction), array('asc', 'desc'))) {
         $ps_direction = 'asc';
     }
     if (!is_array($pa_hits) || !sizeof($pa_hits)) {
         return $pa_hits;
     }
     $vs_search_tmp_table = $this->loadListIntoTemporaryResultTable($pa_hits, $pa_options['search']);
     $t_table = $this->opo_datamodel->getInstanceByTableNum($this->opn_tablenum, true);
     $vs_table_pk = $t_table->primaryKey();
     $vs_table_name = $this->ops_tablename;
     $va_fields = explode(';', $ps_field);
     $va_sorted_hits = array();
     $vn_num_locales = ca_locales::numberOfCataloguingLocales();
     foreach ($va_fields as $vs_field) {
         $va_joins = $va_orderbys = array();
         $vs_locale_where = $vs_is_preferred_sql = '';
         $va_tmp = explode('.', $vs_field);
         // Rewrite for <table>.preferred_labels.* syntax
         if ($va_tmp[1] == 'preferred_labels') {
             if ($t_labeled_item_table = $this->opo_datamodel->getInstanceByTableName($va_tmp[0], true)) {
                 if ($t_label_table = $t_labeled_item_table->getLabelTableInstance()) {
                     $va_tmp2 = array($t_label_table->tableName());
                     if (isset($va_tmp[2]) && $t_label_table->hasField($va_tmp[2])) {
                         $va_tmp2[] = $va_tmp[2];
                     } else {
                         $va_tmp2[] = $t_labeled_item_table->getLabelDisplayField();
                     }
                     $va_tmp = $va_tmp2;
                     $vs_field = join(".", $va_tmp);
                 }
             }
         }
         if ($va_tmp[0] == $vs_table_name) {
             //
             // sort field is in search table
             //
             if (!$t_table->hasField($va_tmp[1])) {
                 //
                 // is it an attribute?
                 //
                 $t_element = new ca_metadata_elements();
                 $vs_sort_element_code = array_pop($va_tmp);
                 if ($t_element->load(array('element_code' => $vs_sort_element_code))) {
                     $vn_element_id = $t_element->getPrimaryKey();
                     if (!($vs_sortable_value_fld = Attribute::getSortFieldForDatatype($t_element->get('datatype')))) {
                         return $pa_hits;
                     }
                     if ((int) $t_element->get('datatype') == 3) {
                         $vs_sortable_value_fld = 'lil.name_plural';
                         $vs_sort_field = array_pop(explode('.', $vs_sortable_value_fld));
                         $vs_locale_where = $vn_num_locales > 1 ? ', lil.locale_id' : '';
                         $vs_sql = "\n\t\t\t\t\t\t\t\tSELECT attr.row_id, lil.locale_id, lower({$vs_sortable_value_fld}) {$vs_sort_field}\n\t\t\t\t\t\t\t\tFROM ca_attributes attr\n\t\t\t\t\t\t\t\tINNER JOIN ca_attribute_values AS attr_vals ON attr_vals.attribute_id = attr.attribute_id\n\t\t\t\t\t\t\t\tINNER JOIN ca_list_item_labels AS lil ON lil.item_id = attr_vals.item_id\n\t\t\t\t\t\t\t\tINNER JOIN {$vs_browse_tmp_table} ON {$vs_browse_tmp_table}.row_id = attr.row_id\n\t\t\t\t\t\t\t\tWHERE\n\t\t\t\t\t\t\t\t\t(attr_vals.element_id = ?) AND (attr.table_num = ?) AND (lil.{$vs_sort_field} IS NOT NULL)\n\t\t\t\t\t\t\t\tORDER BY lil.{$vs_sort_field}\n\t\t\t\t\t\t\t";
                     } else {
                         $vs_sortable_value_fld = 'attr_vals.' . $vs_sortable_value_fld;
                         $vs_sort_field = array_pop(explode('.', $vs_sortable_value_fld));
                         $vs_locale_where = $vn_num_locales > 1 ? 'attr.locale_id' : '';
                         $vs_sql = "\n\t\t\t\t\t\t\t\tSELECT attr.row_id, attr.locale_id, lower({$vs_sortable_value_fld}) {$vs_sort_field}\n\t\t\t\t\t\t\t\tFROM ca_attributes attr\n\t\t\t\t\t\t\t\tINNER JOIN ca_attribute_values AS attr_vals ON attr_vals.attribute_id = attr.attribute_id\n\t\t\t\t\t\t\t\tINNER JOIN {$vs_search_tmp_table} ON {$vs_search_tmp_table}.row_id = attr.row_id\n\t\t\t\t\t\t\t\tWHERE\n\t\t\t\t\t\t\t\t\t(attr_vals.element_id = ?) AND (attr.table_num = ?) AND (attr_vals.{$vs_sort_field} IS NOT NULL)\n\t\t\t\t\t\t\t\tORDER BY attr_vals.{$vs_sort_field}\n\t\t\t\t\t\t\t";
                         //print $vs_sql." ; $vn_element_id/; ".$this->opn_tablenum."<br>";
                     }
                     $qr_sort = $this->opo_db->query($vs_sql, (int) $vn_element_id, (int) $this->opn_tablenum);
                     while ($qr_sort->nextRow()) {
                         $va_row = $qr_sort->getRow();
                         if (!$va_row['row_id']) {
                             continue;
                         }
                         if ($vn_num_locales > 1) {
                             $va_sorted_hits[$va_row['row_id']][$va_row['locale_id']] .= trim(str_replace(array("'", '"'), array('', ''), $va_row[$vs_sort_field]));
                         } else {
                             $va_sorted_hits[$va_row['row_id']] .= trim(str_replace(array("'", '"'), array('', ''), $va_row[$vs_sort_field]));
                         }
                         unset($pa_hits[$va_row['row_id']]);
                     }
                     // Add on hits that aren't sorted because they don't have an attribute associated
                     foreach ($pa_hits as $vn_id => $va_row) {
                         if (!is_array($va_row)) {
                             $va_row = array();
                         }
                         if ($vn_num_locales > 1) {
                             $va_sorted_hits[$vn_id][1] = $va_row;
                         } else {
                             $va_sorted_hits[$vn_id] = $va_row;
                         }
                     }
                 }
                 continue;
             } else {
                 $va_field_info = $t_table->getFieldInfo($va_tmp[1]);
                 if ($va_field_info['START'] && $va_field_info['END']) {
                     $va_orderbys[] = $va_field_info['START'] . ' ' . $ps_direction;
                     $va_orderbys[] = $va_field_info['END'] . ' ' . $ps_direction;
                 } else {
                     $va_orderbys[] = $vs_field . ' ' . $ps_direction;
                 }
                 if ($t_table->hasField('locale_id')) {
                     $vs_locale_where = ", " . $vs_table_name . ".locale_id";
                 }
                 $vs_sortable_value_fld = $vs_field;
             }
         } else {
             // sort field is in related table
             $va_path = $this->opo_datamodel->getPath($vs_table_name, $va_tmp[0]);
             if (sizeof($va_path) > 2) {
                 // many-many
                 $vs_last_table = null;
                 // generate related joins
                 foreach ($va_path as $vs_table => $va_info) {
                     $t_table = $this->opo_datamodel->getInstanceByTableName($vs_table, true);
                     if (!$vs_last_table) {
                         //$va_joins[$vs_table] = "INNER JOIN ".$vs_table." ON ".$vs_table.".".$t_table->primaryKey()." = ca_sql_search_search_final.row_id";
                     } else {
                         $va_rels = $this->opo_datamodel->getOneToManyRelations($vs_last_table, $vs_table);
                         if (!sizeof($va_rels)) {
                             $va_rels = $this->opo_datamodel->getOneToManyRelations($vs_table, $vs_last_table);
                         }
                         if ($vs_table == $va_rels['one_table']) {
                             $va_joins[$vs_table] = "INNER JOIN " . $va_rels['one_table'] . " ON " . $va_rels['one_table'] . "." . $va_rels['one_table_field'] . " = " . $va_rels['many_table'] . "." . $va_rels['many_table_field'];
                         } else {
                             $va_joins[$vs_table] = "INNER JOIN " . $va_rels['many_table'] . " ON " . $va_rels['many_table'] . "." . $va_rels['many_table_field'] . " = " . $va_rels['one_table'] . "." . $va_rels['one_table_field'];
                         }
                     }
                     $t_last_table = $t_table;
                     $vs_last_table = $vs_table;
                 }
                 $va_orderbys[] = $vs_field . ' ' . $ps_direction;
                 $vs_sortable_value_fld = $vs_field;
             } else {
                 $va_rels = $this->opo_datamodel->getRelationships($vs_table_name, $va_tmp[0]);
                 if (!$va_rels) {
                     return $pa_hits;
                 }
                 // return hits unsorted if field is not valid
                 $t_rel = $this->opo_datamodel->getInstanceByTableName($va_tmp[0], true);
                 if (!$t_rel->hasField($va_tmp[1])) {
                     return $pa_hits;
                 }
                 $va_joins[$va_tmp[0]] = 'LEFT JOIN ' . $va_tmp[0] . ' ON ' . $vs_table_name . '.' . $va_rels[$vs_table_name][$va_tmp[0]][0][0] . ' = ' . $va_tmp[0] . '.' . $va_rels[$vs_table_name][$va_tmp[0]][0][1] . "\n";
                 $va_orderbys[] = $vs_field . ' ' . $ps_direction;
                 // if the related supports preferred values (eg. *_labels tables) then only consider those in the sort
                 if ($t_rel->hasField('is_preferred')) {
                     $vs_is_preferred_sql = " " . $va_tmp[0] . ".is_preferred = 1";
                 }
                 if ($t_rel->hasField('locale_id')) {
                     $vs_locale_where = ", " . $va_tmp[0] . ".locale_id";
                 }
                 $vs_sortable_value_fld = $vs_field;
             }
         }
         //
         // Grab values and index for sorting later
         //
         $va_tmp = explode('.', $vs_sortable_value_fld);
         $vs_sort_field = array_pop($va_tmp);
         $vs_join_sql = join("\n", $va_joins);
         $vs_sql = "\n\t\t\t\tSELECT {$vs_table_name}.{$vs_table_pk}{$vs_locale_where}, lower({$vs_sortable_value_fld}) {$vs_sort_field}\n\t\t\t\tFROM {$vs_table_name}\n\t\t\t\t{$vs_join_sql}\n\t\t\t\tINNER JOIN {$vs_search_tmp_table} ON {$vs_search_tmp_table}.row_id = {$vs_table_name}.{$vs_table_pk}\n\t\t\t\t" . ($vs_is_preferred_sql ? 'WHERE' : '') . "\n\t\t\t\t\t{$vs_is_preferred_sql}\n\t\t\t";
         //print $vs_sql;
         $qr_sort = $this->opo_db->query($vs_sql);
         while ($qr_sort->nextRow()) {
             $va_row = $qr_sort->getRow();
             if (!($vs_sortable_value = str_replace(array("'", '"'), array('', ''), $va_row[$vs_sort_field]))) {
                 $vs_sortable_value = '';
             }
             if ($vn_num_locales > 1 && $vs_locale_where) {
                 $va_sorted_hits[$va_row[$vs_table_pk]][$va_row['locale_id']] .= $vs_sortable_value;
             } else {
                 $va_sorted_hits[$va_row[$vs_table_pk]] .= $vs_sortable_value;
             }
         }
     }
     //
     // Actually sort the hits here...
     //
     if ($vn_num_locales > 1 && $vs_locale_where) {
         $va_sorted_hits = caExtractValuesByUserLocale($va_sorted_hits);
     }
     asort($va_sorted_hits, SORT_STRING);
     if ($ps_direction == 'desc') {
         $va_sorted_hits = array_reverse($va_sorted_hits, true);
     }
     $this->cleanupTemporaryResultTable();
     return $va_sorted_hits;
 }
 /**
  * Saves all bundles on the specified screen in the database by extracting 
  * required data from the supplied request
  * $pm_screen can be a screen tag (eg. "Screen5") or a screen_id (eg. 5)
  *
  * Calls processBundlesBeforeBaseModelSave() method in subclass right before invoking insert() or update() on
  * the BaseModel, if the method is defined. Passes the following parameters to processBundlesBeforeBaseModelSave():
  *		array $pa_bundles An array of bundles to be saved
  *		string $ps_form_prefix The form prefix
  *		RequestHTTP $po_request The current request
  *		array $pa_options Optional array of parameters; expected to be the same as that passed to saveBundlesForScreen()
  *
  * The processBundlesBeforeBaseModelSave() is useful for those odd cases where you need to do some processing before the basic
  * database record defined by the model (eg. intrinsic fields and hierarchy coding) is inserted or updated. You usually don't need 
  * to use it.
  *
  * @param mixed $pm_screen
  * @param RequestHTTP $ps_request
  * @param array $pa_options Options are:
  *		dryRun = Go through the motions of saving but don't actually write information to the database
  *		batch = Process save in "batch" mode. Specifically this means honoring batch mode settings (add, replace, remove), skipping bundles that are not supported in batch mode and ignoring updates
  *		existingRepresentationMap = an array of representation_ids key'ed on file path. If set saveBundlesForScreen() use link the specified representation to the row it is saving rather than processing the uploaded file. saveBundlesForScreen() will build the map as it goes, adding newly uploaded files. If you want it to process a file in a batch situation where it should be processed the first time and linked subsequently then pass an empty array here. saveBundlesForScreen() will use the empty array to build the map.
  */
 public function saveBundlesForScreen($pm_screen, $po_request, &$pa_options)
 {
     $vb_we_set_transaction = false;
     $vs_form_prefix = caGetOption('formName', $pa_options, $po_request->getParameter('_formName', pString));
     $vb_dryrun = caGetOption('dryRun', $pa_options, false);
     $vb_batch = caGetOption('batch', $pa_options, false);
     if (!$this->inTransaction()) {
         $this->setTransaction(new Transaction($this->getDb()));
         $vb_we_set_transaction = true;
     } else {
         if ($vb_dryrun) {
             $this->postError(799, _t('Cannot do dry run save when in transaction. Try again without setting a transaction.'), "BundlableLabelableBaseModelWithAttributes->saveBundlesForScreen()");
             return false;
         }
     }
     $vb_read_only_because_deaccessioned = $this->hasField('is_deaccessioned') && (bool) $this->getAppConfig()->get('deaccession_dont_allow_editing') && (bool) $this->get('is_deaccessioned');
     BaseModel::setChangeLogUnitID();
     // get items on screen
     $t_ui = caGetOption('ui_instance', $pa_options, ca_editor_uis::loadDefaultUI($this->tableName(), $po_request, $this->getTypeID()));
     $va_bundle_lists = $this->getBundleListsForScreen($pm_screen, $po_request, $t_ui, $pa_options);
     //
     // Filter bundles to save if deaccessioned - only allow editing of the ca_objects_deaccession bundle
     //
     if ($vb_read_only_because_deaccessioned) {
         foreach ($va_bundle_lists['bundles'] as $vn_i => $va_bundle) {
             if ($va_bundle['bundle_name'] !== 'ca_objects_deaccession') {
                 unset($va_bundle_lists['bundles'][$vn_i]);
             }
         }
         foreach ($va_bundle_lists['fields_by_type'] as $vs_type => $va_bundles) {
             foreach ($va_bundles as $vs_id => $vs_bundle_name) {
                 if ($vs_bundle_name !== 'ca_objects_deaccession') {
                     unset($va_bundle_lists['fields_by_type'][$vs_type][$vs_id]);
                 }
             }
         }
     }
     $va_bundles = $va_bundle_lists['bundles'];
     $va_fields_by_type = $va_bundle_lists['fields_by_type'];
     // save intrinsic fields
     if (is_array($va_fields_by_type['intrinsic'])) {
         $vs_idno_field = $this->getProperty('ID_NUMBERING_ID_FIELD');
         foreach ($va_fields_by_type['intrinsic'] as $vs_placement_code => $vs_f) {
             if ($vb_batch) {
                 $vs_batch_mode = $po_request->getParameter("{$vs_placement_code}{$vs_form_prefix}_batch_mode", pString);
                 if ($vs_batch_mode == '_disabled_') {
                     continue;
                 }
             }
             if (isset($_FILES["{$vs_placement_code}{$vs_form_prefix}{$vs_f}"]) && $_FILES["{$vs_placement_code}{$vs_form_prefix}{$vs_f}"]) {
                 // media field
                 $this->set($vs_f, $_FILES["{$vs_placement_code}{$vs_form_prefix}{$vs_f}"]['tmp_name'], array('original_filename' => $_FILES["{$vs_placement_code}{$vs_form_prefix}{$vs_f}"]['name']));
             } else {
                 switch ($vs_f) {
                     case 'access':
                         if ((bool) $this->getAppConfig()->get($this->tableName() . '_allow_access_inheritance') && $this->hasField('access_inherit_from_parent')) {
                             $this->set('access_inherit_from_parent', $po_request->getParameter("{$vs_placement_code}{$vs_form_prefix}access_inherit_from_parent", pInteger));
                         }
                         if (!(bool) $this->getAppConfig()->get($this->tableName() . '_allow_access_inheritance') || !$this->hasField('access_inherit_from_parent') || !(bool) $this->get('access_inherit_from_parent')) {
                             $this->set('access', $po_request->getParameter("{$vs_placement_code}{$vs_form_prefix}access", pString));
                         }
                         break;
                     case $vs_idno_field:
                         if ($this->opo_idno_plugin_instance) {
                             $this->opo_idno_plugin_instance->setDb($this->getDb());
                             $this->set($vs_f, $vs_tmp = $this->opo_idno_plugin_instance->htmlFormValue($vs_idno_field));
                         } else {
                             $this->set($vs_f, $po_request->getParameter("{$vs_placement_code}{$vs_form_prefix}{$vs_f}", pString));
                         }
                         break;
                     default:
                         // Look for fully qualified intrinsic
                         if (!strlen($vs_v = $po_request->getParameter("{$vs_placement_code}{$vs_form_prefix}{$vs_f}", pString))) {
                             // fall back to simple field name intrinsic spec - still used for "mandatory" fields such as type_id and parent_id
                             $vs_v = $po_request->getParameter("{$vs_f}", pString);
                         }
                         $this->set($vs_f, $vs_v);
                         break;
                 }
             }
             if ($this->numErrors() > 0) {
                 foreach ($this->errors() as $o_e) {
                     switch ($o_e->getErrorNumber()) {
                         case 795:
                             // field conflicts
                             foreach ($this->getFieldConflicts() as $vs_conflict_field) {
                                 $po_request->addActionError($o_e, $vs_conflict_field);
                             }
                             break;
                         default:
                             $po_request->addActionError($o_e, $vs_f);
                             break;
                     }
                 }
             }
         }
     }
     // save attributes
     $va_inserted_attributes_by_element = array();
     if (isset($va_fields_by_type['attribute']) && is_array($va_fields_by_type['attribute'])) {
         //
         // name of attribute request parameters are:
         // 	For new attributes
         // 		{$vs_form_prefix}_attribute_{element_set_id}_{element_id|'locale_id'}_new_{n}
         //		ex. ObjectBasicForm_attribute_6_locale_id_new_0 or ObjectBasicForm_attribute_6_desc_type_new_0
         //
         // 	For existing attributes:
         // 		{$vs_form_prefix}_attribute_{element_set_id}_{element_id|'locale_id'}_{attribute_id}
         //
         // look for newly created attributes; look for attributes to delete
         $va_inserted_attributes = array();
         $reserved_elements = array();
         foreach ($va_fields_by_type['attribute'] as $vs_placement_code => $vs_f) {
             $vs_element_set_code = preg_replace("/^ca_attribute_/", "", $vs_f);
             //does the attribute's datatype have a saveElement method - if so, use that instead
             $vs_element = $this->_getElementInstance($vs_element_set_code);
             $vn_element_id = $vs_element->getPrimaryKey();
             $vs_element_datatype = $vs_element->get('datatype');
             $vs_datatype = Attribute::getValueInstance($vs_element_datatype);
             if (method_exists($vs_datatype, 'saveElement')) {
                 $reserved_elements[] = $vs_element;
                 continue;
             }
             $va_attributes_to_insert = array();
             $va_attributes_to_delete = array();
             $va_locales = array();
             $vs_batch_mode = $_REQUEST[$vs_placement_code . $vs_form_prefix . '_attribute_' . $vn_element_id . '_batch_mode'];
             if ($vb_batch && $vs_batch_mode == '_delete_') {
                 // Remove all attributes and continue
                 $this->removeAttributes($vn_element_id, array('force' => true));
                 continue;
             }
             foreach ($_REQUEST as $vs_key => $vs_val) {
                 // is it a newly created attribute?
                 if (preg_match('/' . $vs_placement_code . $vs_form_prefix . '_attribute_' . $vn_element_id . '_([\\w\\d\\-_]+)_new_([\\d]+)/', $vs_key, $va_matches)) {
                     if ($vb_batch) {
                         switch ($vs_batch_mode) {
                             case '_disabled_':
                                 // skip
                                 continue 2;
                                 break;
                             case '_add_':
                                 // just try to add attribute as in normal non-batch save
                                 // noop
                                 break;
                             case '_replace_':
                                 // remove all existing attributes before trying to save
                                 $this->removeAttributes($vn_element_id, array('force' => true));
                                 continue;
                                 break;
                         }
                     }
                     $vn_c = intval($va_matches[2]);
                     // yep - grab the locale and value
                     $vn_locale_id = isset($_REQUEST[$vs_placement_code . $vs_form_prefix . '_attribute_' . $vn_element_id . '_locale_id_new_' . $vn_c]) ? $_REQUEST[$vs_placement_code . $vs_form_prefix . '_attribute_' . $vn_element_id . '_locale_id_new_' . $vn_c] : null;
                     $va_inserted_attributes_by_element[$vn_element_id][$vn_c]['locale_id'] = $va_attributes_to_insert[$vn_c]['locale_id'] = $vn_locale_id;
                     $va_inserted_attributes_by_element[$vn_element_id][$vn_c][$va_matches[1]] = $va_attributes_to_insert[$vn_c][$va_matches[1]] = $vs_val;
                 } else {
                     // is it a delete key?
                     if (preg_match('/' . $vs_placement_code . $vs_form_prefix . '_attribute_' . $vn_element_id . '_([\\d]+)_delete/', $vs_key, $va_matches)) {
                         $vn_attribute_id = intval($va_matches[1]);
                         $va_attributes_to_delete[$vn_attribute_id] = true;
                     }
                 }
             }
             // look for uploaded files as attributes
             foreach ($_FILES as $vs_key => $va_val) {
                 if (preg_match('/' . $vs_placement_code . $vs_form_prefix . '_attribute_' . $vn_element_id . '_locale_id_new_([\\d]+)/', $vs_key, $va_locale_matches)) {
                     $vn_locale_c = intval($va_locale_matches[1]);
                     $va_locales[$vn_locale_c] = $vs_val;
                     continue;
                 }
                 // is it a newly created attribute?
                 if (preg_match('/' . $vs_placement_code . $vs_form_prefix . '_attribute_' . $vn_element_id . '_([\\w\\d\\-_]+)_new_([\\d]+)/', $vs_key, $va_matches)) {
                     if (!$va_val['size']) {
                         continue;
                     }
                     // skip empty files
                     // yep - grab the value
                     $vn_c = intval($va_matches[2]);
                     $va_inserted_attributes_by_element[$vn_element_id][$vn_c]['locale_id'] = $va_attributes_to_insert[$vn_c]['locale_id'] = $va_locales[$vn_c];
                     $va_val['_uploaded_file'] = true;
                     $va_inserted_attributes_by_element[$vn_element_id][$vn_c][$va_matches[1]] = $va_attributes_to_insert[$vn_c][$va_matches[1]] = $va_val;
                 }
             }
             if (!$vb_batch) {
                 // do deletes
                 $this->clearErrors();
                 foreach ($va_attributes_to_delete as $vn_attribute_id => $vb_tmp) {
                     $this->removeAttribute($vn_attribute_id, $vs_f, array('pending_adds' => $va_attributes_to_insert));
                 }
             }
             // do inserts
             foreach ($va_attributes_to_insert as $va_attribute_to_insert) {
                 $this->clearErrors();
                 $this->addAttribute($va_attribute_to_insert, $vn_element_id, $vs_f);
             }
             if (!$vb_batch) {
                 // check for attributes to update
                 if (is_array($va_attrs = $this->getAttributesByElement($vn_element_id))) {
                     $t_element = new ca_metadata_elements();
                     $va_attrs_update_list = array();
                     foreach ($va_attrs as $o_attr) {
                         $this->clearErrors();
                         $vn_attribute_id = $o_attr->getAttributeID();
                         if (isset($va_inserted_attributes[$vn_attribute_id]) && $va_inserted_attributes[$vn_attribute_id]) {
                             continue;
                         }
                         if (isset($va_attributes_to_delete[$vn_attribute_id]) && $va_attributes_to_delete[$vn_attribute_id]) {
                             continue;
                         }
                         $vn_element_set_id = $o_attr->getElementID();
                         $va_attr_update = array('locale_id' => $po_request->getParameter($vs_placement_code . $vs_form_prefix . '_attribute_' . $vn_element_set_id . '_locale_id_' . $vn_attribute_id, pString));
                         //
                         // Check to see if there are any values in the element set that are not in the  attribute we're editing
                         // If additional sub-elements were added to the set after the attribute we're updating was created
                         // those sub-elements will not have corresponding values returned by $o_attr->getValues() above.
                         // Because we use the element_ids in those values to pull request parameters, if an element_id is missing
                         // it effectively becomes invisible and cannot be set. This is a fairly unusual case but it happens, and when it does
                         // it's really annoying. It would be nice and efficient to simply create the missing values at configuration time, but we wouldn't
                         // know what to set the values to. So what we do is, after setting all of the values present in the attribute from the request, grab
                         // the configuration for the element set and see if there are any elements in the set that we didn't get values for.
                         //
                         $va_sub_elements = $t_element->getElementsInSet($vn_element_set_id);
                         foreach ($va_sub_elements as $vn_i => $va_element_info) {
                             if ($va_element_info['datatype'] == 0) {
                                 continue;
                             }
                             //$vn_element_id = $o_attr_val->getElementID();
                             $vn_element_id = $va_element_info['element_id'];
                             $vs_k = $vs_placement_code . $vs_form_prefix . '_attribute_' . $vn_element_set_id . '_' . $vn_element_id . '_' . $vn_attribute_id;
                             if (isset($_FILES[$vs_k]) && ($va_val = $_FILES[$vs_k])) {
                                 if ($va_val['size'] > 0) {
                                     // is there actually a file?
                                     $va_val['_uploaded_file'] = true;
                                     $va_attr_update[$vn_element_id] = $va_val;
                                     continue;
                                 }
                             }
                             $vs_attr_val = $po_request->getParameter($vs_k, pString);
                             $va_attr_update[$vn_element_id] = $vs_attr_val;
                         }
                         $this->clearErrors();
                         $this->editAttribute($vn_attribute_id, $vn_element_set_id, $va_attr_update, $vs_f);
                     }
                 }
             }
         }
     }
     if (!$vb_batch) {
         // hierarchy moves are not supported in batch mode
         if (is_array($va_fields_by_type['special'])) {
             foreach ($va_fields_by_type['special'] as $vs_placement_code => $vs_bundle) {
                 if ($vs_bundle !== 'hierarchy_location') {
                     continue;
                 }
                 $va_parent_tmp = explode("-", $po_request->getParameter("{$vs_placement_code}{$vs_form_prefix}_new_parent_id", pString));
                 // Hierarchy browser sets new_parent_id param to "X" if user wants to extract item from hierarchy
                 $vn_parent_id = ($vn_parent_id = array_pop($va_parent_tmp)) == 'X' ? -1 : (int) $vn_parent_id;
                 if (sizeof($va_parent_tmp) > 0) {
                     $vs_parent_table = array_pop($va_parent_tmp);
                 } else {
                     $vs_parent_table = $this->tableName();
                 }
                 if ($this->getPrimaryKey() && $this->HIERARCHY_PARENT_ID_FLD && $vn_parent_id > 0) {
                     if ($vs_parent_table == $this->tableName()) {
                         $this->set($this->HIERARCHY_PARENT_ID_FLD, $vn_parent_id);
                     } else {
                         if ((bool) $this->getAppConfig()->get('ca_objects_x_collections_hierarchy_enabled') && $vs_parent_table == 'ca_collections' && $this->tableName() == 'ca_objects' && ($vs_coll_rel_type = $this->getAppConfig()->get('ca_objects_x_collections_hierarchy_relationship_type'))) {
                             // link object to collection
                             $this->removeRelationships('ca_collections', $vs_coll_rel_type);
                             $this->set($this->HIERARCHY_PARENT_ID_FLD, null);
                             $this->set($this->HIERARCHY_ID_FLD, $this->getPrimaryKey());
                             if (!$this->addRelationship('ca_collections', $vn_parent_id, $vs_coll_rel_type)) {
                                 $this->postError(2510, _t('Could not move object under collection: %1', join("; ", $this->getErrors())), "BundlableLabelableBaseModelWithAttributes->saveBundlesForScreen()");
                             }
                         }
                     }
                 } else {
                     if ($this->getPrimaryKey() && $this->HIERARCHY_PARENT_ID_FLD && $this->HIERARCHY_TYPE == __CA_HIER_TYPE_ADHOC_MONO__ && isset($_REQUEST["{$vs_placement_code}{$vs_form_prefix}_new_parent_id"]) && $vn_parent_id <= 0) {
                         $this->set($this->HIERARCHY_PARENT_ID_FLD, null);
                         $this->set($this->HIERARCHY_ID_FLD, $this->getPrimaryKey());
                         // Support for collection-object cross-table hierarchies
                         if ((bool) $this->getAppConfig()->get('ca_objects_x_collections_hierarchy_enabled') && $this->tableName() == 'ca_objects' && ($vs_coll_rel_type = $this->getAppConfig()->get('ca_objects_x_collections_hierarchy_relationship_type')) && $vn_parent_id == -1) {
                             // -1 = extract from hierarchy
                             $this->removeRelationships('ca_collections', $vs_coll_rel_type);
                         }
                     }
                 }
                 break;
             }
         }
     }
     //
     // Call processBundlesBeforeBaseModelSave() method in sub-class, if it is defined. The method is passed
     // a list of bundles, the form prefix, the current request and the options passed to saveBundlesForScreen() –
     // everything needed to perform custom processing using the incoming form content that is being saved.
     //
     // A processBundlesBeforeBaseModelSave() method is rarely needed, but can be handy when you need to do something model-specific
     // right before the basic database record is committed via insert() (for new records) or update() (for existing records).
     // For example, the media in ca_object_representations is set in a "special" bundle, which provides a specialized media upload UI. Unfortunately "special's"
     // are handled after the basic database record is saved via insert() or update(), while the actual media must be set prior to the save.
     // processBundlesBeforeBaseModelSave() allows special logic in the ca_object_representations model to be invoked to set the media before the insert() or update().
     // The "special" takes care of other functions after the insert()/update()
     //
     if (method_exists($this, "processBundlesBeforeBaseModelSave")) {
         $this->processBundlesBeforeBaseModelSave($va_bundles, $vs_form_prefix, $po_request, $pa_options);
     }
     $this->setMode(ACCESS_WRITE);
     $vb_is_insert = false;
     if ($this->getPrimaryKey()) {
         $this->update();
     } else {
         $this->insert();
         $vb_is_insert = true;
     }
     if ($this->numErrors() > 0) {
         $va_errors = array();
         foreach ($this->errors() as $o_e) {
             switch ($o_e->getErrorNumber()) {
                 case 2010:
                     $po_request->addActionErrors(array($o_e), 'hierarchy_location');
                     break;
                 case 795:
                     // field conflict
                     foreach ($this->getFieldConflicts() as $vs_conflict_field) {
                         $po_request->addActionError($o_e, $vs_conflict_field);
                     }
                     break;
                 case 1100:
                     if ($vs_idno_field = $this->getProperty('ID_NUMBERING_ID_FIELD')) {
                         $po_request->addActionError($o_e, $this->getProperty('ID_NUMBERING_ID_FIELD'));
                     }
                     break;
                 default:
                     $va_errors[] = $o_e;
                     break;
             }
         }
         $po_request->addActionErrors($va_errors);
         if ($vb_is_insert) {
             BaseModel::unsetChangeLogUnitID();
             if ($vb_we_set_transaction) {
                 $this->removeTransaction(false);
             }
             return false;
             // bail on insert error
         }
     }
     if (!$this->getPrimaryKey()) {
         BaseModel::unsetChangeLogUnitID();
         if ($vb_we_set_transaction) {
             $this->removeTransaction(false);
         }
         return false;
     }
     // bail if insert failed
     $this->clearErrors();
     //save reserved elements -  those with a saveElement method
     if (isset($reserved_elements) && is_array($reserved_elements)) {
         foreach ($reserved_elements as $res_element) {
             $res_element_id = $res_element->getPrimaryKey();
             $res_element_datatype = $res_element->get('datatype');
             $res_datatype = Attribute::getValueInstance($res_element_datatype);
             $res_datatype->saveElement($this, $res_element, $vs_form_prefix, $po_request);
         }
     }
     // save preferred labels
     if ($this->getProperty('LABEL_TABLE_NAME')) {
         $vb_check_for_dupe_labels = $this->_CONFIG->get('allow_duplicate_labels_for_' . $this->tableName()) ? false : true;
         $vb_error_inserting_pref_label = false;
         if (is_array($va_fields_by_type['preferred_label'])) {
             foreach ($va_fields_by_type['preferred_label'] as $vs_placement_code => $vs_f) {
                 if (!$vb_batch) {
                     // check for existing labels to update (or delete)
                     $va_preferred_labels = $this->getPreferredLabels(null, false);
                     foreach ($va_preferred_labels as $vn_item_id => $va_labels_by_locale) {
                         foreach ($va_labels_by_locale as $vn_locale_id => $va_label_list) {
                             foreach ($va_label_list as $va_label) {
                                 if ($vn_label_locale_id = $po_request->getParameter($vs_placement_code . $vs_form_prefix . '_Pref' . 'locale_id_' . $va_label['label_id'], pString)) {
                                     if (is_array($va_label_values = $this->getLabelUIValuesFromRequest($po_request, $vs_placement_code . $vs_form_prefix, $va_label['label_id'], true))) {
                                         if ($vb_check_for_dupe_labels && $this->checkForDupeLabel($vn_label_locale_id, $va_label_values)) {
                                             $this->postError(1125, _t('Value <em>%1</em> is already used and duplicates are not allowed', join("/", $va_label_values)), "BundlableLabelableBaseModelWithAttributes->saveBundlesForScreen()", $this->tableName() . '.preferred_labels');
                                             $po_request->addActionErrors($this->errors(), 'preferred_labels');
                                             continue;
                                         }
                                         $vn_label_type_id = $po_request->getParameter($vs_placement_code . $vs_form_prefix . '_Pref' . 'type_id_' . $va_label['label_id'], pInteger);
                                         $this->editLabel($va_label['label_id'], $va_label_values, $vn_label_locale_id, $vn_label_type_id, true);
                                         if ($this->numErrors()) {
                                             foreach ($this->errors() as $o_e) {
                                                 switch ($o_e->getErrorNumber()) {
                                                     case 795:
                                                         // field conflicts
                                                         $po_request->addActionError($o_e, 'preferred_labels');
                                                         break;
                                                     default:
                                                         $po_request->addActionError($o_e, $vs_f);
                                                         break;
                                                 }
                                             }
                                         }
                                     }
                                 } else {
                                     if ($po_request->getParameter($vs_placement_code . $vs_form_prefix . '_PrefLabel_' . $va_label['label_id'] . '_delete', pString)) {
                                         // delete
                                         $this->removeLabel($va_label['label_id']);
                                     }
                                 }
                             }
                         }
                     }
                 }
                 // check for new labels to add
                 foreach ($_REQUEST as $vs_key => $vs_value) {
                     if (!preg_match('/' . $vs_placement_code . $vs_form_prefix . '_Pref' . 'locale_id_new_([\\d]+)/', $vs_key, $va_matches)) {
                         continue;
                     }
                     if ($vb_batch) {
                         $vs_batch_mode = $po_request->getParameter($vs_placement_code . $vs_form_prefix . '_Pref_batch_mode', pString);
                         switch ($vs_batch_mode) {
                             case '_disabled_':
                                 // skip
                                 continue 2;
                                 break;
                             case '_replace_':
                                 // remove all existing preferred labels before trying to save
                                 $this->removeAllLabels(__CA_LABEL_TYPE_PREFERRED__);
                                 continue;
                             case '_delete_':
                                 // remove all existing preferred labels
                                 $this->removeAllLabels(__CA_LABEL_TYPE_PREFERRED__);
                                 continue 2;
                             case '_add_':
                                 break;
                         }
                     }
                     $vn_c = intval($va_matches[1]);
                     if ($vn_new_label_locale_id = $po_request->getParameter($vs_placement_code . $vs_form_prefix . '_Pref' . 'locale_id_new_' . $vn_c, pString)) {
                         if (is_array($va_label_values = $this->getLabelUIValuesFromRequest($po_request, $vs_placement_code . $vs_form_prefix, 'new_' . $vn_c, true))) {
                             // make sure we don't add multiple pref labels for one locale in batch mode
                             if ($vb_batch && $vs_batch_mode == '_add_') {
                                 // first remove [BLANK] labels for this locale if there are any, as we are about to add a new one
                                 $va_labels_for_this_locale = $this->getPreferredLabels(array($vn_new_label_locale_id));
                                 if (is_array($va_labels_for_this_locale)) {
                                     foreach ($va_labels_for_this_locale as $vn_id => $va_labels_by_locale) {
                                         foreach ($va_labels_by_locale as $vn_locale_id => $va_labels) {
                                             foreach ($va_labels as $vn_i => $va_label) {
                                                 if (isset($va_label[$this->getLabelDisplayField()]) && $va_label[$this->getLabelDisplayField()] == '[' . _t('BLANK') . ']') {
                                                     $this->removeLabel($va_label['label_id']);
                                                 }
                                             }
                                         }
                                     }
                                 }
                                 // if there are non-[BLANK] labels for this locale, don't add this new one
                                 $va_labels_for_this_locale = $this->getPreferredLabels(array($vn_new_label_locale_id), true, array('forDisplay' => true));
                                 if (is_array($va_labels_for_this_locale) && sizeof($va_labels_for_this_locale) > 0) {
                                     $this->postError(1125, _t('A preferred label for this locale already exists. Only one preferred label per locale is allowed.'), "BundlableLabelableBaseModelWithAttributes->saveBundlesForScreen()", $this->tableName() . '.preferred_labels');
                                     $po_request->addActionErrors($this->errors(), $vs_f);
                                     $vb_error_inserting_pref_label = true;
                                     continue;
                                 }
                             }
                             if ($vb_check_for_dupe_labels && $this->checkForDupeLabel($vn_new_label_locale_id, $va_label_values)) {
                                 $this->postError(1125, _t('Value <em>%1</em> is already used and duplicates are not allowed', join("/", $va_label_values)), "BundlableLabelableBaseModelWithAttributes->saveBundlesForScreen()", $this->tableName() . '.preferred_labels');
                                 $po_request->addActionErrors($this->errors(), 'preferred_labels');
                                 $vb_error_inserting_pref_label = true;
                                 continue;
                             }
                             $vn_label_type_id = $po_request->getParameter($vs_placement_code . $vs_form_prefix . '_Pref' . 'type_id_new_' . $vn_c, pInteger);
                             $this->addLabel($va_label_values, $vn_new_label_locale_id, $vn_label_type_id, true);
                             if ($this->numErrors()) {
                                 $po_request->addActionErrors($this->errors(), $vs_f);
                                 $vb_error_inserting_pref_label = true;
                             }
                         }
                     }
                 }
             }
         }
     }
     // Add default label if needed (ie. if the user has failed to set at least one label or if they have deleted all existing labels)
     // This ensures at least one label is present for the record. If no labels are present then the
     // record may not be found in queries
     if ($this->getProperty('LABEL_TABLE_NAME')) {
         if ($vb_error_inserting_pref_label || !$this->addDefaultLabel($vn_new_label_locale_id)) {
             if (!$vb_error_inserting_pref_label) {
                 $po_request->addActionErrors($this->errors(), 'preferred_labels');
             }
             if ($vb_we_set_transaction) {
                 $this->removeTransaction(false);
             }
             if ($vb_is_insert) {
                 $this->_FIELD_VALUES[$this->primaryKey()] = null;
                 // clear primary key, which doesn't actually exist since we rolled back the transaction
                 foreach ($va_inserted_attributes_by_element as $vn_element_id => $va_failed_inserts) {
                     // set attributes as "failed" (but with no error messages) so they stay set
                     $this->setFailedAttributeInserts($vn_element_id, $va_failed_inserts);
                 }
             }
             return false;
         }
     }
     unset($va_inserted_attributes_by_element);
     // save non-preferred labels
     if ($this->getProperty('LABEL_TABLE_NAME') && isset($va_fields_by_type['nonpreferred_label']) && is_array($va_fields_by_type['nonpreferred_label'])) {
         if (!$vb_batch) {
             foreach ($va_fields_by_type['nonpreferred_label'] as $vs_placement_code => $vs_f) {
                 // check for existing labels to update (or delete)
                 $va_nonpreferred_labels = $this->getNonPreferredLabels(null, false);
                 foreach ($va_nonpreferred_labels as $vn_item_id => $va_labels_by_locale) {
                     foreach ($va_labels_by_locale as $vn_locale_id => $va_label_list) {
                         foreach ($va_label_list as $va_label) {
                             if ($vn_label_locale_id = $po_request->getParameter($vs_placement_code . $vs_form_prefix . '_NPref' . 'locale_id_' . $va_label['label_id'], pString)) {
                                 if (is_array($va_label_values = $this->getLabelUIValuesFromRequest($po_request, $vs_placement_code . $vs_form_prefix, $va_label['label_id'], false))) {
                                     $vn_label_type_id = $po_request->getParameter($vs_placement_code . $vs_form_prefix . '_NPref' . 'type_id_' . $va_label['label_id'], pInteger);
                                     $this->editLabel($va_label['label_id'], $va_label_values, $vn_label_locale_id, $vn_label_type_id, false);
                                     if ($this->numErrors()) {
                                         foreach ($this->errors() as $o_e) {
                                             switch ($o_e->getErrorNumber()) {
                                                 case 795:
                                                     // field conflicts
                                                     $po_request->addActionError($o_e, 'nonpreferred_labels');
                                                     break;
                                                 default:
                                                     $po_request->addActionError($o_e, $vs_f);
                                                     break;
                                             }
                                         }
                                     }
                                 }
                             } else {
                                 if ($po_request->getParameter($vs_placement_code . $vs_form_prefix . '_NPrefLabel_' . $va_label['label_id'] . '_delete', pString)) {
                                     // delete
                                     $this->removeLabel($va_label['label_id']);
                                 }
                             }
                         }
                     }
                 }
             }
         }
         // check for new labels to add
         foreach ($va_fields_by_type['nonpreferred_label'] as $vs_placement_code => $vs_f) {
             if ($vb_batch) {
                 $vs_batch_mode = $po_request->getParameter($vs_placement_code . $vs_form_prefix . '_NPref_batch_mode', pString);
                 switch ($vs_batch_mode) {
                     case '_disabled_':
                         // skip
                         continue 2;
                         break;
                     case '_add_':
                         // just try to add attribute as in normal non-batch save
                         // noop
                         break;
                     case '_replace_':
                         // remove all existing nonpreferred labels before trying to save
                         $this->removeAllLabels(__CA_LABEL_TYPE_NONPREFERRED__);
                         continue;
                     case '_delete_':
                         // remove all existing nonpreferred labels
                         $this->removeAllLabels(__CA_LABEL_TYPE_NONPREFERRED__);
                         continue 2;
                         break;
                 }
             }
             foreach ($_REQUEST as $vs_key => $vs_value) {
                 if (!preg_match('/^' . $vs_placement_code . $vs_form_prefix . '_NPref' . 'locale_id_new_([\\d]+)/', $vs_key, $va_matches)) {
                     continue;
                 }
                 $vn_c = intval($va_matches[1]);
                 if ($vn_new_label_locale_id = $po_request->getParameter($vs_placement_code . $vs_form_prefix . '_NPref' . 'locale_id_new_' . $vn_c, pString)) {
                     if (is_array($va_label_values = $this->getLabelUIValuesFromRequest($po_request, $vs_placement_code . $vs_form_prefix, 'new_' . $vn_c, false))) {
                         $vn_new_label_type_id = $po_request->getParameter($vs_placement_code . $vs_form_prefix . '_NPref' . 'type_id_new_' . $vn_c, pInteger);
                         $this->addLabel($va_label_values, $vn_new_label_locale_id, $vn_new_label_type_id, false);
                         if ($this->numErrors()) {
                             $po_request->addActionErrors($this->errors(), $vs_f);
                         }
                     }
                 }
             }
         }
     }
     // save data in related tables
     if (isset($va_fields_by_type['related_table']) && is_array($va_fields_by_type['related_table'])) {
         foreach ($va_fields_by_type['related_table'] as $vs_placement_code => $vs_f) {
             $vn_table_num = $this->_DATAMODEL->getTableNum($vs_f);
             // get settings
             $va_bundle_settings = array();
             foreach ($va_bundles as $va_bundle_info) {
                 if ($va_bundle_info['placement_code'] == $vs_placement_code) {
                     $va_bundle_settings = $va_bundle_info['settings'];
                     break;
                 }
             }
             switch ($vs_f) {
                 # -------------------------------------
                 case 'ca_object_representations':
                     // check for existing representations to update (or delete)
                     $vs_prefix_stub = $vs_placement_code . $vs_form_prefix . '_';
                     $vb_allow_fetching_of_urls = (bool) $this->_CONFIG->get('allow_fetching_of_media_from_remote_urls');
                     $va_rep_ids_sorted = $va_rep_sort_order = explode(';', $po_request->getParameter($vs_prefix_stub . 'ObjectRepresentationBundleList', pString));
                     sort($va_rep_ids_sorted, SORT_NUMERIC);
                     $va_reps = $this->getRepresentations();
                     if (!$vb_batch && is_array($va_reps)) {
                         foreach ($va_reps as $vn_i => $va_rep) {
                             $this->clearErrors();
                             if (strlen($po_request->getParameter($vs_prefix_stub . 'access_' . $va_rep['representation_id'], pInteger)) > 0) {
                                 if ($vb_allow_fetching_of_urls && ($vs_path = $_REQUEST[$vs_prefix_stub . 'media_url_' . $va_rep['representation_id']])) {
                                     $va_tmp = explode('/', $vs_path);
                                     $vs_original_name = array_pop($va_tmp);
                                 } else {
                                     $vs_path = $_FILES[$vs_prefix_stub . 'media_' . $va_rep['representation_id']]['tmp_name'];
                                     $vs_original_name = $_FILES[$vs_prefix_stub . 'media_' . $va_rep['representation_id']]['name'];
                                 }
                                 $vn_is_primary = $po_request->getParameter($vs_prefix_stub . 'is_primary_' . $va_rep['representation_id'], pString) != '' ? $po_request->getParameter($vs_prefix_stub . 'is_primary_' . $va_rep['representation_id'], pInteger) : null;
                                 $vn_locale_id = $po_request->getParameter($vs_prefix_stub . 'locale_id_' . $va_rep['representation_id'], pInteger);
                                 $vs_idno = $po_request->getParameter($vs_prefix_stub . 'idno_' . $va_rep['representation_id'], pString);
                                 $vn_access = $po_request->getParameter($vs_prefix_stub . 'access_' . $va_rep['representation_id'], pInteger);
                                 $vn_status = $po_request->getParameter($vs_prefix_stub . 'status_' . $va_rep['representation_id'], pInteger);
                                 $vs_rep_label = trim($po_request->getParameter($vs_prefix_stub . 'rep_label_' . $va_rep['representation_id'], pString));
                                 //$vn_rep_type_id = $po_request->getParameter($vs_prefix_stub.'rep_type_id'.$va_rep['representation_id'], pInteger);
                                 // Get user-specified center point (images only)
                                 $vn_center_x = $po_request->getParameter($vs_prefix_stub . 'center_x_' . $va_rep['representation_id'], pString);
                                 $vn_center_y = $po_request->getParameter($vs_prefix_stub . 'center_y_' . $va_rep['representation_id'], pString);
                                 $vn_rank = null;
                                 if (($vn_rank_index = array_search($va_rep['representation_id'], $va_rep_sort_order)) !== false) {
                                     $vn_rank = $va_rep_ids_sorted[$vn_rank_index];
                                 }
                                 $this->editRepresentation($va_rep['representation_id'], $vs_path, $vn_locale_id, $vn_status, $vn_access, $vn_is_primary, array('idno' => $vs_idno), array('original_filename' => $vs_original_name, 'rank' => $vn_rank, 'centerX' => $vn_center_x, 'centerY' => $vn_center_y));
                                 if ($this->numErrors()) {
                                     //$po_request->addActionErrors($this->errors(), $vs_f, $va_rep['representation_id']);
                                     foreach ($this->errors() as $o_e) {
                                         switch ($o_e->getErrorNumber()) {
                                             case 795:
                                                 // field conflicts
                                                 $po_request->addActionError($o_e, $vs_f, $va_rep['representation_id']);
                                                 break;
                                             default:
                                                 $po_request->addActionError($o_e, $vs_f, $va_rep['representation_id']);
                                                 break;
                                         }
                                     }
                                 }
                                 if ($vs_rep_label) {
                                     //
                                     // Set representation label
                                     //
                                     $t_rep = new ca_object_representations();
                                     if ($this->inTransaction()) {
                                         $t_rep->setTransaction($this->getTransaction());
                                     }
                                     global $g_ui_locale_id;
                                     if ($t_rep->load($va_rep['representation_id'])) {
                                         $t_rep->setMode(ACCESS_WRITE);
                                         $t_rep->replaceLabel(array('name' => $vs_rep_label), $g_ui_locale_id, null, true);
                                         if ($t_rep->numErrors()) {
                                             $po_request->addActionErrors($t_rep->errors(), $vs_f, $va_rep['representation_id']);
                                         }
                                     }
                                 }
                             } else {
                                 // is it a delete key?
                                 $this->clearErrors();
                                 if ($po_request->getParameter($vs_prefix_stub . $va_rep['representation_id'] . '_delete', pInteger) > 0) {
                                     // delete!
                                     $this->removeRepresentation($va_rep['representation_id']);
                                     if ($this->numErrors()) {
                                         $po_request->addActionErrors($this->errors(), $vs_f, $va_rep['representation_id']);
                                     }
                                 }
                             }
                         }
                     }
                     if ($vb_batch) {
                         $vs_batch_mode = $_REQUEST[$vs_prefix_stub . 'batch_mode'];
                         if ($vs_batch_mode == '_disabled_') {
                             break;
                         }
                         if ($vs_batch_mode == '_replace_') {
                             $this->removeAllRepresentations();
                         }
                         if ($vs_batch_mode == '_delete_') {
                             $this->removeAllRepresentations();
                             break;
                         }
                     }
                     // check for new representations to add
                     $va_file_list = $_FILES;
                     foreach ($_REQUEST as $vs_key => $vs_value) {
                         if (!preg_match('/^' . $vs_prefix_stub . 'media_url_new_([\\d]+)$/', $vs_key, $va_matches)) {
                             continue;
                         }
                         $va_file_list[$vs_key] = array('url' => $vs_value);
                     }
                     foreach ($va_file_list as $vs_key => $va_values) {
                         $this->clearErrors();
                         if (!preg_match('/^' . $vs_prefix_stub . 'media_new_([\\d]+)$/', $vs_key, $va_matches) && ($vb_allow_fetching_of_urls && !preg_match('/^' . $vs_prefix_stub . 'media_url_new_([\\d]+)$/', $vs_key, $va_matches) || !$vb_allow_fetching_of_urls)) {
                             continue;
                         }
                         if ($vs_upload_type = $po_request->getParameter($vs_prefix_stub . 'upload_typenew_' . $va_matches[1], pString)) {
                             $po_request->user->setVar('defaultRepresentationUploadType', $vs_upload_type);
                         }
                         $vn_type_id = $po_request->getParameter($vs_prefix_stub . 'type_id_new_' . $va_matches[1], pInteger);
                         if ($vn_existing_rep_id = $po_request->getParameter($vs_prefix_stub . 'idnew_' . $va_matches[1], pInteger)) {
                             $this->addRelationship('ca_object_representations', $vn_existing_rep_id, $vn_type_id);
                         } else {
                             if ($vb_allow_fetching_of_urls && ($vs_path = $va_values['url'])) {
                                 $va_tmp = explode('/', $vs_path);
                                 $vs_original_name = array_pop($va_tmp);
                             } else {
                                 $vs_path = $va_values['tmp_name'];
                                 $vs_original_name = $va_values['name'];
                             }
                             if (!$vs_path) {
                                 continue;
                             }
                             $vn_rep_type_id = $po_request->getParameter($vs_prefix_stub . 'rep_type_id_new_' . $va_matches[1], pInteger);
                             if (!$vn_rep_type_id && !($vn_rep_type_id = caGetDefaultItemID('object_representation_types'))) {
                                 require_once __CA_MODELS_DIR__ . '/ca_lists.php';
                                 $t_list = new ca_lists();
                                 if (is_array($va_rep_type_ids = $t_list->getItemsForList('object_representation_types', array('idsOnly' => true, 'enabledOnly' => true)))) {
                                     $vn_rep_type_id = array_shift($va_rep_type_ids);
                                 }
                             }
                             if (is_array($pa_options['existingRepresentationMap']) && isset($pa_options['existingRepresentationMap'][$vs_path]) && $pa_options['existingRepresentationMap'][$vs_path]) {
                                 $this->addRelationship('ca_object_representations', $pa_options['existingRepresentationMap'][$vs_path], $vn_type_id);
                                 break;
                             }
                             $vs_rep_label = trim($po_request->getParameter($vs_prefix_stub . 'rep_label_new_' . $va_matches[1], pString));
                             $vn_locale_id = $po_request->getParameter($vs_prefix_stub . 'locale_id_new_' . $va_matches[1], pInteger);
                             $vs_idno = $po_request->getParameter($vs_prefix_stub . 'idno_new_' . $va_matches[1], pString);
                             $vn_status = $po_request->getParameter($vs_prefix_stub . 'status_new_' . $va_matches[1], pInteger);
                             $vn_access = $po_request->getParameter($vs_prefix_stub . 'access_new_' . $va_matches[1], pInteger);
                             $vn_is_primary = $po_request->getParameter($vs_prefix_stub . 'is_primary_new_' . $va_matches[1], pInteger);
                             // Get user-specified center point (images only)
                             $vn_center_x = $po_request->getParameter($vs_prefix_stub . 'center_x_new_' . $va_matches[1], pString);
                             $vn_center_y = $po_request->getParameter($vs_prefix_stub . 'center_y_new_' . $va_matches[1], pString);
                             $t_rep = $this->addRepresentation($vs_path, $vn_rep_type_id, $vn_locale_id, $vn_status, $vn_access, $vn_is_primary, array('name' => $vs_rep_label, 'idno' => $vs_idno), array('original_filename' => $vs_original_name, 'returnRepresentation' => true, 'centerX' => $vn_center_x, 'centerY' => $vn_center_y, 'type_id' => $vn_type_id));
                             // $vn_type_id = *relationship* type_id (as opposed to representation type)
                             if ($this->numErrors()) {
                                 $po_request->addActionErrors($this->errors(), $vs_f, 'new_' . $va_matches[1]);
                             } else {
                                 if ($t_rep && is_array($pa_options['existingRepresentationMap'])) {
                                     $pa_options['existingRepresentationMap'][$vs_path] = $t_rep->getPrimaryKey();
                                 }
                             }
                         }
                     }
                     break;
                     # -------------------------------------
                 # -------------------------------------
                 case 'ca_entities':
                 case 'ca_places':
                 case 'ca_objects':
                 case 'ca_collections':
                 case 'ca_occurrences':
                 case 'ca_list_items':
                 case 'ca_object_lots':
                 case 'ca_storage_locations':
                 case 'ca_loans':
                 case 'ca_movements':
                 case 'ca_tour_stops':
                     $this->_processRelated($po_request, $vs_f, $vs_form_prefix, $vs_placement_code, array('batch' => $vb_batch, 'settings' => $va_bundle_settings));
                     break;
                     # -------------------------------------
                 # -------------------------------------
                 case 'ca_representation_annotations':
                     if ($vb_batch) {
                         break;
                     }
                     // not supported in batch mode
                     $this->_processRepresentationAnnotations($po_request, $vs_form_prefix, $vs_placement_code);
                     break;
                     # -------------------------------------
             }
         }
     }
     // save data for "specials"
     if (isset($va_fields_by_type['special']) && is_array($va_fields_by_type['special'])) {
         foreach ($va_fields_by_type['special'] as $vs_placement_code => $vs_f) {
             // get settings
             $va_bundle_settings = array();
             foreach ($va_bundles as $va_bundle_info) {
                 if ('P' . $va_bundle_info['placement_id'] == $vs_placement_code) {
                     $va_bundle_settings = $va_bundle_info['settings'];
                     break;
                 }
             }
             switch ($vs_f) {
                 # -------------------------------------
                 // This bundle is only available when editing objects of type ca_representation_annotations
                 case 'ca_representation_annotation_properties':
                     if ($vb_batch) {
                         break;
                     }
                     // not supported in batch mode
                     if (!$this->useInEditor()) {
                         break;
                     }
                     foreach ($this->getPropertyList() as $vs_property) {
                         $this->setPropertyValue($vs_property, $po_request->getParameter("{$vs_placement_code}{$vs_form_prefix}{$vs_property}", pString));
                     }
                     if (!$this->validatePropertyValues()) {
                         $po_request->addActionErrors($this->errors(), 'ca_representation_annotation_properties', 'general');
                     }
                     $this->update();
                     break;
                     # -------------------------------------
                     // This bundle is only available for types which support set membership
                 # -------------------------------------
                 // This bundle is only available for types which support set membership
                 case 'ca_sets':
                     // check for existing labels to delete (no updating supported)
                     require_once __CA_MODELS_DIR__ . '/ca_sets.php';
                     require_once __CA_MODELS_DIR__ . '/ca_set_items.php';
                     $t_set = new ca_sets();
                     if (!$vb_batch) {
                         $va_sets = caExtractValuesByUserLocale($t_set->getSetsForItem($this->tableNum(), $this->getPrimaryKey(), array('user_id' => $po_request->getUserID())));
                         foreach ($va_sets as $vn_set_id => $va_set_info) {
                             $vn_item_id = $va_set_info['item_id'];
                             if ($po_request->getParameter("{$vs_placement_code}{$vs_form_prefix}_set_id_{$vn_item_id}_delete", pString)) {
                                 // delete
                                 $t_set->load($va_set_info['set_id']);
                                 $t_set->removeItem($this->getPrimaryKey(), $po_request->getUserID());
                                 // remove *all* instances of the item in the set, not just the specified id
                                 if ($t_set->numErrors()) {
                                     $po_request->addActionErrors($t_set->errors(), $vs_f);
                                 }
                             }
                         }
                     }
                     if ($vb_batch) {
                         $vs_batch_mode = $_REQUEST["{$vs_placement_code}{$vs_form_prefix}_batch_mode"];
                         if ($vs_batch_mode == '_disabled_') {
                             break;
                         }
                         if ($vs_batch_mode == '_replace_') {
                             $t_set->removeItemFromAllSets($this->tableNum(), $this->getPrimaryKey());
                         }
                         if ($vs_batch_mode == '_delete_') {
                             $t_set->removeItemFromAllSets($this->tableNum(), $this->getPrimaryKey());
                             break;
                         }
                     }
                     foreach ($_REQUEST as $vs_key => $vs_value) {
                         if (!preg_match("/{$vs_placement_code}{$vs_form_prefix}_set_id_new_([\\d]+)/", $vs_key, $va_matches)) {
                             continue;
                         }
                         $vn_c = intval($va_matches[1]);
                         if ($vn_new_set_id = $po_request->getParameter("{$vs_placement_code}{$vs_form_prefix}_set_id_new_{$vn_c}", pString)) {
                             $t_set->load($vn_new_set_id);
                             $t_set->addItem($this->getPrimaryKey(), null, $po_request->getUserID());
                             if ($t_set->numErrors()) {
                                 $po_request->addActionErrors($t_set->errors(), $vs_f);
                             }
                         }
                     }
                     break;
                     # -------------------------------------
                     // This bundle is only available for types which support set membership
                 # -------------------------------------
                 // This bundle is only available for types which support set membership
                 case 'ca_set_items':
                     if ($vb_batch) {
                         break;
                     }
                     // not supported in batch mode
                     // check for existing labels to delete (no updating supported)
                     require_once __CA_MODELS_DIR__ . '/ca_sets.php';
                     require_once __CA_MODELS_DIR__ . '/ca_set_items.php';
                     $va_rids = explode(';', $po_request->getParameter("{$vs_placement_code}{$vs_form_prefix}setRowIDList", pString));
                     $this->reorderItems($va_rids, array('user_id' => $po_request->getUserID(), 'treatRowIDsAsRIDs' => true, 'deleteExcludedItems' => true));
                     break;
                     # -------------------------------------
                     // This bundle is only available for ca_search_forms
                 # -------------------------------------
                 // This bundle is only available for ca_search_forms
                 case 'ca_search_form_elements':
                     if ($vb_batch) {
                         break;
                     }
                     // not supported in batch mode
                     // save settings
                     $va_settings = $this->getAvailableSettings();
                     foreach ($va_settings as $vs_setting => $va_setting_info) {
                         if (isset($_REQUEST['setting_' . $vs_setting])) {
                             $vs_setting_val = $po_request->getParameter('setting_' . $vs_setting, pString);
                             $this->setSetting($vs_setting, $vs_setting_val);
                             $this->update();
                         }
                     }
                     break;
                     # -------------------------------------
                     // This bundle is only available for ca_bundle_displays
                 # -------------------------------------
                 // This bundle is only available for ca_bundle_displays
                 case 'ca_bundle_display_placements':
                     if ($vb_batch) {
                         break;
                     }
                     // not supported in batch mode
                     $this->savePlacementsFromHTMLForm($po_request, $vs_form_prefix, $vs_placement_code);
                     break;
                     # -------------------------------------
                     // This bundle is only available for ca_bundle_displays
                 # -------------------------------------
                 // This bundle is only available for ca_bundle_displays
                 case 'ca_bundle_display_type_restrictions':
                     if ($vb_batch) {
                         break;
                     }
                     // not supported in batch mode
                     $this->saveTypeRestrictionsFromHTMLForm($po_request, $vs_form_prefix, $vs_placement_code);
                     break;
                     # -------------------------------------
                     // This bundle is only available for ca_search_forms
                 # -------------------------------------
                 // This bundle is only available for ca_search_forms
                 case 'ca_search_form_placements':
                     if ($vb_batch) {
                         break;
                     }
                     // not supported in batch mode
                     $this->savePlacementsFromHTMLForm($po_request, $vs_form_prefix, $vs_placement_code);
                     break;
                     # -------------------------------------
                     // This bundle is only available for ca_editor_ui
                 # -------------------------------------
                 // This bundle is only available for ca_editor_ui
                 case 'ca_editor_ui_screens':
                     if ($vb_batch) {
                         break;
                     }
                     // not supported in batch mode
                     global $g_ui_locale_id;
                     require_once __CA_MODELS_DIR__ . '/ca_editor_ui_screens.php';
                     $va_screen_ids = explode(';', $po_request->getParameter("{$vs_placement_code}{$vs_form_prefix}_ScreenBundleList", pString));
                     foreach ($_REQUEST as $vs_key => $vs_val) {
                         if (is_array($vs_val)) {
                             continue;
                         }
                         if (!($vs_val = trim($vs_val))) {
                             continue;
                         }
                         if (preg_match("!^{$vs_placement_code}{$vs_form_prefix}_name_new_([\\d]+)\$!", $vs_key, $va_matches)) {
                             if (!($t_screen = $this->addScreen($vs_val, $g_ui_locale_id, 'screen_' . $this->getPrimaryKey() . '_' . $va_matches[1]))) {
                                 break;
                             }
                             if ($vn_fkey = array_search("new_" . $va_matches[1], $va_screen_ids)) {
                                 $va_screen_ids[$vn_fkey] = $t_screen->getPrimaryKey();
                             } else {
                                 $va_screen_ids[] = $t_screen->getPrimaryKey();
                             }
                             continue;
                         }
                         if (preg_match("!^{$vs_placement_code}{$vs_form_prefix}_([\\d]+)_delete\$!", $vs_key, $va_matches)) {
                             $this->removeScreen($va_matches[1]);
                             if ($vn_fkey = array_search($va_matches[1], $va_screen_ids)) {
                                 unset($va_screen_ids[$vn_fkey]);
                             }
                         }
                     }
                     $this->reorderScreens($va_screen_ids);
                     break;
                     # -------------------------------------
                     // This bundle is only available for ca_editor_ui_screens
                 # -------------------------------------
                 // This bundle is only available for ca_editor_ui_screens
                 case 'ca_editor_ui_bundle_placements':
                     if ($vb_batch) {
                         break;
                     }
                     // not supported in batch mode
                     $this->savePlacementsFromHTMLForm($po_request, $vs_form_prefix, $vs_placement_code);
                     break;
                     # -------------------------------------
                     // This bundle is only available for ca_editor_uis
                 # -------------------------------------
                 // This bundle is only available for ca_editor_uis
                 case 'ca_editor_ui_type_restrictions':
                     if ($vb_batch) {
                         break;
                     }
                     // not supported in batch mode
                     $this->saveTypeRestrictionsFromHTMLForm($po_request, $vs_form_prefix, $vs_placement_code);
                     break;
                     # -------------------------------------
                     // This bundle is only available for ca_editor_ui_screens
                 # -------------------------------------
                 // This bundle is only available for ca_editor_ui_screens
                 case 'ca_editor_ui_screen_type_restrictions':
                     if ($vb_batch) {
                         break;
                     }
                     // not supported in batch mode
                     $this->saveTypeRestrictionsFromHTMLForm($po_request, $vs_form_prefix, $vs_placement_code);
                     break;
                     # -------------------------------------
                     // This bundle is only available for ca_tours
                 # -------------------------------------
                 // This bundle is only available for ca_tours
                 case 'ca_tour_stops_list':
                     if ($vb_batch) {
                         break;
                     }
                     // not supported in batch mode
                     global $g_ui_locale_id;
                     require_once __CA_MODELS_DIR__ . '/ca_tour_stops.php';
                     $va_stop_ids = explode(';', $po_request->getParameter("{$vs_placement_code}{$vs_form_prefix}_StopBundleList", pString));
                     foreach ($_REQUEST as $vs_key => $vs_val) {
                         if (!($vs_val = trim($vs_val))) {
                             continue;
                         }
                         if (preg_match("!^{$vs_placement_code}{$vs_form_prefix}_name_new_([\\d]+)\$!", $vs_key, $va_matches)) {
                             $vn_type_id = $_REQUEST["{$vs_placement_code}{$vs_form_prefix}_type_id_new_" . $va_matches[1]];
                             if (!($t_stop = $this->addStop($vs_val, $vn_type_id, $g_ui_locale_id, mb_substr(preg_replace('![^A-Za-z0-9_]+!', '_', $vs_val), 0, 255)))) {
                                 break;
                             }
                             if ($vn_fkey = array_search("new_" . $va_matches[1], $va_stop_ids)) {
                                 $va_stop_ids[$vn_fkey] = $t_stop->getPrimaryKey();
                             } else {
                                 $va_stop_ids[] = $t_stop->getPrimaryKey();
                             }
                             continue;
                         }
                         if (preg_match("!^{$vs_placement_code}{$vs_form_prefix}_([\\d]+)_delete\$!", $vs_key, $va_matches)) {
                             $this->removeStop($va_matches[1]);
                             if ($vn_fkey = array_search($va_matches[1], $va_stop_ids)) {
                                 unset($va_stop_ids[$vn_fkey]);
                             }
                         }
                     }
                     $this->reorderStops($va_stop_ids);
                     break;
                     # -------------------------------------
                 # -------------------------------------
                 case 'ca_user_groups':
                     if ($vb_batch) {
                         break;
                     }
                     // not supported in batch mode
                     if (!$po_request->user->canDoAction('is_administrator') && $po_request->getUserID() != $this->get('user_id')) {
                         break;
                     }
                     // don't save if user is not owner
                     require_once __CA_MODELS_DIR__ . '/ca_user_groups.php';
                     $va_groups_to_set = $va_group_effective_dates = array();
                     foreach ($_REQUEST as $vs_key => $vs_val) {
                         if (preg_match("!^{$vs_placement_code}{$vs_form_prefix}_id(.*)\$!", $vs_key, $va_matches)) {
                             $vs_effective_date = $po_request->getParameter("{$vs_placement_code}{$vs_form_prefix}_effective_date_" . $va_matches[1], pString);
                             $vn_group_id = (int) $po_request->getParameter("{$vs_placement_code}{$vs_form_prefix}_id" . $va_matches[1], pInteger);
                             $vn_access = $po_request->getParameter("{$vs_placement_code}{$vs_form_prefix}_access_" . $va_matches[1], pInteger);
                             if ($vn_access > 0) {
                                 $va_groups_to_set[$vn_group_id] = $vn_access;
                                 $va_group_effective_dates[$vn_group_id] = $vs_effective_date;
                             }
                         }
                     }
                     $this->setUserGroups($va_groups_to_set, $va_group_effective_dates, array('user_id' => $po_request->getUserID()));
                     break;
                     # -------------------------------------
                 # -------------------------------------
                 case 'ca_users':
                     if ($vb_batch) {
                         break;
                     }
                     // not supported in batch mode
                     if (!$po_request->user->canDoAction('is_administrator') && $po_request->getUserID() != $this->get('user_id')) {
                         break;
                     }
                     // don't save if user is not owner
                     require_once __CA_MODELS_DIR__ . '/ca_users.php';
                     $va_users_to_set = $va_user_effective_dates = array();
                     foreach ($_REQUEST as $vs_key => $vs_val) {
                         if (preg_match("!^{$vs_placement_code}{$vs_form_prefix}_id(.*)\$!", $vs_key, $va_matches)) {
                             $vs_effective_date = $po_request->getParameter("{$vs_placement_code}{$vs_form_prefix}_effective_date_" . $va_matches[1], pString);
                             $vn_user_id = (int) $po_request->getParameter("{$vs_placement_code}{$vs_form_prefix}_id" . $va_matches[1], pInteger);
                             $vn_access = $po_request->getParameter("{$vs_placement_code}{$vs_form_prefix}_access_" . $va_matches[1], pInteger);
                             if ($vn_access > 0) {
                                 $va_users_to_set[$vn_user_id] = $vn_access;
                                 $va_user_effective_dates[$vn_user_id] = $vs_effective_date;
                             }
                         }
                     }
                     $this->setUsers($va_users_to_set, $va_user_effective_dates);
                     break;
                     # -------------------------------------
                 # -------------------------------------
                 case 'settings':
                     if ($vb_batch) {
                         break;
                     }
                     // not supported in batch mode
                     $this->setSettingsFromHTMLForm($po_request, array('id' => $vs_form_prefix . '_', 'placement_code' => $vs_placement_code));
                     break;
                     # -------------------------------
                     // This bundle is only available when editing objects of type ca_object_representations
                 # -------------------------------
                 // This bundle is only available when editing objects of type ca_object_representations
                 case 'ca_object_representations_media_display':
                     if ($vb_batch) {
                         break;
                     }
                     // not supported in batch mode
                     $va_versions_to_process = null;
                     if ($vb_use_options = (bool) $po_request->getParameter("{$vs_placement_code}{$vs_form_prefix}_derivative_options_selector", pInteger)) {
                         // update only specified versions
                         $va_versions_to_process = $po_request->getParameter("{$vs_placement_code}{$vs_form_prefix}_set_versions", pArray);
                     }
                     if (!is_array($va_versions_to_process) || !sizeof($va_versions_to_process)) {
                         $va_versions_to_process = array('_all');
                     }
                     if ($vb_use_options && $po_request->getParameter("{$vs_placement_code}{$vs_form_prefix}_derivative_options_mode", pString) == 'timecode') {
                         // timecode
                         if (!(string) ($vs_timecode = $po_request->getParameter("{$vs_placement_code}{$vs_form_prefix}_derivative_options_mode_timecode_value", pString))) {
                             $vs_timecode = "1s";
                         }
                         //
                         $o_media = new Media();
                         if ($o_media->read($this->getMediaPath('media', 'original'))) {
                             $va_files = $o_media->writePreviews(array('force' => true, 'outputDirectory' => $this->_CONFIG->get("taskqueue_tmp_directory"), 'minNumberOfFrames' => 1, 'maxNumberOfFrames' => 1, 'startAtTime' => $vs_timecode, 'endAtTime' => $vs_timecode, 'width' => 720, 'height' => 540));
                             if (sizeof($va_files)) {
                                 $this->set('media', array_shift($va_files));
                             }
                         }
                     } else {
                         if ($vb_use_options && $po_request->getParameter("{$vs_placement_code}{$vs_form_prefix}_derivative_options_mode", pString) == 'page') {
                             if (!(int) ($vn_page = $po_request->getParameter("{$vs_placement_code}{$vs_form_prefix}_derivative_options_mode_page_value", pInteger))) {
                                 $vn_page = 1;
                             }
                             //
                             $o_media = new Media();
                             if ($o_media->read($this->getMediaPath('media', 'original'))) {
                                 $va_files = $o_media->writePreviews(array('force' => true, 'outputDirectory' => $this->_CONFIG->get("taskqueue_tmp_directory"), 'numberOfPages' => 1, 'startAtPage' => $vn_page, 'width' => 2048, 'height' => 2048));
                                 if (sizeof($va_files)) {
                                     $this->set('media', array_shift($va_files));
                                 }
                             }
                         } else {
                             // process file as new upload
                             $vs_key = "{$vs_placement_code}{$vs_form_prefix}_url";
                             if (($vs_media_url = trim($po_request->getParameter($vs_key, pString))) && isURL($vs_media_url)) {
                                 $this->set('media', $vs_media_url);
                             } else {
                                 $vs_key = "{$vs_placement_code}{$vs_form_prefix}_media";
                                 if (isset($_FILES[$vs_key])) {
                                     $this->set('media', $_FILES[$vs_key]['tmp_name'], array('original_filename' => $_FILES[$vs_key]['name']));
                                 }
                             }
                         }
                     }
                     if ($this->changed('media')) {
                         $this->update($vs_version != '_all' ? array('updateOnlyMediaVersions' => $va_versions_to_process) : array());
                         if ($this->numErrors()) {
                             $po_request->addActionErrors($this->errors(), 'ca_object_representations_media_display', 'general');
                         }
                     }
                     break;
                     # -------------------------------
                     // This bundle is only available when editing objects of type ca_object_representations
                 # -------------------------------
                 // This bundle is only available when editing objects of type ca_object_representations
                 case 'ca_object_representation_captions':
                     if ($vb_batch) {
                         return null;
                     }
                     // not supported in batch mode
                     $va_users_to_set = array();
                     foreach ($_REQUEST as $vs_key => $vs_val) {
                         if (preg_match("!^{$vs_placement_code}{$vs_form_prefix}_locale_id(.*)\$!", $vs_key, $va_matches)) {
                             $vn_locale_id = (int) $po_request->getParameter("{$vs_placement_code}{$vs_form_prefix}_locale_id" . $va_matches[1], pInteger);
                             $this->addCaptionFile($_FILES["{$vs_placement_code}{$vs_form_prefix}_caption_file" . $va_matches[1]]['tmp_name'], $vn_locale_id, array('originalFilename' => $_FILES["{$vs_placement_code}{$vs_form_prefix}_captions_caption_file" . $va_matches[1]]['name']));
                         } else {
                             // any to delete?
                             if (preg_match("!^{$vs_placement_code}{$vs_form_prefix}_([\\d]+)_delete\$!", $vs_key, $va_matches)) {
                                 $this->removeCaptionFile((int) $va_matches[1]);
                             }
                         }
                     }
                     break;
                     # -------------------------------
                     // This bundle is only available for relationships that include an object on one end
                 # -------------------------------
                 // This bundle is only available for relationships that include an object on one end
                 case 'ca_object_representation_chooser':
                     if ($vb_batch) {
                         return null;
                     }
                     // not supported in batch mode
                     if (!is_array($va_rep_ids = $po_request->getParameter("{$vs_placement_code}{$vs_form_prefix}", pArray))) {
                         $va_rep_ids = array();
                     }
                     if ($vs_element_code = caGetOption(array('elementCode', 'element_code'), $va_bundle_settings, null)) {
                         if (!is_array($va_current_rep_ids = $this->get($this->tableName() . "." . $vs_element_code, array('returnAsArray' => true, 'idsOnly' => true)))) {
                             $va_current_rep_ids = $va_current_rep_id_with_structure = array();
                         } else {
                             $va_current_rep_id_with_structure = $this->get($this->tableName() . "." . $vs_element_code, array('returnWithStructure' => true, 'idsOnly' => true));
                         }
                         $va_rep_to_attr_id = array();
                         foreach ($va_rep_ids as $vn_rep_id) {
                             if (in_array($vn_rep_id, $va_current_rep_ids)) {
                                 continue;
                             }
                             $this->addAttribute(array($vs_element_code => $vn_rep_id), $vs_element_code);
                         }
                         foreach ($va_current_rep_id_with_structure as $vn_id => $va_vals_by_attr_id) {
                             foreach ($va_vals_by_attr_id as $vn_attribute_id => $va_val) {
                                 if (!in_array($va_val[$vs_element_code], $va_rep_ids)) {
                                     $this->removeAttribute($vn_attribute_id);
                                 }
                             }
                         }
                         $this->update();
                     }
                     break;
                     # -------------------------------
                     // This bundle is only available for objects
                 # -------------------------------
                 // This bundle is only available for objects
                 case 'ca_objects_location':
                     if ($vb_batch) {
                         return null;
                     }
                     // not supported in batch mode
                     if (!$po_request->user->canDoAction('can_edit_ca_objects')) {
                         break;
                     }
                     if ($vn_location_id = $po_request->getParameter("{$vs_placement_code}{$vs_form_prefix}_location_idnew_0", pInteger)) {
                         if (is_array($va_relationship_types = caGetOption('ca_storage_locations_relationshipType', $va_bundle_settings, null)) && ($vn_relationship_type_id = array_shift($va_relationship_types))) {
                             $this->addRelationship('ca_storage_locations', $vn_location_id, $vn_relationship_type_id, null, null, null, null, array('allowDuplicates' => true));
                             if ($this->numErrors()) {
                                 $po_request->addActionErrors($this->errors(), 'ca_objects_location', 'general');
                             }
                         }
                     }
                     break;
                     # -------------------------------
                     // This bundle is only available for objects
                 # -------------------------------
                 // This bundle is only available for objects
                 case 'ca_objects_history':
                     if ($vb_batch) {
                         return null;
                     }
                     // not supported in batch mode
                     if (!$po_request->user->canDoAction('can_edit_ca_objects')) {
                         break;
                     }
                     // set storage location
                     if ($vn_location_id = $po_request->getParameter("{$vs_placement_code}{$vs_form_prefix}_location_idnew_0", pInteger)) {
                         if (is_array($va_relationship_types = caGetOption('ca_storage_locations_showRelationshipTypes', $va_bundle_settings, null)) && ($vn_relationship_type_id = array_shift($va_relationship_types))) {
                             $this->addRelationship('ca_storage_locations', $vn_location_id, $vn_relationship_type_id, null, null, null, null, array('allowDuplicates' => true));
                             if ($this->numErrors()) {
                                 $po_request->addActionErrors($this->errors(), 'ca_objects_history', 'general');
                             }
                         }
                     }
                     // set loan
                     if ($vn_loan_id = $po_request->getParameter("{$vs_placement_code}{$vs_form_prefix}_loan_idnew_0", pInteger)) {
                         if ($vn_loan_type_id = $po_request->getParameter("{$vs_placement_code}{$vs_form_prefix}_loan_type_idnew_0", pInteger)) {
                             $this->addRelationship('ca_loans', $vn_loan_id, $vn_loan_type_id);
                             if ($this->numErrors()) {
                                 $po_request->addActionErrors($this->errors(), 'ca_objects_history', 'general');
                             }
                         }
                     }
                     break;
                     # -------------------------------
                     // This bundle is only available for objects
                 # -------------------------------
                 // This bundle is only available for objects
                 case 'ca_objects_deaccession':
                     // object deaccession information
                     if (!$vb_batch && !$this->getPrimaryKey()) {
                         return null;
                     }
                     // not supported for new records
                     if (!$po_request->user->canDoAction('can_edit_ca_objects')) {
                         break;
                     }
                     $this->set('is_deaccessioned', $vb_is_deaccessioned = $po_request->getParameter("{$vs_placement_code}{$vs_form_prefix}is_deaccessioned", pInteger));
                     $this->set('deaccession_notes', $po_request->getParameter("{$vs_placement_code}{$vs_form_prefix}deaccession_notes", pString));
                     $this->set('deaccession_type_id', $x = $po_request->getParameter("{$vs_placement_code}{$vs_form_prefix}deaccession_type_id", pString));
                     $this->set('deaccession_date', $po_request->getParameter("{$vs_placement_code}{$vs_form_prefix}deaccession_date", pString));
                     if ($vb_is_deaccessioned && (bool) $this->getAppConfig()->get('deaccession_force_access_private')) {
                         $this->get('access', 0);
                     }
                     // set access to private for accessioned items
                     $this->update();
                     break;
                     # -------------------------------
                     // This bundle is only available for objects
                 # -------------------------------
                 // This bundle is only available for objects
                 case 'ca_object_checkouts':
                     // object checkout information
                     if ($vb_batch) {
                         return null;
                     }
                     // not supported in batch mode
                     if (!$vb_batch && !$this->getPrimaryKey()) {
                         return null;
                     }
                     // not supported for new records
                     if (!$po_request->user->canDoAction('can_edit_ca_objects')) {
                         break;
                     }
                     // NOOP (for now)
                     break;
                     # -------------------------------
             }
         }
     }
     BaseModel::unsetChangeLogUnitID();
     $va_bundle_names = array();
     foreach ($va_bundles as $va_bundle) {
         $vs_bundle_name = str_replace('ca_attribute_', '', $va_bundle['bundle_name']);
         if (!$this->getAppDatamodel()->getInstanceByTableName($vs_bundle_name, true)) {
             $vs_bundle_name = $this->tableName() . '.' . $vs_bundle_name;
         }
         $va_bundle_names[] = $vs_bundle_name;
     }
     // validate metadata dictionary rules
     $va_violations = $this->validateUsingMetadataDictionaryRules(array('bundles' => $va_bundle_names));
     if (sizeof($va_violations)) {
         if ($vb_we_set_transaction && isset($va_violations['ERR']) && is_array($va_violations['ERR']) && sizeof($va_violations['ERR']) > 0) {
             BaseModel::unsetChangeLogUnitID();
             $this->removeTransaction(false);
             $this->_FIELD_VALUES[$this->primaryKey()] = null;
             // clear primary key since transaction has been rolled back
             foreach ($va_violations['ERR'] as $vs_bundle => $va_errs_by_bundle) {
                 foreach ($va_errs_by_bundle as $vn_i => $va_rule) {
                     $vs_bundle = str_replace($this->tableName() . ".", "", $vs_bundle);
                     $po_request->addActionErrors(array(new Error(1100, $va_rule['rule_settings']['violationMessage'], "BundlableLabelableBaseModelWithAttributes->saveBundlesForScreen()", 'MetadataDictionary', false, false)), $vs_bundle, 'general');
                 }
             }
             return false;
         }
     }
     // prepopulate fields
     $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')) {
         $this->prepopulateFields(array('prepopulateConfig' => $vs_prepopulate_cfg));
     }
     if ($vb_dryrun) {
         $this->removeTransaction(false);
     }
     if ($vb_we_set_transaction) {
         $this->removeTransaction(true);
     }
     return true;
 }
Example #24
0
 private function _getMetadataElement($ps_element_code)
 {
     if (isset(WLPlugSearchEngineSolr::$s_element_code_cache[$ps_element_code])) {
         return WLPlugSearchEngineSolr::$s_element_code_cache[$ps_element_code];
     }
     $t_element = new ca_metadata_elements($ps_element_code);
     if (!($vn_element_id = $t_element->getPrimaryKey())) {
         return WLPlugSearchEngineSolr::$s_element_code_cache[$ps_element_code] = null;
     }
     return WLPlugSearchEngineSolr::$s_element_code_cache[$ps_element_code] = array('element_id' => $vn_element_id, 'element_code' => $t_element->get('element_code'), 'datatype' => $t_element->get('datatype'));
 }
Example #25
0
 /**
  * Save edits from "spreadsheet" (editable results) mode
  *
  */
 public function saveInlineEdit($pa_options = null)
 {
     global $g_ui_locale_id;
     $pa_changes = $this->request->getParameter("changes", pArray);
     $vs_resp = array();
     $o_dm = Datamodel::load();
     if (!is_array($pa_changes) || !sizeof($pa_changes)) {
         $va_resp['messages'][0] = _t("Nothing to save");
     } else {
         foreach ($pa_changes as $vn_i => $pa_change) {
             $ps_table = $pa_change['table'];
             $pa_bundle = explode("-", $ps_bundle = $pa_change['bundle']);
             $pn_id = (int) $pa_change['id'];
             $ps_val = $pa_change['value'];
             if (!($t_instance = $o_dm->getInstanceByTableName($ps_table, true))) {
                 $va_resp['errors'][$pn_id] = array('error' => 100, 'message' => _t('Invalid table: %1', $ps_table));
             } else {
                 if (!$t_instance->load($pn_id)) {
                     $va_resp['errors'][$pn_id] = array('error' => 100, 'message' => _t('Invalid id: %1', $pn_id));
                 } else {
                     if (!$t_instance->isSaveable($this->request)) {
                         $va_resp['errors'][$pn_id] = array('error' => 100, 'message' => _t('You are not allowed to edit this.'));
                     } elseif ($pa_bundle[0] == 'preferred_labels') {
                         if ($this->request->user->getBundleAccessLevel($ps_table, $pa_bundle[0]) != __CA_BUNDLE_ACCESS_EDIT__) {
                             $va_resp['errors'][$pn_id] = array('error' => 100, 'message' => _t('You are not allowed to edit this.'));
                         } else {
                             $vn_label_id = $t_instance->getPreferredLabelID($g_ui_locale_id);
                             $va_label_values = array();
                             if (sizeof($pa_bundle) == 1) {
                                 // is generic "preferred_labels"
                                 $va_label_values[$t_instance->getLabelDisplayField()] = $ps_val;
                             } else {
                                 $vs_preferred_label_element = $pa_bundle[1];
                                 $va_label_values[$vs_preferred_label_element] = $ps_val;
                             }
                             if ($vn_label_id) {
                                 $t_instance->editLabel($vn_label_id, $va_label_values, $g_ui_locale_id, null, true);
                                 // TODO: what about type?
                             } else {
                                 $t_instance->addLabel($va_label_values, $g_ui_locale_id, null, true);
                             }
                             if ($t_instance->numErrors()) {
                                 $va_resp['errors'][$pn_id] = array('error' => 100, 'message' => _t('Could not set preferred label %1 to %2: %3', $ps_bundle, $ps_val, join("; ", $t_instance->getErrors())));
                             } else {
                                 $va_resp['messages'][$pn_id] = array('message' => _t('Set preferred label %1 to %2', $ps_bundle, $ps_val), 'value' => $ps_val);
                             }
                         }
                     } elseif ($t_instance->hasField($ps_bundle)) {
                         if ($this->request->user->getBundleAccessLevel($ps_table, $ps_bundle) != __CA_BUNDLE_ACCESS_EDIT__) {
                             $va_resp['errors'][$pn_id] = array('error' => 100, 'message' => _t('You are not allowed to edit this.'));
                         } else {
                             // is it a list?
                             $t_list = new ca_lists();
                             $t_instance->setMode(ACCESS_WRITE);
                             if (($vs_list_code = $t_instance->getFieldInfo($ps_bundle, 'LIST')) && ($va_item = $t_list->getItemFromListByLabel($vs_list_code, $ps_val))) {
                                 $t_instance->set($ps_bundle, $va_item['item_value']);
                             } elseif (($vs_list_code = $t_instance->getFieldInfo($ps_bundle, 'LIST_CODE')) && ($vn_item_id = $t_list->getItemIDFromListByLabel($vs_list_code, $ps_val))) {
                                 $t_instance->set($ps_bundle, $vn_item_id);
                             } else {
                                 $t_instance->set($ps_bundle, $ps_val);
                             }
                             $t_instance->update();
                             if ($t_instance->numErrors()) {
                                 $va_resp['errors'][$pn_id] = array('error' => 100, 'message' => _t('Could not set %1 to %2: %3', $ps_bundle, $ps_val, join("; ", $t_instance->getErrors())));
                             } else {
                                 $va_resp['messages'][$pn_id] = array('message' => _t('Set %1 to %2', $ps_bundle, $ps_val), 'value' => $ps_val);
                             }
                         }
                     } elseif ($t_instance->hasElement($ps_bundle)) {
                         $vn_datatype = ca_metadata_elements::getElementDatatype($ps_bundle);
                         // Check if it repeats?
                         if ($vn_count = $t_instance->getAttributeCountByElement($ps_bundle) > 1) {
                             $va_resp['errors'][$pn_id] = array('error' => 100, 'message' => _t('Cannot edit <em>%1</em> here because it has multiple values. Try editing it directly.', mb_strtolower($t_instance->getDisplayLabel("{$ps_table}.{$ps_bundle}"))));
                         } elseif (!in_array($vn_datatype, array(1, 2, 3, 5, 6, 8, 9, 10, 11, 12))) {
                             // Check if it's a supported type?
                             $va_resp['errors'][$pn_id] = array('error' => 100, 'message' => _t('Cannot edit <em>%1</em> here. Try editing it directly.', mb_strtolower($t_instance->getDisplayLabel("{$ps_table}.{$ps_bundle}"))));
                         } elseif ($this->request->user->getBundleAccessLevel($ps_table, $ps_bundle) != __CA_BUNDLE_ACCESS_EDIT__) {
                             $va_resp['errors'][$pn_id] = array('error' => 100, 'message' => _t('You are not allowed to edit this.'));
                         } else {
                             // Do edit
                             $t_instance->setMode(ACCESS_WRITE);
                             $vs_val_proc = null;
                             if ($vn_datatype == 3) {
                                 if ($vn_id = ca_list_items::find(array('preferred_labels' => array('name_plural' => $ps_val)), array('returnAs' => 'firstId'))) {
                                     $t_instance->replaceAttribute(array('locale_id' => $g_ui_locale_id, $ps_bundle => $vn_id), $ps_bundle);
                                     // convert list codes to display text
                                     $t_list_item = new ca_list_items((int) $vn_id);
                                     if ($t_list_item->getPrimaryKey()) {
                                         $vs_val_proc = $t_list_item->get('ca_list_items.preferred_labels.name_plural');
                                     }
                                 }
                             } else {
                                 $t_instance->replaceAttribute(array('locale_id' => $g_ui_locale_id, $ps_bundle => $ps_val), $ps_bundle);
                             }
                             $t_instance->update();
                             if (!$vs_val_proc) {
                                 $vs_val_proc = $t_instance->get($ps_table . '.' . $ps_bundle);
                             }
                             if ($t_instance->numErrors()) {
                                 $va_resp['errors'][$pn_id] = array('error' => 100, 'message' => _t('Could not set %1 to %2: %3', $ps_bundle, $ps_val, join("; ", $t_instance->getErrors())));
                             } else {
                                 $va_resp['messages'][$pn_id] = array('message' => _t('Set %1 to %2', $ps_bundle, $ps_val), 'value' => $vs_val_proc);
                             }
                         }
                     } else {
                         $va_resp['errors'][$pn_id] = array('error' => 100, 'message' => _t('Invalid bundle: %1', $ps_bundle));
                     }
                 }
             }
         }
     }
     $this->view->setVar('results', $va_resp);
     $this->render('Results/ajax_save_inline_edit_json.php');
 }
Example #26
0
 /** 
  * 
  */
 public function advanced()
 {
     $o_config = caGetSearchConfig();
     $ps_function = strtolower($this->request->getActionExtra());
     if (!($va_search_info = caGetInfoForAdvancedSearchType($ps_function))) {
         // invalid advanced search type – throw error
         die("Invalid advanced search type");
     }
     $vs_class = $va_search_info['table'];
     $va_types = caGetOption('restrictToTypes', $va_search_info, array(), array('castTo' => 'array'));
     $this->opo_result_context = new ResultContext($this->request, $va_search_info['table'], $this->ops_find_type . '_advanced');
     $this->opo_result_context->setAsLastFind();
     MetaTagManager::setWindowTitle($this->request->config->get("app_display_name") . ": " . _t("Search %1", $va_search_info["displayName"]));
     $this->view->setVar('searchInfo', $va_search_info);
     $this->view->setVar('options', caGetOption('options', $va_search_info, array(), array('castTo' => 'array')));
     $va_default_form_values = $this->opo_result_context->getParameter("pawtucketAdvancedSearchFormContent_{$ps_function}");
     $va_default_form_booleans = $this->opo_result_context->getParameter("pawtucketAdvancedSearchFormBooleans_{$ps_function}");
     $va_tags = $this->view->getTagList($va_search_info['view']);
     $t_subject = $this->request->datamodel->getInstanceByTableName($va_search_info['table'], true);
     $va_form_elements = array();
     $vs_script = null;
     foreach ($va_tags as $vs_tag) {
         $va_parse = caParseTagOptions($vs_tag);
         $vs_tag_proc = $va_parse['tag'];
         $va_opts = $va_parse['options'];
         if (($vs_default_value = caGetOption('default', $va_opts, null)) || ($vs_default_value = caGetOption($vs_tag_proc, $va_default_form_values, null))) {
             $va_default_form_values[$vs_tag_proc] = $vs_default_value;
             unset($va_opts['default']);
         }
         $vs_tag_val = null;
         switch (strtolower($vs_tag_proc)) {
             case 'submit':
                 $this->view->setVar($vs_tag, "<a href='#' class='caAdvancedSearchFormSubmit'>" . (isset($va_opts['label']) && $va_opts['label'] ? $va_opts['label'] : _t('Submit')) . "</a>");
                 break;
             case 'reset':
                 $this->view->setVar($vs_tag, "<a href='#' class='caAdvancedSearchFormReset'>" . (isset($va_opts['label']) && $va_opts['label'] ? $va_opts['label'] : _t('Reset')) . "</a>");
                 $vs_script = "<script type='text/javascript'>\n\tjQuery('.caAdvancedSearchFormSubmit').bind('click', function() {\n\t\tjQuery('#caAdvancedSearch').submit();\n\t\treturn false;\n\t});\n\tjQuery('.caAdvancedSearchFormReset').bind('click', function() {\n\t\tjQuery('#caAdvancedSearch').find('input[type!=\"hidden\"],textarea').val('');\n\t\tjQuery('#caAdvancedSearch').find('select.caAdvancedSearchBoolean').val('AND');\n\t\tjQuery('#caAdvancedSearch').find('select').prop('selectedIndex', 0);\n\t\treturn false;\n\t});\n\tjQuery(document).ready(function() {\n\t\tvar f, defaultValues = " . json_encode($va_default_form_values) . ", defaultBooleans = " . json_encode($va_default_form_booleans) . ";\n\t\tfor (f in defaultValues) {\n\t\t\tvar f_proc = f + '[]';\n\t\t\tjQuery('input[name=\"' + f_proc+ '\"], textarea[name=\"' + f_proc+ '\"], select[name=\"' + f_proc+ '\"]').each(function(k, v) {\n\t\t\t\tif (defaultValues[f][k]) { jQuery(v).val(defaultValues[f][k]); } \n\t\t\t});\n\t\t}\n\t\tfor (f in defaultBooleans) {\n\t\t\tvar f_proc = f + '[]';\n\t\t\tjQuery('select[name=\"' + f_proc+ '\"].caAdvancedSearchBoolean').each(function(k, v) {\n\t\t\t\tif (defaultBooleans[f][k]) { jQuery(v).val(defaultBooleans[f][k]); }\n\t\t\t});\n\t\t}\n\t});\n</script>\n";
                 break;
             default:
                 if (preg_match("!^(.*):label\$!", $vs_tag_proc, $va_matches)) {
                     $this->view->setVar($vs_tag, $vs_tag_val = $t_subject->getDisplayLabel($va_matches[1]));
                 } elseif (preg_match("!^(.*):boolean\$!", $vs_tag_proc, $va_matches)) {
                     $this->view->setVar($vs_tag, caHTMLSelect($vs_tag_proc . '[]', array(_t('AND') => 'AND', _t('OR') => 'OR', 'AND NOT' => 'AND NOT'), array('class' => 'caAdvancedSearchBoolean')));
                 } else {
                     $va_opts['asArrayElement'] = true;
                     if (isset($va_opts['restrictToTypes']) && $va_opts['restrictToTypes'] && !is_array($va_opts['restrictToTypes'])) {
                         $va_opts['restrictToTypes'] = explode(";", $va_opts['restrictToTypes']);
                     }
                     if ($vs_tag_val = $t_subject->htmlFormElementForSearch($this->request, $vs_tag_proc, $va_opts)) {
                         $this->view->setVar($vs_tag, $vs_tag_val);
                     }
                     $va_tmp = explode('.', $vs_tag_proc);
                     if (($t_element = ca_metadata_elements::getInstance($va_tmp[1])) && $t_element->get('datatype') == 0) {
                         if (is_array($va_elements = $t_element->getElementsInSet())) {
                             foreach ($va_elements as $va_element) {
                                 if ($va_element['datatype'] > 0) {
                                     $va_form_elements[] = $va_tmp[0] . '.' . $va_tmp[1] . '.' . $va_element['element_code'];
                                 }
                             }
                         }
                         break;
                     }
                 }
                 if ($vs_tag_val) {
                     $va_form_elements[] = $vs_tag_proc;
                 }
                 break;
         }
     }
     $this->view->setVar("form", caFormTag($this->request, "{$ps_function}", 'caAdvancedSearch', null, 'post', 'multipart/form-data', '_top', array('disableUnsavedChangesWarning' => true, 'submitOnReturn' => true)));
     $this->view->setVar("/form", $vs_script . caHTMLHiddenInput("_advancedFormName", array("value" => $ps_function)) . caHTMLHiddenInput("_formElements", array("value" => join(';', $va_form_elements))) . caHTMLHiddenInput("_advanced", array("value" => 1)) . "</form>");
     $this->render($va_search_info['view']);
 }
$va_facet = $this->getVar('facet');
$vs_facet_name = $this->getVar('facet_name');
$va_facet_info = $this->getVar('facet_info');
$va_types = $this->getVar('type_list');
$va_relationship_types = $this->getVar('relationship_type_list');
if (!is_array($va_other_params = $this->getVar('other_parameters'))) {
    $va_other_params = array();
}
$vs_grouping_field = $this->getVar('grouping');
if ((!isset($va_facet_info['groupings'][$vs_grouping_field]) || !$va_facet_info['groupings'][$vs_grouping_field]) && is_array($va_facet_info['groupings'])) {
    $va_tmp = array_keys($va_facet_info['groupings']);
    $vs_grouping_field = $va_tmp[0];
}
$vn_element_datatype = null;
if ($vs_grouping_attribute_element_code = preg_match('!^ca_attribute_([\\w]+)!', $vs_grouping_field, $va_matches) ? $va_matches[1] : null) {
    $t_element = new ca_metadata_elements();
    $t_element->load(array('element_code' => $vs_grouping_attribute_element_code));
    $vn_grouping_attribute_id = $t_element->getPrimaryKey();
    $vn_element_datatype = $t_element->get('datatype');
}
$vs_group_mode = $this->getVar('group_mode');
if (!$va_facet || !$vs_facet_name) {
    print 'No facet defined';
    return;
}
if (!($vm_modify_id = $this->getVar('modify'))) {
    $vm_modify_id = '0';
}
?>
<div id="facetList">
<div id="facetTitle">
Example #28
0
 private static function getElementType($pa_element_info)
 {
     $va_table_fields = $va_element_opts = array();
     $vn_element_id = $pa_element_info['element_id'];
     switch ($pa_element_info['datatype']) {
         case 0:
             //container
             /* Retrieve child elements of the container. */
             $t_element = new ca_metadata_elements((int) $pa_element_info['element_id']);
             if ($t_element->getPrimaryKey()) {
                 $va_children = $t_element->getElementsInSet();
                 foreach ($va_children as $va_child) {
                     if ($va_child['element_id'] == $vn_element_id) {
                         continue;
                     }
                     $va_table_fields += SolrConfiguration::getElementType($va_child);
                 }
             }
             break;
         case 1:
             // text
         // text
         case 3:
             // list
         // list
         case 5:
             // url
         // url
         case 6:
             // currency
         // currency
         case 8:
             // length
         // length
         case 9:
             // weight
         // weight
         case 13:
             // LCSH
         // LCSH
         case 14:
             // geonames
         // geonames
         case 15:
             // file
         // file
         case 16:
             // media
         // media
         case 19:
             // taxonomy
         // taxonomy
         case 20:
             // information service
             $va_element_opts['type'] = 'text';
             break;
         case 2:
             // daterange
             $va_element_opts['type'] = 'daterange';
             $va_table_fields['_ca_attribute_' . $vn_element_id . '_text'] = array('type' => 'text');
             break;
         case 4:
             // geocode
             $va_element_opts['type'] = 'geocode';
             $va_table_fields['_ca_attribute_' . $vn_element_id . '_text'] = array('type' => 'text');
             break;
         case 10:
             // timecode
         // timecode
         case 12:
             // numeric/float
             $va_element_opts['type'] = 'float';
             break;
         case 11:
             // integer
             $va_element_opts['type'] = 'int';
             break;
         default:
             $va_element_opts['type'] = 'text';
             break;
     }
     $va_table_fields['_ca_attribute_' . $vn_element_id] = $va_element_opts;
     return $va_table_fields;
 }
Example #29
0
 /**
  * Returns the names of the datatypes for a given list of metadata elements
  * 
  * @param array $element_codes List of codes of the elements in question
  * @return array Names of the datatypes, e.g. "List", "Text", etc.
  */
 public function getElementTypesForCodes($element_codes)
 {
     $vo_db = new Db();
     if (!is_array($element_codes)) {
         throw new SoapFault("Server", "Invalid argument");
     }
     $va_return = array();
     foreach ($element_codes as $vs_element_code) {
         $qr_elements = $vo_db->query("SELECT datatype FROM ca_metadata_elements WHERE element_code=?", $vs_element_code);
         while ($qr_elements->nextRow()) {
             $va_return[$vs_element_code] = ca_metadata_elements::getAttributeNameForTypeCode(intval($qr_elements->get("datatype")));
         }
     }
     return $va_return;
 }
Example #30
0
 /**
  * Returns HTML form element for editing of setting
  *
  * Options:
  *
  * 	'name' => sets the name of the HTML form element explicitly, otherwise 'setting_<name_of_setting>' is used
  * 	'id' => sets the id of the HTML form element explicitly, otherwise 'setting_<name_of_setting>' is used
  *  'value' => sets the value of the HTML form element explicitly, otherwise the current value for the setting in the loaded row is used
  *  'label_id' => sets the id of the label for the setting form element (used to link tools tips to the label); if not set then the default is to set it to  'setting_<name_of_setting>_label'
  */
 public function settingHTMLFormElement($ps_setting, $pa_options = null)
 {
     if (!$this->isValidSetting($ps_setting)) {
         return false;
     }
     $va_available_settings = $this->getAvailableSettings();
     $va_properties = $va_available_settings[$ps_setting];
     if (isset($pa_options['name'])) {
         $vs_input_name = $pa_options['name'];
     } else {
         $vs_input_name = "setting_{$ps_setting}";
     }
     if (isset($pa_options['id'])) {
         $vs_input_id = $pa_options['id'];
     } else {
         $vs_input_id = "setting_{$ps_setting}";
     }
     if (isset($pa_options['value'])) {
         $vs_value = $pa_options['value'];
     } else {
         $vs_value = $this->getSetting(trim($ps_setting));
     }
     if (isset($pa_options['label_id'])) {
         $vs_label_id = $pa_options['label_id'];
     } else {
         $vs_label_id = "setting_{$ps_setting}_label";
     }
     $vs_return = "\n" . '<div class="formLabel" id="' . $vs_input_id . '_container">' . "\n";
     $vs_return .= '<span id="' . $vs_label_id . '"  class="' . $vs_label_id . '">' . $va_properties['label'] . '</span>';
     if ($vs_help_text = $pa_options['helpText']) {
         $vs_return .= "<a href='#' onclick='jQuery(\"#" . str_replace(".", "_", $vs_label_id) . "_help_text\").slideToggle(250); return false;' class='settingsKeyButton'>" . _t('Key') . "</a>";
     }
     $vs_return .= '<br />' . "\n";
     if ($vs_help_text) {
         $vs_return .= "\n<div id='" . str_replace(".", "_", $vs_label_id) . "_help_text' class='settingsKey'>{$vs_help_text}</div>\n";
     }
     switch ($va_properties['displayType']) {
         # --------------------------------------------
         case DT_FIELD:
             $vb_takes_locale = false;
             if (isset($va_properties['takesLocale']) && $va_properties['takesLocale']) {
                 $vb_takes_locale = true;
                 $va_locales = ca_locales::getLocaleList(array('sort_field' => '', 'sort_order' => 'asc', 'index_by_code' => true, 'available_for_cataloguing_only' => true));
             } else {
                 $va_locales = array('_generic' => array());
             }
             foreach ($va_locales as $vs_locale => $va_locale_info) {
                 if ($vb_takes_locale && sizeof($va_locales) > 1) {
                     $vs_locale_label = " (" . $va_locale_info['name'] . ")";
                     $vs_input_name_suffix = '_' . $vs_locale;
                 } else {
                     if ($vb_takes_locale) {
                         $vs_input_name_suffix = '_' . $vs_locale;
                     } else {
                         $vs_input_name_suffix = $vs_locale_label = '';
                     }
                 }
                 if ($vs_locale != '_generic' && is_array($vs_value)) {
                     // _generic means this setting doesn't take a locale
                     if (!($vs_text_value = $vs_value[$va_locale_info['locale_id']])) {
                         $vs_text_value = is_array($vs_value) && isset($vs_value[$va_locale_info['code']]) ? $vs_value[$va_locale_info['code']] : '';
                     }
                 } else {
                     $vs_text_value = $vs_value;
                 }
                 $vs_return .= caHTMLTextInput($vs_input_name . $vs_input_name_suffix, array('size' => $va_properties["width"], 'height' => $va_properties["height"], 'value' => $vs_text_value, 'id' => $vs_input_id)) . "{$vs_locale_label}<br/>\n";
             }
             break;
             # --------------------------------------------
         # --------------------------------------------
         case DT_CHECKBOXES:
             $va_attributes = array('value' => '1', 'id' => $vs_input_id);
             if ((int) $vs_value === 1) {
                 $va_attributes['checked'] = '1';
             }
             if (isset($va_properties['hideOnSelect'])) {
                 if (!is_array($va_properties['hideOnSelect'])) {
                     $va_properties['hideOnSelect'] = array($va_properties['hideOnSelect']);
                 }
                 $va_ids = array();
                 foreach ($va_properties['hideOnSelect'] as $vs_n) {
                     $va_ids[] = "#" . $pa_options['id_prefix'] . "_{$vs_n}_container";
                 }
                 $va_attributes['onchange'] = 'jQuery(this).prop("checked") ? jQuery("' . join(",", $va_ids) . '").slideUp(250).find("input, textarea").val("") : jQuery("' . join(",", $va_ids) . '").slideDown(250);';
             }
             $vs_return .= caHTMLCheckboxInput($vs_input_name, $va_attributes, array());
             break;
             # --------------------------------------------
         # --------------------------------------------
         case DT_COLORPICKER:
             $va_attributes = array('value' => $vs_value, 'id' => $vs_input_id);
             $vs_return .= caHTMLHiddenInput($vs_input_name, $va_attributes, array());
             $vs_return .= "<div id='{$vs_input_id}_colorchip' class='colorpicker_chip' style='background-color: #{$vs_value}'><!-- empty --></div>";
             $vs_return .= "<script type='text/javascript'>jQuery(document).ready(function() { jQuery('#{$vs_input_name}_colorchip').ColorPicker({\n\t\t\t\t\t\t\t\tonShow: function (colpkr) {\n\t\t\t\t\t\t\t\t\tjQuery(colpkr).fadeIn(500);\n\t\t\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\tonHide: function (colpkr) {\n\t\t\t\t\t\t\t\t\tjQuery(colpkr).fadeOut(500);\n\t\t\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\tonChange: function (hsb, hex, rgb) {\n\t\t\t\t\t\t\t\t\tjQuery('#{$vs_input_name}').val(hex);\n\t\t\t\t\t\t\t\t\tjQuery('#{$vs_input_name}_colorchip').css('backgroundColor', '#' + hex);\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\tcolor: jQuery('#" . $pa_options["name"] . "').val()\n\t\t\t\t\t\t\t})}); </script>\n";
             JavascriptLoadManager::register('jquery', 'colorpicker');
             break;
             # --------------------------------------------
         # --------------------------------------------
         case DT_SELECT:
             include_once __CA_MODELS_DIR__ . '/ca_relationship_types.php';
             $vn_width = isset($va_properties['width']) && strlen($va_properties['width']) > 0 ? $va_properties['width'] : "100px";
             $vn_height = isset($va_properties['height']) && strlen($va_properties['height']) > 0 ? $va_properties['height'] : "50px";
             $vs_select_element = '';
             if (($vs_rel_table = $va_properties['useRelationshipTypeList']) || ($vb_locale_list = (bool) $va_properties['useLocaleList']) || ($vs_list_code = $va_properties['useList']) || ($vb_show_lists = (bool) $va_properties['showLists'] || (bool) $va_properties['showVocabularies'])) {
                 if ($vs_rel_table) {
                     $t_rel = new ca_relationship_types();
                     $va_rels = $t_rel->getRelationshipInfo($vs_rel_table);
                     $va_rel_opts = array();
                     if (isset($va_properties['allowNull']) && $va_properties['allowNull']) {
                         $va_rel_opts['-'] = null;
                     }
                     foreach ($va_rels as $vn_type_id => $va_rel_type_info) {
                         if (!$va_rel_type_info['parent_id']) {
                             continue;
                         }
                         $va_rel_opts[$va_rel_type_info['typename'] . '/' . $va_rel_type_info['typename_reverse']] = $va_rel_type_info['type_id'];
                     }
                 } else {
                     if ($vb_locale_list) {
                         include_once __CA_MODELS_DIR__ . '/ca_locales.php';
                         $va_rel_opts = array_flip(ca_locales::getLocaleList(array('return_display_values' => true)));
                     } else {
                         if ($vb_show_lists) {
                             include_once __CA_MODELS_DIR__ . '/ca_lists.php';
                             $t_list = new ca_lists();
                             $va_lists = caExtractValuesByUserLocale($t_list->getListOfLists());
                             $va_rel_opts = array();
                             foreach ($va_lists as $vn_list_id => $va_list_info) {
                                 if ($va_properties['showVocabularies'] && !$va_list_info['use_as_vocabulary']) {
                                     continue;
                                 }
                                 $va_rel_opts[$va_list_info['name'] . ' (' . $va_list_info['list_code'] . ')'] = $vn_list_id;
                             }
                         }
                     }
                 }
                 $va_attr = array();
                 if ($vn_height > 1) {
                     $va_attr['multiple'] = 1;
                     $vs_input_name .= '[]';
                 }
                 $va_opts = array('id' => $vs_input_id, 'width' => $vn_width, 'height' => $vn_height);
                 if ($vn_height > 1) {
                     if ($vs_value && !is_array($vs_value)) {
                         $vs_value = array($vs_value);
                     }
                     $va_opts['values'] = $vs_value;
                 } else {
                     if (is_array($vs_value)) {
                         $va_opts['value'] = array_pop($vs_value);
                     } else {
                         if ($vs_value) {
                             $va_opts['value'] = $vs_value;
                         } else {
                             $va_opts['value'] = null;
                         }
                     }
                 }
                 if ($vs_list_code) {
                     $t_list = new ca_lists();
                     if (!isset($va_opts['value'])) {
                         $va_opts['value'] = -1;
                     }
                     // make sure default list item is never selected
                     $vs_select_element = $t_list->getListAsHTMLFormElement($vs_list_code, $vs_input_name, $va_attr, $va_opts);
                 } else {
                     if (!isset($va_opts['value'])) {
                         $va_opts['value'] = -1;
                     }
                     // make sure default list item is never selected
                     $vs_select_element = caHTMLSelect($vs_input_name, $va_rel_opts, $va_attr, $va_opts);
                 }
             } else {
                 if (strlen($va_properties['showSortableBundlesFor']) > 0) {
                     require_once __CA_MODELS_DIR__ . '/ca_metadata_elements.php';
                     $o_dm = Datamodel::load();
                     if (!($t_rel = $o_dm->getInstanceByTableName($va_properties['showSortableBundlesFor'], true))) {
                         break;
                     }
                     $va_elements = ca_metadata_elements::getSortableElements($va_properties['showSortableBundlesFor']);
                     $va_select_opts = array(_t('User defined sort order') => '', _t('Order created') => 'relation_id', _t('Preferred label') => $va_properties['showSortableBundlesFor'] . ".preferred_labels." . $t_rel->getLabelDisplayField());
                     foreach ($va_elements as $vn_element_id => $va_element) {
                         if (!$va_element['display_label']) {
                             continue;
                         }
                         $va_select_opts[_t('Element: %1', $va_element['display_label'])] = $va_properties['showSortableBundlesFor'] . "." . $va_element['element_code'];
                     }
                     $va_opts = array('id' => $vs_input_id, 'width' => $vn_width, 'height' => $vn_height, 'value' => is_array($vs_value) ? $vs_value[0] : $vs_value, 'values' => is_array($vs_value) ? $vs_value : array($vs_value));
                     $vs_select_element = caHTMLSelect($vs_input_name, $va_select_opts, array(), $va_opts);
                 } elseif ((int) $va_properties['showSortableElementsFor'] > 0) {
                     require_once __CA_MODELS_DIR__ . '/ca_metadata_elements.php';
                     $t_element = new ca_metadata_elements($va_properties['showSortableElementsFor']);
                     if (!$t_element->getPrimaryKey()) {
                         return '';
                     }
                     $va_elements = $t_element->getElementsInSet();
                     $va_select_opts = array(_t('Order created') => '');
                     foreach ($va_elements as $vn_i => $va_element) {
                         if ((int) $va_element['element_id'] == (int) $va_properties['showSortableElementsFor']) {
                             continue;
                         }
                         if (!$va_element['display_label']) {
                             continue;
                         }
                         $va_select_opts[_t('Element: %1', $va_element['display_label'])] = $va_element['element_code'];
                     }
                     $va_opts = array('id' => $vs_input_id, 'width' => $vn_width, 'height' => $vn_height, 'value' => is_array($vs_value) ? $vs_value[0] : $vs_value, 'values' => is_array($vs_value) ? $vs_value : array($vs_value));
                     $vs_select_element = caHTMLSelect($vs_input_name, $va_select_opts, array(), $va_opts);
                 } elseif ((int) $va_properties['showMetadataElementsWithDataType'] > 0) {
                     require_once __CA_MODELS_DIR__ . '/ca_metadata_elements.php';
                     $va_rep_elements = ca_metadata_elements::getElementsAsList(true, $va_properties['table'], null, true, false, true, array($va_properties['showMetadataElementsWithDataType']));
                     if (is_array($va_rep_elements)) {
                         $va_select_opts = array();
                         foreach ($va_rep_elements as $vs_element_code => $va_element_info) {
                             $va_select_opts[$va_element_info['display_label']] = $vs_element_code;
                         }
                         $va_opts = array('id' => $vs_input_id, 'width' => $vn_width, 'height' => $vn_height, 'value' => is_array($vs_value) ? $vs_value[0] : $vs_value, 'values' => is_array($vs_value) ? $vs_value : array($vs_value));
                         $vs_select_element = caHTMLSelect($vs_input_name, $va_select_opts, array(), $va_opts);
                     }
                 } else {
                     // Regular drop-down with configured options
                     if ($vn_height > 1) {
                         $va_attr['multiple'] = 1;
                         $vs_input_name .= '[]';
                     }
                     $va_opts = array('id' => $vs_input_id, 'width' => $vn_width, 'height' => $vn_height, 'value' => is_array($vs_value) ? $vs_value[0] : $vs_value, 'values' => is_array($vs_value) ? $vs_value : array($vs_value));
                     if (!isset($va_opts['value'])) {
                         $va_opts['value'] = -1;
                     }
                     // make sure default list item is never selected
                     $vs_select_element = caHTMLSelect($vs_input_name, $va_properties['options'], array(), $va_opts);
                 }
             }
             if ($vs_select_element) {
                 $vs_return .= $vs_select_element;
             } else {
                 return '';
             }
             break;
             # --------------------------------------------
         # --------------------------------------------
         default:
             break;
             # --------------------------------------------
     }
     $vs_return .= '</div>' . "\n";
     TooltipManager::add('.' . $vs_label_id, "<h3>" . $va_properties["label"] . "</h3>" . $va_properties["description"]);
     return $vs_return;
 }