/**
  *  Returns or Creates a list item or list item id matching the parameters and options provided
  * @param string/int $pm_list_code_or_id
  * @param string $ps_item_idno
  * @param string/int $pn_type_id
  * @param int $pn_locale_id
  * @param null/array $pa_values
  * @param array $pa_options An optional array of options. See DataMigrationUtils::_getID() for a list.
  * @return bool|ca_list_items|mixed|null
  *
  * @see DataMigrationUtils::_getID()
  */
 static function getListItemID($pm_list_code_or_id, $ps_item_idno, $pn_type_id, $pn_locale_id, $pa_values = null, $pa_options = null)
 {
     if (!is_array($pa_options)) {
         $pa_options = array();
     }
     $pb_output_errors = caGetOption('outputErrors', $pa_options, false);
     $pa_match_on = caGetOption('matchOn', $pa_options, array('label', 'idno'), array('castTo' => "array"));
     $vn_parent_id = caGetOption('parent_id', $pa_values, false);
     $vs_singular_label = isset($pa_values['preferred_labels']['name_singular']) && $pa_values['preferred_labels']['name_singular'] ? $pa_values['preferred_labels']['name_singular'] : '';
     if (!$vs_singular_label) {
         $vs_singular_label = isset($pa_values['name_singular']) && $pa_values['name_singular'] ? $pa_values['name_singular'] : str_replace("_", " ", $ps_item_idno);
     }
     $vs_plural_label = isset($pa_values['preferred_labels']['name_plural']) && $pa_values['preferred_labels']['name_plural'] ? $pa_values['preferred_labels']['name_plural'] : '';
     if (!$vs_plural_label) {
         $vs_plural_label = isset($pa_values['name_plural']) && $pa_values['name_plural'] ? $pa_values['name_plural'] : str_replace("_", " ", $ps_item_idno);
     }
     if (!$vs_singular_label) {
         $vs_singular_label = $vs_plural_label;
     }
     if (!$vs_plural_label) {
         $vs_plural_label = $vs_singular_label;
     }
     if (!$ps_item_idno) {
         $ps_item_idno = $vs_plural_label;
     }
     if (!isset($pa_options['cache'])) {
         $pa_options['cache'] = true;
     }
     // Create cache key
     $vs_cache_key = md5($pm_list_code_or_id . '/' . $ps_item_idno . '/' . $vn_parent_id . '/' . $vs_singular_label . '/' . $vs_plural_label . '/' . json_encode($pa_match_on));
     $o_event = isset($pa_options['importEvent']) && $pa_options['importEvent'] instanceof ca_data_import_events ? $pa_options['importEvent'] : null;
     $ps_event_source = isset($pa_options['importEventSource']) && $pa_options['importEventSource'] ? $pa_options['importEventSource'] : "?";
     /** @var KLogger $o_log */
     $o_log = isset($pa_options['log']) && $pa_options['log'] instanceof KLogger ? $pa_options['log'] : null;
     if ($pa_options['cache'] && isset(DataMigrationUtils::$s_cached_list_item_ids[$vs_cache_key])) {
         if (isset($pa_options['returnInstance']) && $pa_options['returnInstance']) {
             $t_item = new ca_list_items(DataMigrationUtils::$s_cached_list_item_ids[$vs_cache_key]);
             if (isset($pa_options['transaction']) && $pa_options['transaction'] instanceof Transaction) {
                 $t_item->setTransaction($pa_options['transaction']);
             }
             return $t_item;
         }
         if ($o_event) {
             $o_event->beginItem($ps_event_source, 'ca_list_items', 'U');
             $o_event->endItem(DataMigrationUtils::$s_cached_list_item_ids[$vs_cache_key], __CA_DATA_IMPORT_ITEM_SUCCESS__, '');
         }
         if ($o_log) {
             $o_log->logDebug(_t("Found existing list item %1 (member of list %2) in DataMigrationUtils::getListItemID() using idno", $ps_item_idno, $pm_list_code_or_id));
         }
         return DataMigrationUtils::$s_cached_list_item_ids[$vs_cache_key];
     }
     if (!($vn_list_id = ca_lists::getListID($pm_list_code_or_id))) {
         if ($pb_output_errors) {
             print "[Error] " . _t("Could not find list with list code %1", $pm_list_code_or_id) . "\n";
         }
         if ($o_log) {
             $o_log->logError(_t("Could not find list with list code %1", $pm_list_code_or_id));
         }
         return DataMigrationUtils::$s_cached_list_item_ids[$vs_cache_key] = null;
     }
     if (!$vn_parent_id && $vn_parent_id !== false) {
         $vn_parent_id = caGetListRootID($pm_list_code_or_id);
     }
     $t_list = new ca_lists();
     $t_item = new ca_list_items();
     if (isset($pa_options['transaction']) && $pa_options['transaction'] instanceof Transaction) {
         $t_list->setTransaction($pa_options['transaction']);
         $t_item->setTransaction($pa_options['transaction']);
         if ($o_event) {
             $o_event->setTransaction($pa_options['transaction']);
         }
     }
     $vn_item_id = null;
     foreach ($pa_match_on as $vs_match_on) {
         switch (strtolower($vs_match_on)) {
             case 'label':
             case 'labels':
                 if (trim($vs_singular_label) || trim($vs_plural_label)) {
                     $va_criteria = array('preferred_labels' => array('name_singular' => $vs_singular_label), 'list_id' => $vn_list_id);
                     if ($vn_parent_id !== false) {
                         $va_criteria['parent_id'] = $vn_parent_id;
                     }
                     if ($vn_item_id = ca_list_items::find($va_criteria, array('returnAs' => 'firstId', 'purifyWithFallback' => true, 'transaction' => $pa_options['transaction']))) {
                         if ($o_log) {
                             $o_log->logDebug(_t("Found existing list item %1 (member of list %2) in DataMigrationUtils::getListItemID() using singular label %3", $ps_item_idno, $pm_list_code_or_id, $vs_singular_label));
                         }
                         break 2;
                     } else {
                         $va_criteria['preferred_labels'] = array('name_plural' => $vs_plural_label);
                         if ($vn_item_id = ca_list_items::find($va_criteria, array('returnAs' => 'firstId', 'purifyWithFallback' => true, 'transaction' => $pa_options['transaction']))) {
                             if ($o_log) {
                                 $o_log->logDebug(_t("Found existing list item %1 (member of list %2) in DataMigrationUtils::getListItemID() using plural label %3", $ps_item_idno, $pm_list_code_or_id, $vs_plural_label));
                             }
                             break 2;
                         }
                     }
                     break;
                 }
             case 'idno':
                 if ($ps_item_idno == '%') {
                     break;
                 }
                 // don't try to match on an unreplaced idno placeholder
                 $va_criteria = array('idno' => $ps_item_idno ? $ps_item_idno : $vs_plural_label, 'list_id' => $vn_list_id);
                 if ($vn_parent_id !== false) {
                     $va_criteria['parent_id'] = $vn_parent_id;
                 }
                 if ($vn_item_id = ca_list_items::find($va_criteria, array('returnAs' => 'firstId', 'purifyWithFallback' => true, 'transaction' => $pa_options['transaction']))) {
                     if ($o_log) {
                         $o_log->logDebug(_t("Found existing list item %1 (member of list %2) in DataMigrationUtils::getListItemID() using idno with %3", $ps_item_idno, $pm_list_code_or_id, $ps_item_idno));
                     }
                     break 2;
                 }
                 break;
         }
     }
     if ($vn_item_id) {
         DataMigrationUtils::$s_cached_list_item_ids[$vs_cache_key] = $vn_item_id;
         if ($o_event) {
             $o_event->beginItem($ps_event_source, 'ca_list_items', 'U');
             $o_event->endItem($vn_item_id, __CA_DATA_IMPORT_ITEM_SUCCESS__, '');
         }
         if (($vb_force_update = caGetOption('forceUpdate', $pa_options, false)) || ($vb_return_instance = caGetOption('returnInstance', $pa_options, false))) {
             $vb_has_attr = false;
             if ($vb_force_update) {
                 foreach ($pa_values as $vs_element => $va_values) {
                     if ($t_item->hasElement($vs_element)) {
                         $vb_has_attr = true;
                         break;
                     }
                 }
             }
             if ($vb_return_instance || $vb_force_update && $vb_has_attr) {
                 $t_item = new ca_list_items($vn_item_id);
                 if (isset($pa_options['transaction']) && $pa_options['transaction'] instanceof Transaction) {
                     $t_item->setTransaction($pa_options['transaction']);
                 }
             }
             $vb_attr_errors = false;
             if ($vb_force_update && $vb_has_attr) {
                 $vb_attr_errors = !DataMigrationUtils::_setAttributes($t_item, $pn_locale_id, $pa_values, $pa_options);
             }
             if ($o_event) {
                 if ($vb_attr_errors) {
                     $o_event->endItem($vn_item_id, __CA_DATA_IMPORT_ITEM_PARTIAL_SUCCESS__, _t("Errors setting field values: %1", join('; ', $t_item->getErrors())));
                 } else {
                     $o_event->endItem($vn_item_id, __CA_DATA_IMPORT_ITEM_SUCCESS__, '');
                 }
             }
             if ($vb_return_instance) {
                 return $t_item;
             }
         }
         return $vn_item_id;
     }
     if (isset($pa_options['dontCreate']) && $pa_options['dontCreate']) {
         return false;
     }
     //
     // Need to create list item
     //
     if (!$t_list->load($vn_list_id)) {
         if ($o_log) {
             $o_log->logError(_t("Could not find list with list id %1", $vn_list_id));
         }
         return null;
     }
     if ($o_event) {
         $o_event->beginItem($ps_event_source, 'ca_list_items', 'I');
     }
     if ($t_item = $t_list->addItem($ps_item_idno, $pa_values['is_enabled'], $pa_values['is_default'], $vn_parent_id, $pn_type_id, $ps_item_idno, '', (int) $pa_values['status'], (int) $pa_values['access'], $pa_values['rank'])) {
         $vb_label_errors = false;
         $t_item->addLabel(array('name_singular' => $vs_singular_label, 'name_plural' => $vs_plural_label), $pn_locale_id, null, true);
         if ($t_item->numErrors()) {
             if ($pb_output_errors) {
                 print "[Error] " . _t("Could not set preferred label for list item %1: %2", "{$vs_singular_label}/{$vs_plural_label}/{$ps_item_idno}", join('; ', $t_item->getErrors())) . "\n";
             }
             if ($o_log) {
                 $o_log->logError(_t("Could not set preferred label for list item %1: %2", "{$vs_singular_label}/{$vs_plural_label}/{$ps_item_idno}", join('; ', $t_item->getErrors())));
             }
             $vb_label_errors = true;
         }
         unset($pa_values['access']);
         unset($pa_values['status']);
         unset($pa_values['idno']);
         unset($pa_values['source_id']);
         $vb_attr_errors = !DataMigrationUtils::_setAttributes($t_item, $pn_locale_id, $pa_values, $pa_options);
         DataMigrationUtils::_setNonPreferredLabels($t_item, $pn_locale_id, $pa_options);
         DataMigrationUtils::_setIdno($t_item, $ps_item_idno, $pa_options);
         $vn_item_id = DataMigrationUtils::$s_cached_list_item_ids[$vs_cache_key] = $t_item->getPrimaryKey();
         if ($o_event) {
             if ($vb_attr_errors || $vb_label_errors) {
                 $o_event->endItem($vn_item_id, __CA_DATA_IMPORT_ITEM_PARTIAL_SUCCESS__, _t("Errors setting field values: %1", join('; ', $t_item->getErrors())));
             } else {
                 $o_event->endItem($vn_item_id, __CA_DATA_IMPORT_ITEM_SUCCESS__, '');
             }
         }
         if ($o_log) {
             $o_log->logInfo(_t("Created new list item %1 in list %2", "{$vs_singular_label}/{$vs_plural_label}/{$ps_item_idno}", $pm_list_code_or_id));
         }
         if (isset($pa_options['returnInstance']) && $pa_options['returnInstance']) {
             return $t_item;
         }
         return $vn_item_id;
     } else {
         if ($o_log) {
             $o_log->logError(_t("Could not find add item to list: %1", join("; ", $t_list->getErrors())));
         }
     }
     return null;
 }