/**
  * Extracts and returns printable parameters for the queue record passed in $pa_rec
  * This is used by utilties that present information on the task queue to show details of each queued task
  * without having to know specifics about the type of task.
  *
  * @param array $pa_rec An raw database record array for the queued task (eg. each key a field in ca_task_queue and the values are raw database data that has not been manipulated or unserialized)
  * @return array An array of printable parameters for the task; array keys are parameter codes, values are arrays with two keys: 'label' = a printable parameter description'; 'value' is a printable parameter setting
  */
 public function getParametersForDisplay($pa_rec)
 {
     $va_parameters = caUnserializeForDatabase($pa_rec["parameters"]);
     $va_params = array();
     $va_params['input_format'] = array('label' => _t('Input format'), 'value' => $va_parameters["INPUT_MIMETYPE"]);
     if (file_exists($va_parameters["FILENAME"])) {
         $va_params['input_file_size'] = array('label' => _t('Input file size'), 'value' => sprintf("%4.2dM", filesize($va_parameters["FILENAME"]) / (1024 * 1024)));
     }
     $va_params['table'] = array('label' => _t('Data source'), 'value' => $va_parameters["TABLE"] . ':' . $va_parameters["FIELD"] . ':' . $va_parameters["PK_VAL"]);
     $va_params['temporary_filename'] = array('label' => _t('Temporary filename'), 'value' => $va_parameters["FILENAME"]);
     if (is_array($va_parameters["VERSIONS"])) {
         $va_params['version'] = array('label' => _t('Versions output'), 'value' => join(", ", array_keys($va_parameters["VERSIONS"])));
     }
     if (is_array($va_parameters["RULES"]) && sizeof($va_parameters["RULES"]) > 0) {
         $vs_rules = '';
         foreach ($va_parameters["RULES"] as $vs_rule => $va_rule_info) {
             $vs_params .= "\t" . $vs_rule . " => ";
             $va_rule_list = array();
             foreach ($va_rule_info as $vs_key => $vs_val) {
                 $va_rule_list[] = "{$vs_key} = {$vs_val}";
             }
             $vs_rules = join("; ", $va_rule_list) . "\n";
         }
         $va_params['rule_list'] = array('label' => _t('Media processing rules'), 'value' => $vs_rules);
     }
     return $va_params;
 }
 public function getParametersForDisplay($pa_rec)
 {
     $va_parameters = caUnserializeForDatabase($pa_rec["parameters"]);
     $va_params = array();
     // TODO: add params
     return $va_params;
 }
 /**
  *
  *
  */
 public function loadTypeSpecificValueFromRow($pa_value_array)
 {
     $this->ops_text_value = $pa_value_array['value_longtext1'];
     $this->ops_uri_value = $pa_value_array['value_longtext2'];
     $va_info = caUnserializeForDatabase($pa_value_array['value_blob']);
     $this->opa_indexing_info = is_array($va_info) && isset($va_info['indexing_info']) && is_array($va_info['indexing_info']) ? $va_info['indexing_info'] : array();
     $this->opa_extra_info = is_array($va_info) && isset($va_info['extra_info']) && is_array($va_info['extra_info']) ? $va_info['extra_info'] : array();
 }
 public function getMediaArray($ps_data)
 {
     if (!is_array($ps_data)) {
         $va_data = caUnserializeForDatabase($ps_data);
         return is_array($va_data) ? $va_data : false;
     } else {
         return $ps_data;
     }
 }
Exemple #5
0
 public function getParametersForDisplay($pa_rec)
 {
     $va_parameters = caUnserializeForDatabase($pa_rec["parameters"]);
     $va_params = array();
     $t_set = new ca_sets($va_parameters['set_id']);
     $va_params['importing_from'] = array('label' => _t("Applying batch edits to set"), 'value' => $t_set->getLabelForDisplay());
     $va_params['number_of_records'] = array('label' => _t("Records to edit"), 'value' => (int) $t_set->getItemCount(array('user_id' => $va_parameters['user_id'])));
     $t_ui = new ca_editor_uis($va_parameters['ui_id']);
     $t_screen = new ca_editor_ui_screens();
     if ($t_screen->load(array('ui_id' => $t_ui->getPrimaryKey(), 'screen_id' => str_ireplace("screen", "", $va_parameters['screen'])))) {
         $va_params['ui'] = array('label' => _t("Using interface"), 'value' => $t_ui->getLabelForDisplay() . " ➜ " . $t_screen->getLabelForDisplay());
     }
     return $va_params;
 }
 public function getParametersForDisplay($pa_rec)
 {
     $va_parameters = caUnserializeForDatabase($pa_rec["parameters"]);
     $va_params = array();
     $o_config = Configuration::load();
     $vs_batch_media_import_root_directory = $o_config->get('batch_media_import_root_directory');
     $vs_relative_directory = preg_replace("!{$vs_batch_media_import_root_directory}[/]*!", "", $va_parameters["importFromDirectory"]);
     $va_params['importFromDirectory'] = array('label' => _t("Importing media from"), 'value' => "/" . $vs_relative_directory);
     if (file_exists($va_parameters["importFromDirectory"])) {
         $va_counts = caGetDirectoryContentsCount($va_parameters["importFromDirectory"], $va_parameters["includeSubDirectories"], false);
         $va_params['number_of_files'] = array('label' => _t("Files to import"), 'value' => (int) $va_counts['files']);
     }
     return $va_params;
 }
 public function __construct($po_db = null)
 {
     if (!is_object($po_db)) {
         $po_db = new Db();
     }
     $this->o_db = $po_db;
     $qr_res = $po_db->query("SELECT * FROM ca_application_vars LIMIT 1");
     if (!$qr_res->nextRow()) {
         # -- create app var record
         $this->opa_app_vars = array("last_modified_on" => time());
         $this->o_db->query("INSERT INTO ca_application_vars (vars) VALUES (?)", caSerializeForDatabase($this->opa_app_vars));
         if ($this->o_db->numErrors()) {
             # error
             $this->postError(300, join(';', $this->o_db->getErrors()), "ApplicationVars->load()");
             return false;
         }
         return true;
     }
     if (!is_array($this->opa_app_vars = caUnserializeForDatabase($qr_res->get('vars')))) {
         $this->opa_app_vars = array();
     }
 }
 /**
  * Generate  export file of current result
  */
 protected function _genExport($pt_subject, $ps_template, $ps_output_filename, $ps_title = null)
 {
     $this->view->setVar('t_subject', $pt_subject);
     if (substr($ps_template, 0, 5) === '_pdf_') {
         $va_template_info = caGetPrintTemplateDetails('summary', substr($ps_template, 5));
     } elseif (substr($ps_template, 0, 9) === '_display_') {
         $vn_display_id = substr($ps_template, 9);
         $t_display = new ca_bundle_displays($vn_display_id);
         if ($vn_display_id && $t_display->haveAccessToDisplay($this->request->getUserID(), __CA_BUNDLE_DISPLAY_READ_ACCESS__)) {
             $this->view->setVar('t_display', $t_display);
             $this->view->setVar('display_id', $vn_display_id);
             $va_display_list = array();
             $va_placements = $t_display->getPlacements(array('settingsOnly' => true));
             foreach ($va_placements as $vn_placement_id => $va_display_item) {
                 $va_settings = caUnserializeForDatabase($va_display_item['settings']);
                 // get column header text
                 $vs_header = $va_display_item['display'];
                 if (isset($va_settings['label']) && is_array($va_settings['label'])) {
                     $va_tmp = caExtractValuesByUserLocale(array($va_settings['label']));
                     if ($vs_tmp = array_shift($va_tmp)) {
                         $vs_header = $vs_tmp;
                     }
                 }
                 $va_display_list[$vn_placement_id] = array('placement_id' => $vn_placement_id, 'bundle_name' => $va_display_item['bundle_name'], 'display' => $vs_header, 'settings' => $va_settings);
             }
             $this->view->setVar('placements', $va_display_list);
         } else {
             $this->postError(3100, _t("Invalid format %1", $ps_template), "DetailController->_genExport()");
             return;
         }
         $va_template_info = caGetPrintTemplateDetails('summary', 'summary');
     } else {
         $this->postError(3100, _t("Invalid format %1", $ps_template), "DetailController->_genExport()");
         return;
     }
     //
     // PDF output
     //
     if (!is_array($va_template_info)) {
         $this->postError(3110, _t("Could not find view for PDF"), "DetailController->_genExport()");
         return;
     }
     //
     // Tag substitution
     //
     // Views can contain tags in the form {{{tagname}}}. Some tags, such as "itemType" and "detailType" are defined by
     // the detail controller. More usefully, you can pull data from the item being detailed by using a valid "get" expression
     // as a tag (Eg. {{{ca_objects.idno}}}. Even more usefully for some, you can also use a valid bundle display template
     // (see http://docs.collectiveaccess.org/wiki/Bundle_Display_Templates) as a tag. The template will be evaluated in the
     // context of the item being detailed.
     //
     $va_defined_vars = array_keys($this->view->getAllVars());
     // get list defined vars (we don't want to copy over them)
     $va_tag_list = $this->getTagListForView($va_template_info['path']);
     // get list of tags in view
     foreach ($va_tag_list as $vs_tag) {
         if (in_array($vs_tag, $va_defined_vars)) {
             continue;
         }
         if (strpos($vs_tag, "^") !== false || strpos($vs_tag, "<") !== false) {
             $this->view->setVar($vs_tag, $pt_subject->getWithTemplate($vs_tag, array('checkAccess' => $this->opa_access_values)));
         } elseif (strpos($vs_tag, ".") !== false) {
             $this->view->setVar($vs_tag, $pt_subject->get($vs_tag, array('checkAccess' => $this->opa_access_values)));
         } else {
             $this->view->setVar($vs_tag, "?{$vs_tag}");
         }
     }
     try {
         $this->view->setVar('base_path', $vs_base_path = pathinfo($va_template_info['path'], PATHINFO_DIRNAME));
         $this->view->addViewPath(array($vs_base_path, "{$vs_base_path}/local"));
         $vs_content = $this->render($va_template_info['path']);
         $o_dompdf = new DOMPDF();
         $o_dompdf->load_html($vs_content);
         $o_dompdf->set_paper(caGetOption('pageSize', $va_template_info, 'letter'), caGetOption('pageOrientation', $va_template_info, 'portrait'));
         $o_dompdf->set_base_path(caGetPrintTemplateDirectoryPath('summary'));
         $o_dompdf->render();
         $o_dompdf->stream(caGetOption('filename', $va_template_info, 'export_results.pdf'));
         $vb_printed_properly = true;
     } catch (Exception $e) {
         $vb_printed_properly = false;
         $this->postError(3100, _t("Could not generate PDF"), "DetailController->_genExport()");
     }
     return;
 }
Exemple #9
0
 /**
  * get() value for intrinsic
  *
  * @param array $pa_value_list
  * @param BaseModel $pt_instance
  * @param array Options
  *
  * @return array|string
  */
 private function _getIntrinsicValue($pa_value_list, $pt_instance, $pa_options)
 {
     $vb_return_as_link = isset($pa_options['returnAsLink']) ? $pa_options['returnAsLink'] : false;
     $vb_get_direct_date = (bool) caGetOption(array('getDirectDate', 'GET_DIRECT_DATE'), $pa_options, false);
     $vb_sortable = isset($pa_options['sortable']) ? $pa_options['sortable'] : false;
     $va_path_components = $pa_options['pathComponents'];
     $va_field_info = $pa_options['fieldInfo'];
     $vs_pk = $pa_options['primaryKey'];
     $vs_table_name = $pt_instance->tableName();
     // Handle specific intrinsic types
     switch ($va_field_info['FIELD_TYPE']) {
         case FT_DATERANGE:
         case FT_HISTORIC_DATERANGE:
         case FT_TIMESTAMP:
         case FT_DATETIME:
         case FT_HISTORIC_DATETIME:
             foreach ($pa_value_list as $vn_locale_id => $va_values) {
                 if ($pa_options['useLocaleCodes']) {
                     if (!$vn_locale_id || !($vm_locale_id = $this->opo_locales->localeIDToCode($vn_locale_id))) {
                         $vm_locale_id = __CA_DEFAULT_LOCALE__;
                     }
                 } else {
                     if (!($vm_locale_id = $vn_locale_id)) {
                         $vm_locale_id = $this->opo_locales->localeCodeToID(__CA_DEFAULT_LOCALE__);
                     }
                 }
                 foreach ($va_values as $vn_i => $va_value) {
                     $va_ids[] = $vn_id = $va_value[$vs_pk];
                     if (in_array($va_field_info['FIELD_TYPE'], array(FT_TIMESTAMP, FT_DATETIME, FT_HISTORIC_DATETIME))) {
                         $vs_prop = $va_value[$va_path_components['field_name']];
                         if (!$vb_get_direct_date && !$vb_sortable) {
                             $this->opo_tep->init();
                             if ($va_field_info['FIELD_TYPE'] !== FT_HISTORIC_DATETIME) {
                                 $this->opo_tep->setUnixTimestamps($vs_prop, $vs_prop);
                             } else {
                                 $this->opo_tep->setHistoricTimestamps($vs_prop, $vs_prop);
                             }
                             $vs_prop = $this->opo_tep->getText($pa_options);
                         }
                     } elseif ($vb_get_direct_date) {
                         $vs_prop = $va_value[$va_field_info['START']];
                     } elseif ($vb_sortable) {
                         $vs_prop = $va_value[$va_field_info['START']];
                     } else {
                         $this->opo_tep->init();
                         if ($va_field_info['FIELD_TYPE'] == FT_DATERANGE) {
                             $this->opo_tep->setUnixTimestamps($va_value[$va_field_info['START']], $va_value[$va_field_info['END']]);
                         } else {
                             $this->opo_tep->setHistoricTimestamps($va_value[$va_field_info['START']], $va_value[$va_field_info['END']]);
                         }
                         $vs_prop = $this->opo_tep->getText($pa_options);
                     }
                     if ($vb_return_as_link) {
                         $vs_prop = array_shift(caCreateLinksFromText(array($vs_prop), $vs_table_name, array($vn_id)));
                     }
                     $va_return_values[$vn_id][$vm_locale_id] = $vs_prop;
                 }
             }
             break;
         case FT_MEDIA:
             if (!($vs_version = $va_path_components['subfield_name'])) {
                 $vs_version = "largeicon";
                 // TODO: fix
             }
             foreach ($pa_value_list as $vn_locale_id => $va_values) {
                 if ($pa_options['useLocaleCodes']) {
                     if (!$vn_locale_id || !($vm_locale_id = $this->opo_locales->localeIDToCode($vn_locale_id))) {
                         $vm_locale_id = __CA_DEFAULT_LOCALE__;
                     }
                 } else {
                     if (!($vm_locale_id = $vn_locale_id)) {
                         $vm_locale_id = $this->opo_locales->localeCodeToID(__CA_DEFAULT_LOCALE__);
                     }
                 }
                 foreach ($va_values as $vn_i => $va_value) {
                     $va_ids[] = $vn_id = $va_value[$vs_pk];
                     $o_media_settings = new MediaProcessingSettings($va_path_components['table_name'], $va_path_components['field_name']);
                     $va_versions = $o_media_settings->getMediaTypeVersions('*');
                     if (!isset($va_versions[$vs_version])) {
                         $va_tmp = array_keys($va_versions);
                         $vs_version = array_shift($va_tmp);
                     }
                     // See if an info element was passed, eg. ca_object_representations.media.icon.width should return the width of the media rather than a tag or url to the media
                     $vs_info_element = $va_path_components['num_components'] == 4 ? $va_path_components['components'][3] : null;
                     if ($pa_options['unserialize']) {
                         $va_return_values[$vn_id][$vm_locale_id] = caUnserializeForDatabase($va_value[$va_path_components['field_name']]);
                     } elseif ($vs_info_element) {
                         $va_return_values[$vn_id][$vm_locale_id] = $this->getMediaInfo($va_path_components['table_name'] . '.' . $va_path_components['field_name'], $vs_version, $vs_info_element, $pa_options);
                     } elseif (isset($pa_options['returnURL']) && $pa_options['returnURL']) {
                         $va_return_values[$vn_id][$vm_locale_id] = $this->getMediaUrl($va_path_components['table_name'] . '.' . $va_path_components['field_name'], $vs_version, $pa_options);
                     } elseif (isset($pa_options['returnPath']) && $pa_options['returnPath']) {
                         $va_return_values[$vn_id][$vm_locale_id] = $this->getMediaPath($va_path_components['table_name'] . '.' . $va_path_components['field_name'], $vs_version, $pa_options);
                     } else {
                         $va_return_values[$vn_id][$vm_locale_id] = $this->getMediaTag($va_path_components['table_name'] . '.' . $va_path_components['field_name'], $vs_version, $pa_options);
                     }
                 }
             }
             break;
         default:
             // is intrinsic field in primary table
             foreach ($pa_value_list as $vn_locale_id => $va_values) {
                 if ($pa_options['useLocaleCodes']) {
                     if (!$vn_locale_id || !($vm_locale_id = $this->opo_locales->localeIDToCode($vn_locale_id))) {
                         $vm_locale_id = __CA_DEFAULT_LOCALE__;
                     }
                 } else {
                     if (!($vm_locale_id = $vn_locale_id)) {
                         $vm_locale_id = $this->opo_locales->localeCodeToID(__CA_DEFAULT_LOCALE__);
                     }
                 }
                 foreach ($va_values as $vn_i => $va_value) {
                     $va_ids[] = $vn_id = $va_value[$vs_pk];
                     $vs_prop = $va_value[$va_path_components['field_name']];
                     if ($pa_options['unserialize']) {
                         $vs_prop = caUnserializeForDatabase($vs_prop);
                     }
                     if ($pa_options['convertCodesToDisplayText']) {
                         $vs_prop = $this->_convertCodeToDisplayText($vs_prop, $va_path_components, $pt_instance, $pa_options);
                     } elseif ($pa_options['convertCodesToIdno']) {
                         $vs_prop = $this->_convertCodeToIdno($vs_prop, $va_path_components, $pt_instance, $pa_options);
                     }
                     $va_return_values[$vn_id][$vm_locale_id] = $vs_prop;
                 }
             }
             break;
     }
     if (!$pa_options['returnAllLocales']) {
         $va_return_values = caExtractValuesByUserLocale($va_return_values);
     }
     if ($pa_options['returnWithStructure']) {
         return is_array($va_return_values) ? $va_return_values : array();
     }
     //
     // Flatten array for return as string or simple array value
     //
     $va_flattened_values = $this->_flattenArray($va_return_values, $pa_options);
     if ($pa_options['returnAsArray']) {
         return $va_flattened_values;
     } else {
         return sizeof($va_flattened_values) > 0 ? join($pa_options['delimiter'], $va_flattened_values) : null;
     }
 }
 public function getDisplaysAsXML()
 {
     $t_display = new ca_bundle_displays();
     /** @var Datamodel $o_dm */
     $o_dm = Datamodel::load();
     $this->opt_locale = new ca_locales();
     $va_displays = $t_display->getBundleDisplays();
     $vs_buf = "<displays>\n";
     foreach ($va_displays as $vn_i => $va_display_by_locale) {
         $va_locales = array_keys($va_display_by_locale);
         $va_info = $va_display_by_locale[$va_locales[0]];
         if (!$t_display->load($va_info['display_id'])) {
             continue;
         }
         $vs_buf .= "\t<display code='" . ($va_info['display_code'] && preg_match('!^[A-Za-z0-9_]+$!', $va_info['display_code']) ? $va_info['display_code'] : 'display_' . $va_info['display_id']) . "' type='" . $o_dm->getTableName($va_info['table_num']) . "' system='" . $t_display->get('is_system') . "'>\n";
         $vs_buf .= "\t\t<labels>\n";
         foreach ($va_display_by_locale as $vn_locale_id => $va_display_info) {
             if (strlen($this->opt_locale->localeIDToCode($vn_locale_id)) > 0) {
                 $vs_buf .= "\t\t\t<label locale='" . $this->opt_locale->localeIDToCode($vn_locale_id) . "'><name>" . caEscapeForXML($va_display_info['name']) . "</name></label>\n";
             }
         }
         $vs_buf .= "\t\t</labels>\n";
         $va_settings = $t_display->getSettings();
         if (sizeof($va_settings) > 0) {
             $vs_buf .= "\t\t<settings>\n";
             foreach ($va_settings as $vs_setting => $vm_val) {
                 if (is_array($vm_val)) {
                     foreach ($vm_val as $vn_i => $vn_val) {
                         $vs_buf .= "\t\t\t<setting name='{$vs_setting}'><![CDATA[" . $vn_val . "]]></setting>\n";
                     }
                 } else {
                     $vs_buf .= "\t\t\t<setting name='{$vs_setting}'><![CDATA[" . $vm_val . "]]></setting>\n";
                 }
             }
             $vs_buf .= "\t\t</settings>\n";
         }
         // User and group access
         $va_users = $t_display->getUsers();
         if (sizeof($va_users) > 0) {
             $vs_buf .= "\t\t<userAccess>\n";
             foreach ($va_users as $va_user_info) {
                 $vs_buf .= "\t\t\t<permission user='******' access='" . $this->_convertUserGroupAccessToString(intval($va_user_info['access'])) . "'/>\n";
             }
             $vs_buf .= "\t\t</userAccess>\n";
         }
         $va_groups = $t_display->getUserGroups();
         if (sizeof($va_groups) > 0) {
             $vs_buf .= "\t\t<groupAccess>\n";
             foreach ($va_groups as $va_group_info) {
                 $vs_buf .= "\t\t\t<permission group='" . $va_group_info["code"] . "' access='" . $this->_convertUserGroupAccessToString(intval($va_group_info['access'])) . "'/>\n";
             }
             $vs_buf .= "\t\t</groupAccess>\n";
         }
         $va_placements = $t_display->getPlacements();
         $vs_buf .= "<bundlePlacements>\n";
         foreach ($va_placements as $vn_placement_id => $va_placement_info) {
             $vs_buf .= "\t\t<placement code='" . preg_replace("![^A-Za-z0-9_]+!", "_", $va_placement_info['bundle_name']) . "'><bundle>" . $va_placement_info['bundle_name'] . "</bundle>\n";
             $va_settings = caUnserializeForDatabase($va_placement_info['settings']);
             if (is_array($va_settings)) {
                 $vs_buf .= "<settings>\n";
                 foreach ($va_settings as $vs_setting => $vm_value) {
                     switch ($vs_setting) {
                         case 'label':
                             if (is_array($vm_value)) {
                                 foreach ($vm_value as $vn_locale_id => $vm_locale_specific_value) {
                                     if (preg_match("/^[a-z]{2,3}\\_[A-Z]{2,3}\$/", $vn_locale_id)) {
                                         // locale code
                                         $vs_locale_code = $vn_locale_id;
                                     } else {
                                         if (!($vs_locale_code = $this->opt_locale->localeIDToCode($vn_locale_id))) {
                                             $vs_locale_code = 'en_US';
                                         }
                                     }
                                     $vs_buf .= "<setting name='label' locale='" . $vs_locale_code . "'>" . caEscapeForXML($vm_locale_specific_value) . "</setting>\n";
                                 }
                             }
                             break;
                         case 'restrict_to_relationship_types':
                             if (is_array($vm_value)) {
                                 foreach ($vm_value as $vn_val) {
                                     $t_rel_type = new ca_relationship_types($vn_val);
                                     if ($t_rel_type->getPrimaryKey()) {
                                         $vs_value = $t_rel_type->get('type_code');
                                         $vs_buf .= "\t\t\t\t<setting name='{$vs_setting}'><![CDATA[" . $vs_value . "]]></setting>\n";
                                     }
                                 }
                             }
                             break;
                         case 'restrict_to_types':
                             if (is_array($vm_value)) {
                                 foreach ($vm_value as $vn_val) {
                                     $t_item = new ca_list_items($vn_val);
                                     if ($t_item->getPrimaryKey()) {
                                         $vs_value = $t_item->get('idno');
                                         $vs_buf .= "\t\t\t\t<setting name='{$vs_setting}'><![CDATA[" . $vs_value . "]]></setting>\n";
                                     }
                                 }
                             }
                             break;
                         default:
                             if (is_array($vm_value)) {
                                 foreach ($vm_value as $vn_i => $vn_val) {
                                     $vs_buf .= "\t\t\t\t<setting name='{$vs_setting}'><![CDATA[" . $vn_val . "]]></setting>\n";
                                 }
                             } else {
                                 $vs_buf .= "\t\t\t\t<setting name='{$vs_setting}'><![CDATA[" . $vm_value . "]]></setting>\n";
                             }
                             break;
                     }
                 }
                 $vs_buf .= "</settings>\n";
             }
             $vs_buf .= "\t\t</placement>\n";
         }
         $vs_buf .= "</bundlePlacements>\n";
         $vs_buf .= "\t</display>\n";
     }
     $vs_buf .= "</displays>\n";
     return $vs_buf;
 }
Exemple #11
0
 /**
  * Get change log for the current record represented by this BaseModel object, or for another specified row.
  * 
  * @access public
  * @param int $pn_row_id Return change log for row with specified primary key id. If omitted currently loaded record is used.
  * @param array $pa_options Array of options. Valid options are:
  * 		range = optional range to restrict returned entries to. Should be array with 0th key set to start and 1st key set to end of range. Both values should be Unix timestamps. You can also use 'start' and 'end' as keys if desired. 
  * 		limit = maximum number of entries returned. Omit or set to zero for no limit. [default=all]
  * 		forTable = if true only return changes made directly to the current table (ie. omit changes to related records that impact this record [default=false]
  * 		excludeUnitID = if set, log records with the specific unit_id are not returned [default=not set]
  *		changeType = if set to I, U or D, will limit change log to inserts, updates or deletes respectively. If not set all types are returned.
  * @return array Change log data
  */
 public function getChangeLog($pn_row_id = null, $pa_options = null)
 {
     $pa_datetime_range = isset($pa_options['range']) && is_array($pa_options['range']) ? $pa_options['range'] : null;
     $pn_max_num_entries_returned = isset($pa_options['limit']) && (int) $pa_options['limit'] ? (int) $pa_options['limit'] : 0;
     $pb_for_table = isset($pa_options['forTable']) ? (bool) $pa_options['forTable'] : false;
     $ps_exclude_unit_id = isset($pa_options['excludeUnitID']) && $pa_options['excludeUnitID'] ? $pa_options['excludeUnitID'] : null;
     $ps_change_type = isset($pa_options['changeType']) && in_array($pa_options['changeType'], array('I', 'U', 'D')) ? $pa_options['changeType'] : null;
     $vs_daterange_sql = '';
     if ($pa_datetime_range) {
         $vn_start = $vn_end = null;
         if (isset($pa_datetime_range[0])) {
             $vn_start = (int) $pa_datetime_range[0];
         } else {
             if (isset($pa_datetime_range['start'])) {
                 $vn_start = (int) $pa_datetime_range['start'];
             }
         }
         if (isset($pa_datetime_range[1])) {
             $vn_end = (int) $pa_datetime_range[1];
         } else {
             if (isset($pa_datetime_range['end'])) {
                 $vn_end = (int) $pa_datetime_range['end'];
             }
         }
         if ($vn_start <= 0) {
             $vn_start = time() - 3600;
         }
         if (!$vn_end <= 0) {
             $vn_end = time();
         }
         if ($vn_end < $vn_start) {
             $vn_end = $vn_start;
         }
         if (!$pn_row_id) {
             if (!($pn_row_id = $this->getPrimaryKey())) {
                 return array();
             }
         }
         $vs_daterange_sql = " AND (wcl.log_datetime > ? AND wcl.log_datetime < ?)";
     }
     if (!$this->opqs_get_change_log) {
         $vs_change_log_database = '';
         if ($vs_change_log_database = $this->_CONFIG->get("change_log_database")) {
             $vs_change_log_database .= ".";
         }
         $o_db = $this->getDb();
         if ($pb_for_table) {
             if (!($this->opqs_get_change_log = $o_db->prepare("\n\t\t\t\t\tSELECT DISTINCT\n\t\t\t\t\t\twcl.log_id, wcl.log_datetime log_datetime, wcl.user_id, wcl.changetype, wcl.logged_table_num, wcl.logged_row_id,\n\t\t\t\t\t\twclsnap.snapshot, wcl.unit_id, wu.email, wu.fname, wu.lname\n\t\t\t\t\tFROM ca_change_log wcl\n\t\t\t\t\tINNER JOIN ca_change_log_snapshots AS wclsnap ON wclsnap.log_id = wcl.log_id\n\t\t\t\t\tLEFT JOIN ca_change_log_subjects AS wcls ON wcl.log_id = wcls.log_id\n\t\t\t\t\tLEFT JOIN ca_users AS wu ON wcl.user_id = wu.user_id\n\t\t\t\t\tWHERE\n\t\t\t\t\t\t(\n\t\t\t\t\t\t\t(wcl.logged_table_num = " . (int) $this->tableNum() . ") AND " . ($ps_change_type ? "(wcl.changetype = '" . $ps_change_type . "') AND " : "") . "\n\t\t\t\t\t\t\t(wcl.logged_row_id = ?)\n\t\t\t\t\t\t)\n\t\t\t\t\t\t{$vs_daterange_sql}\n\t\t\t\t\tORDER BY log_datetime\n\t\t\t\t"))) {
                 # should not happen
                 return false;
             }
         } else {
             if (!($this->opqs_get_change_log = $o_db->prepare("\n\t\t\t\t\tSELECT DISTINCT\n\t\t\t\t\t\twcl.log_id, wcl.log_datetime log_datetime, wcl.user_id, wcl.changetype, wcl.logged_table_num, wcl.logged_row_id,\n\t\t\t\t\t\twclsnap.snapshot, wcl.unit_id, wu.email, wu.fname, wu.lname\n\t\t\t\t\tFROM ca_change_log wcl\n\t\t\t\t\tINNER JOIN ca_change_log_snapshots AS wclsnap ON wclsnap.log_id = wcl.log_id\n\t\t\t\t\tLEFT JOIN ca_change_log_subjects AS wcls ON wcl.log_id = wcls.log_id\n\t\t\t\t\tLEFT JOIN ca_users AS wu ON wcl.user_id = wu.user_id\n\t\t\t\t\tWHERE\n\t\t\t\t\t\t(\n\t\t\t\t\t\t\t(wcl.logged_table_num = " . (int) $this->tableNum() . ") AND " . ($ps_change_type ? "(wcl.changetype = '" . $ps_change_type . "') AND " : "") . "\n\t\t\t\t\t\t\t(wcl.logged_row_id = ?)\n\t\t\t\t\t\t)\n\t\t\t\t\t\t{$vs_daterange_sql}\n\t\t\t\t\tUNION\n\t\t\t\t\tSELECT DISTINCT\n\t\t\t\t\t\twcl.log_id, wcl.log_datetime, wcl.user_id, wcl.changetype, wcl.logged_table_num, wcl.logged_row_id,\n\t\t\t\t\t\twclsnap.snapshot, wcl.unit_id, wu.email, wu.fname, wu.lname\n\t\t\t\t\tFROM ca_change_log wcl\n\t\t\t\t\tINNER JOIN ca_change_log_snapshots AS wclsnap ON wclsnap.log_id = wcl.log_id\n\t\t\t\t\tLEFT JOIN ca_change_log_subjects AS wcls ON wcl.log_id = wcls.log_id\n\t\t\t\t\tLEFT JOIN ca_users AS wu ON wcl.user_id = wu.user_id\n\t\t\t\t\tWHERE\n\t\t\t\t\t\t (\n\t\t\t\t\t\t\t(wcls.subject_table_num = " . (int) $this->tableNum() . ") AND " . ($ps_change_type ? "(wcl.changetype = '" . $ps_change_type . "') AND " : "") . "\n\t\t\t\t\t\t\t(wcls.subject_row_id  = ?)\n\t\t\t\t\t\t)\n\t\t\t\t\t\t{$vs_daterange_sql}\n\t\t\t\t\tORDER BY log_datetime\n\t\t\t\t"))) {
                 # should not happen
                 return false;
             }
         }
         if ($pn_max_num_entries_returned > 0) {
             $this->opqs_get_change_log->setLimit($pn_max_num_entries_returned);
         }
     }
     // get directly logged records
     $va_log = array();
     if ($pb_for_table) {
         $qr_log = $this->opqs_get_change_log->execute($vs_daterange_sql ? array((int) $pn_row_id, (int) $vn_start, (int) $vn_end) : array((int) $pn_row_id));
     } else {
         $qr_log = $this->opqs_get_change_log->execute($vs_daterange_sql ? array((int) $pn_row_id, (int) $vn_start, (int) $vn_end, (int) $pn_row_id, (int) $vn_start, (int) $vn_end) : array((int) $pn_row_id, (int) $pn_row_id));
     }
     while ($qr_log->nextRow()) {
         if ($ps_exclude_unit_id && $ps_exclude_unit_id == $qr_log->get('unit_id')) {
             continue;
         }
         $va_log[] = $qr_log->getRow();
         $va_log[sizeof($va_log) - 1]['snapshot'] = caUnserializeForDatabase($va_log[sizeof($va_log) - 1]['snapshot']);
     }
     return $va_log;
 }
 /**
  * Returns values for bundle. Can be used to set initial state of bundle as well as to grab partial value sets for
  * progressive loading of bundles.
  *
  * NOTE: Currently only support ca_object_representations bundle
  *
  */
 public function getBundleFormValues($ps_bundle_name, $ps_placement_code, $pa_bundle_settings, $pa_options = null)
 {
     global $g_ui_locale;
     // Check if user has access to this bundle
     if ($pa_options['request']->user->getBundleAccessLevel($this->tableName(), $ps_bundle_name) == __CA_BUNDLE_ACCESS_NONE__) {
         return;
     }
     // Check if user has access to this type
     if ((bool) $this->getAppConfig()->get('perform_type_access_checking')) {
         $vn_type_access = $pa_options['request']->user->getTypeAccessLevel($this->tableName(), $this->getTypeID());
         if ($vn_type_access == __CA_BUNDLE_ACCESS_NONE__) {
             return;
         }
         if ($vn_type_access == __CA_BUNDLE_ACCESS_READONLY__) {
             $pa_bundle_settings['readonly'] = true;
         }
     }
     // Check if user has access to this source
     if ((bool) $this->getAppConfig()->get('perform_source_access_checking')) {
         $vn_source_access = $pa_options['request']->user->getSourceAccessLevel($this->tableName(), $this->getSourceID());
         if ($vn_source_access == __CA_BUNDLE_ACCESS_NONE__) {
             return;
         }
         if ($vn_source_access == __CA_BUNDLE_ACCESS_READONLY__) {
             $pa_bundle_settings['readonly'] = true;
         }
     }
     if ((bool) $this->getAppConfig()->get('perform_item_level_access_checking') && $this->getPrimaryKey()) {
         $vn_item_access = $this->checkACLAccessForUser($pa_options['request']->user);
         if ($vn_item_access == __CA_ACL_NO_ACCESS__) {
             return;
         }
         if ($vn_item_access == __CA_ACL_READONLY_ACCESS__) {
             $pa_bundle_settings['readonly'] = true;
         }
     }
     $va_info = $this->getBundleInfo($ps_bundle_name);
     if (!($vs_type = $va_info['type'])) {
         return null;
     }
     if (isset($pa_options['config']) && is_object($pa_options['config'])) {
         $o_config = $pa_options['config'];
     } else {
         $o_config = $this->getAppConfig();
     }
     // start and count
     $pn_start = caGetOption('start', $pa_options, 0);
     $pn_limit = caGetOption('limit', $pa_options, null);
     $vs_element = '';
     switch ($vs_type) {
         # -------------------------------------------------
         case 'preferred_label':
         case 'nonpreferred_label':
             break;
             # -------------------------------------------------
         # -------------------------------------------------
         case 'intrinsic':
             break;
             # -------------------------------------------------
         # -------------------------------------------------
         case 'attribute':
             break;
             # -------------------------------------------------
         # -------------------------------------------------
         case 'related_table':
             switch ($ps_bundle_name) {
                 # -------------------------------
                 case 'ca_object_representations':
                     foreach (array('restrict_to_types', 'restrict_to_relationship_types') as $vs_k) {
                         $pa_options[$vs_k] = $pa_bundle_settings[$vs_k];
                     }
                     $va_reps = $this->getRepresentations(array('thumbnail', 'original'), null, $pa_options);
                     $t_item = new ca_object_representations();
                     $va_rep_type_list = $t_item->getTypeList();
                     $va_errors = array();
                     $vs_bundle_template = caGetOption('display_template', $pa_bundle_settings, null);
                     // Paging
                     $vn_primary_id = 0;
                     $va_initial_values = array();
                     if (sizeof($va_reps)) {
                         $o_type_config = Configuration::load($t_item->getAppConfig()->get('annotation_type_config'));
                         $va_annotation_type_mappings = $o_type_config->getAssoc('mappings');
                         // Get display template values
                         $va_display_template_values = array();
                         if ($vs_bundle_template && is_array($va_relation_ids = caExtractValuesFromArrayList($va_reps, 'relation_id')) && sizeof($va_relation_ids)) {
                             if ($vs_linking_table = RepresentableBaseModel::getRepresentationRelationshipTableName($this->tableName())) {
                                 $va_display_template_values = caProcessTemplateForIDs($vs_bundle_template, $vs_linking_table, $va_relation_ids, array_merge($pa_options, array('returnAsArray' => true, 'returnAllLocales' => false, 'includeBlankValuesInArray' => true)));
                             }
                         }
                         $vn_i = 0;
                         foreach ($va_reps as $va_rep) {
                             $vn_num_multifiles = $va_rep['num_multifiles'];
                             if ($vs_extracted_metadata = caFormatMediaMetadata(caSanitizeArray(caUnserializeForDatabase($va_rep['media_metadata'])))) {
                                 $vs_extracted_metadata = "<h3>" . _t('Extracted metadata') . ":</h3>\n{$vs_extracted_metadata}\n";
                             }
                             $vs_md5 = isset($va_rep['info']['original']['MD5']) ? "<h3>" . _t('MD5 signature') . ':</h3>' . $va_rep['info']['original']['MD5'] : '';
                             if ($va_rep['is_primary']) {
                                 $vn_primary_id = $va_rep['representation_id'];
                             }
                             $va_initial_values[$va_rep['representation_id']] = array('idno' => $va_rep['idno'], '_display' => $vs_bundle_template && isset($va_display_template_values[$vn_i]) ? $va_display_template_values[$vn_i] : '', 'status' => $va_rep['status'], 'status_display' => $t_item->getChoiceListValue('status', $va_rep['status']), 'access' => $va_rep['access'], 'access_display' => $t_item->getChoiceListValue('access', $va_rep['access']), 'rep_type_id' => $va_rep['type_id'], 'rep_type' => $t_item->getTypeName($va_rep['type_id']), 'rep_label' => $va_rep['label'], 'is_primary' => (int) $va_rep['is_primary'], 'is_primary_display' => $va_rep['is_primary'] == 1 ? _t('PRIMARY') : '', 'locale_id' => $va_rep['locale_id'], 'icon' => $va_rep['tags']['thumbnail'], 'mimetype' => $va_rep['info']['original']['PROPERTIES']['mimetype'], 'annotation_type' => isset($va_annotation_type_mappings[$va_rep['info']['original']['PROPERTIES']['mimetype']]) ? $va_annotation_type_mappings[$va_rep['info']['original']['PROPERTIES']['mimetype']] : null, 'type' => $va_rep['info']['original']['PROPERTIES']['typename'], 'dimensions' => $va_rep['dimensions']['original'], 'filename' => $va_rep['info']['original_filename'] ? $va_rep['info']['original_filename'] : _t('Unknown'), 'num_multifiles' => $vn_num_multifiles ? $vn_num_multifiles == 1 ? _t('+ 1 additional preview') : _t('+ %1 additional previews', $vn_num_multifiles) : '', 'metadata' => $vs_extracted_metadata, 'md5' => $vs_md5 ? "{$vs_md5}" : "", 'typename' => $va_rep_type_list[$va_rep['type_id']]['name_singular'], 'fetched_from' => $va_rep['fetched_from'], 'fetched_on' => date('c', $va_rep['fetched_on']), 'fetched' => $va_rep['fetched_from'] ? _t("<h3>Fetched from:</h3> URL %1 on %2", '<a href="' . $va_rep['fetched_from'] . '" target="_ext" title="' . $va_rep['fetched_from'] . '">' . $va_rep['fetched_from'] . '</a>', date('c', $va_rep['fetched_on'])) : "");
                             $vn_i++;
                         }
                     }
                     return $va_initial_values;
                     break;
                 case 'ca_entities':
                 case 'ca_places':
                 case 'ca_occurrences':
                 case 'ca_objects':
                 case 'ca_collections':
                 case 'ca_list_items':
                 case 'ca_storage_locations':
                 case 'ca_loans':
                 case 'ca_movements':
                 case 'ca_tour_stops':
                     return $this->getRelatedBundleFormValues($pa_options['request'], $pa_options['formName'], $ps_bundle_name, $ps_placement_code, $pa_bundle_settings, $pa_options);
                     break;
                     # -------------------------------
                 # -------------------------------
                 case 'ca_object_lots':
                     break;
                     # -------------------------------
                 # -------------------------------
                 case 'ca_representation_annotations':
                     break;
                     # -------------------------------
                 # -------------------------------
                 default:
                     return null;
                     break;
                     # -------------------------------
             }
             break;
     }
     return null;
 }
Exemple #13
0
 /**
  * Get list of roles the current user has via associated groups
  *
  * @access public
  * @return array Returns associative array of roles. Key is role id, value is array containing information about the role.
  *
  * The role information array contains the following keys: 
  *		role_id 	(numeric id you can use in addRoles(), deleteRoles(), hasRole(), etc.)
  *		name 		(the full name of the role)
  *		code		(a short code used for the role)
  *		description	(narrative description of role)
  */
 public function getGroupRoles()
 {
     if ($pn_user_id = $this->getPrimaryKey()) {
         if (isset(ca_users::$s_group_role_cache[$pn_user_id])) {
             return ca_users::$s_group_role_cache[$pn_user_id];
         } else {
             $o_db = $this->getDb();
             $qr_res = $o_db->query("\n\t\t\t\t\tSELECT wur.role_id, wur.name, wur.code, wur.description, wur.rank, wur.vars\n\t\t\t\t\tFROM ca_user_roles wur\n\t\t\t\t\tINNER JOIN ca_groups_x_roles AS wgxr ON wgxr.role_id = wur.role_id\n\t\t\t\t\tINNER JOIN ca_users_x_groups AS wuxg ON wuxg.group_id = wgxr.group_id\n\t\t\t\t\tWHERE wuxg.user_id = ?\n\t\t\t\t", (int) $pn_user_id);
             $va_roles = array();
             while ($qr_res->nextRow()) {
                 $va_row = $qr_res->getRow();
                 $va_row['vars'] = caUnserializeForDatabase($va_row['vars']);
                 $va_roles[$va_row['role_id']] = $va_row;
             }
             return ca_users::$s_group_role_cache[$pn_user_id] = $va_roles;
         }
     } else {
         return array();
     }
 }
 public function getDisplaysAsXML($pa_options = null)
 {
     $t_display = new ca_bundle_displays();
     $o_dm = Datamodel::load();
     $this->opt_locale = new ca_locales();
     $va_displays = $t_display->getBundleDisplays();
     $vs_buf = "<displays>\n";
     foreach ($va_displays as $vn_i => $va_display_by_locale) {
         $va_locales = array_keys($va_display_by_locale);
         $va_info = $va_display_by_locale[$va_locales[0]];
         if (!$t_display->load($va_info['display_id'])) {
             continue;
         }
         $vs_buf .= "\t<display code='" . ($va_info['display_code'] && preg_match('!^[A-Za-z0-9_]+$!', $va_info['display_code']) ? $va_info['display_code'] : 'display_' . $va_info['display_id']) . "' type='" . $o_dm->getTableName($va_info['table_num']) . "' system='" . $t_display->get('is_system') . "'>\n";
         $vs_buf .= "\t\t<labels>\n";
         foreach ($va_display_by_locale as $vn_locale_id => $va_display_info) {
             if (strlen($this->opt_locale->localeIDToCode($vn_locale_id)) > 0) {
                 $vs_buf .= "\t\t\t<label locale='" . $this->opt_locale->localeIDToCode($vn_locale_id) . "'><name>" . caEscapeForXML($va_display_info['name']) . "</name></label>\n";
             }
         }
         $vs_buf .= "\t\t</labels>\n";
         $va_placements = $t_display->getPlacements();
         //print_R(($va_placements));
         $vs_buf .= "<bundlePlacements>\n";
         foreach ($va_placements as $vn_placement_id => $va_placement_info) {
             $vs_buf .= "\t\t<placement code='" . preg_replace("![^A-Za-z0-9_]+!", "_", $va_placement_info['bundle_name']) . "'><bundle>" . $va_placement_info['bundle_name'] . "</bundle>\n";
             $va_settings = caUnserializeForDatabase($va_placement_info['settings']);
             if (is_array($va_settings)) {
                 $vs_buf .= "<settings>\n";
                 foreach ($va_settings as $vs_setting => $vm_value) {
                     switch ($vs_setting) {
                         case 'label':
                             //restrict_to_relationship_types
                             if (is_array($vm_value)) {
                                 foreach ($vm_value as $vn_locale_id => $vm_locale_specific_value) {
                                     $vs_buf .= "<setting name='label' locale='" . $this->opt_locale->localeIDToCode($vn_locale_id) . "'>" . caEscapeForXML($vm_locale_specific_value) . "</setting>\n";
                                 }
                             }
                             break;
                         default:
                             if (is_array($vm_value)) {
                                 foreach ($vm_value as $vn_i => $vn_val) {
                                     $vs_buf .= "\t\t\t\t<setting name='{$vs_setting}'>" . caEscapeForXML($vn_val) . "</setting>\n";
                                 }
                             } else {
                                 $vs_buf .= "\t\t\t\t<setting name='{$vs_setting}'>" . caEscapeForXML($vm_value) . "</setting>\n";
                             }
                             break;
                     }
                 }
                 $vs_buf .= "</settings>\n";
             }
             $vs_buf .= "\t\t</placement>\n";
         }
         $vs_buf .= "</bundlePlacements>\n";
         $vs_buf .= "\t</display>\n";
     }
     $vs_buf .= "</displays>\n";
     //print_R($va_displays);
     return $vs_buf;
 }
 /**
  * Returns list of placements for the currently loaded display.
  *
  * @param array $pa_options Optional array of options. Supports the following options:
  * 		noCache = if set to true then the returned list if always generated directly from the database, otherwise it is returned from the cache if possible. Set this to true if you expect the cache may be stale. Default is false.
  *		returnAllAvailableIfEmpty = if set to true then the list of all available bundles will be returned if the currently loaded display has no placements, or if there is no display loaded
  *		table = if using the returnAllAvailableIfEmpty option and you expect a list of available bundles to be returned if no display is loaded, you must specify the table the bundles are intended for use with with this option. Either the table name or number may be used.
  *		user_id = if specified then placements are only returned if the user has at least read access to the display
  *		settingsOnly = if true the settings forms are omitted and only setting values are returned; default is false
  * @return array List of placements in display order. Array is keyed on bundle name. Values are arrays with the following keys:
  *		placement_id = primary key of ca_bundle_display_placements row - a unique id for the placement
  *		bundle_name = bundle name (a code - not for display)
  *		settings = array of placement settings. Keys are setting names.
  *		display = display string for bundle
  */
 public function getPlacements($pa_options = null)
 {
     $pb_no_cache = isset($pa_options['noCache']) ? (bool) $pa_options['noCache'] : false;
     $pb_settings_only = isset($pa_options['settingsOnly']) ? (bool) $pa_options['settingsOnly'] : false;
     $pb_return_all_available_if_empty = isset($pa_options['returnAllAvailableIfEmpty']) && !$pb_settings_only ? (bool) $pa_options['returnAllAvailableIfEmpty'] : false;
     $ps_table = isset($pa_options['table']) ? $pa_options['table'] : null;
     $pn_user_id = isset($pa_options['user_id']) ? $pa_options['user_id'] : null;
     if ($pn_user_id && !$this->haveAccessToDisplay($pn_user_id, __CA_BUNDLE_DISPLAY_READ_ACCESS__)) {
         return array();
     }
     if (!($vn_display_id = $this->getPrimaryKey())) {
         if ($pb_return_all_available_if_empty && $ps_table) {
             return ca_bundle_displays::$s_placement_list_cache[$vn_display_id] = $this->getAvailableBundles($ps_table);
         }
         return array();
     }
     $vs_cache_key = $vn_display_id . '/' . ($pb_settings_only ? 1 : 0);
     if (!$pb_no_cache && isset(ca_bundle_displays::$s_placement_list_cache[$vs_cache_key]) && ca_bundle_displays::$s_placement_list_cache[$vs_cache_key]) {
         return ca_bundle_displays::$s_placement_list_cache[$vs_cache_key];
     }
     $o_dm = $this->getAppDatamodel();
     $o_db = $this->getDb();
     $t_list = new ca_lists();
     if ($this->inTransaction()) {
         $t_list->setTransaction($this->getTransaction());
     }
     $qr_res = $o_db->query("\n\t\t\tSELECT placement_id, bundle_name, settings\n\t\t\tFROM ca_bundle_display_placements\n\t\t\tWHERE\n\t\t\t\tdisplay_id = ?\n\t\t\tORDER BY rank\n\t\t", (int) $vn_display_id);
     $va_available_bundles = $pb_settings_only ? array() : $this->getAvailableBundles(null, $pa_options);
     $va_placements = array();
     if ($qr_res->numRows() > 0) {
         $vs_subject_table = $o_dm->getTableName($this->get('table_num'));
         $t_subject = $o_dm->getInstanceByTableNum($this->get('table_num'), true);
         $t_placement = new ca_bundle_display_placements();
         if ($this->inTransaction()) {
             $t_placement->setTransaction($this->getTransaction());
         }
         while ($qr_res->nextRow()) {
             $vs_bundle_name = $qr_res->get('bundle_name');
             $va_bundle_name = explode(".", $vs_bundle_name);
             $va_placements[$vn_placement_id = (int) $qr_res->get('placement_id')] = $qr_res->getRow();
             $va_placements[$vn_placement_id]['settings'] = $va_settings = caUnserializeForDatabase($qr_res->get('settings'));
             if (!$pb_settings_only) {
                 $t_placement->setSettingDefinitionsForPlacement($va_available_bundles[$vs_bundle_name]['settings']);
                 $va_placements[$vn_placement_id]['display'] = $va_available_bundles[$vs_bundle_name]['display'];
                 $va_placements[$vn_placement_id]['settingsForm'] = $t_placement->getHTMLSettingForm(array('id' => $vs_bundle_name . '_' . $vn_placement_id, 'settings' => $va_settings));
             } else {
                 $va_tmp = explode('.', $vs_bundle_name);
                 $t_instance = $o_dm->getInstanceByTableName($va_tmp[0], true);
                 $va_placements[$vn_placement_id]['display'] = $t_instance ? $t_instance->getDisplayLabel($vs_bundle_name) : "???";
             }
             if ($va_bundle_name[0] == $vs_subject_table) {
                 // Only primary fields are inline-editable
                 // Check if it is one of the types of fields that is inline editable
                 if ($va_bundle_name[1] == 'preferred_labels') {
                     // Preferred labels are inline editable
                     $va_placements[$vn_placement_id]['allowInlineEditing'] = true;
                     $va_placements[$vn_placement_id]['inlineEditingType'] = DT_FIELD;
                 } elseif ($t_subject->hasField($va_bundle_name[1])) {
                     //
                     // Intrinsics are editable, except for type_id
                     //
                     if ($va_bundle_name[1] == $t_subject->getTypeFieldName()) {
                         $va_placements[$vn_placement_id]['allowInlineEditing'] = false;
                         $va_placements[$vn_placement_id]['inlineEditingType'] = null;
                     } else {
                         if (isset($va_bundle_name[1])) {
                             // check if identifier is editable
                             $id_editable = $t_subject->opo_idno_plugin_instance->isFormatEditable($vs_subject_table);
                             // Do not allow in-line editing if the intrinsic element is identifier and
                             // a). is not editable (editable = 0 in multipart_id_numbering.conf)
                             // b). consists of multiple elements
                             if ($va_bundle_name[1] == $t_subject->getProperty('ID_NUMBERING_ID_FIELD') && $id_editable == false) {
                                 $va_placements[$vn_placement_id]['allowInlineEditing'] = false;
                             } else {
                                 $va_placements[$vn_placement_id]['allowInlineEditing'] = true;
                             }
                         }
                         switch ($t_subject->getFieldInfo($va_bundle_name[1], 'DISPLAY_TYPE')) {
                             case 'DT_SELECT':
                                 if (($vs_list_code = $t_subject->getFieldInfo($va_bundle_name[1], 'LIST')) || ($vs_list_code = $t_subject->getFieldInfo($va_bundle_name[1], 'LIST_CODE'))) {
                                     $va_placements[$vn_placement_id]['inlineEditingType'] = DT_SELECT;
                                     if (!is_array($va_list_labels = $t_list->getItemsForList($vs_list_code, array('labelsOnly' => true)))) {
                                         $va_list_labels = array();
                                     }
                                     $va_placements[$vn_placement_id]['inlineEditingListValues'] = array_values($va_list_labels);
                                 } else {
                                     $va_placements[$vn_placement_id]['inlineEditingType'] = DT_FIELD;
                                 }
                                 break;
                             default:
                                 $va_placements[$vn_placement_id]['inlineEditingType'] = DT_FIELD;
                                 break;
                         }
                     }
                 } elseif ($t_subject->hasElement($va_bundle_name[1])) {
                     $vn_data_type = ca_metadata_elements::getElementDatatype($va_bundle_name[1]);
                     switch ($vn_data_type) {
                         case 1:
                         case 2:
                         case 5:
                         case 6:
                         case 8:
                         case 9:
                         case 10:
                         case 11:
                         case 12:
                             $va_placements[$vn_placement_id]['allowInlineEditing'] = true;
                             $va_placements[$vn_placement_id]['inlineEditingType'] = DT_FIELD;
                             break;
                         case 3:
                             // lists
                             if ($t_element = ca_metadata_elements::getInstance($va_bundle_name[1])) {
                                 switch ($t_element->getSetting('render')) {
                                     case 'select':
                                     case 'yes_no_checkboxes':
                                     case 'radio_buttons':
                                     case 'checklist':
                                         $va_placements[$vn_placement_id]['allowInlineEditing'] = true;
                                         $va_placements[$vn_placement_id]['inlineEditingType'] = DT_SELECT;
                                         $va_placements[$vn_placement_id]['inlineEditingListValues'] = array_values($t_list->getItemsForList($t_element->get("list_id"), array('labelsOnly' => true)));
                                         break;
                                     case 'lookup':
                                     case 'horiz_hierbrowser':
                                     case 'horiz_hierbrowser_with_search':
                                     case 'vert_hierbrowser':
                                         $va_placements[$vn_placement_id]['allowInlineEditing'] = true;
                                         $va_placements[$vn_placement_id]['inlineEditingType'] = DT_LOOKUP;
                                         $va_placements[$vn_placement_id]['inlineEditingList'] = $t_element->get('list_id');
                                         break;
                                     default:
                                         // if it's a render setting we don't know about it's not editable
                                         $va_placements[$vn_placement_id]['allowInlineEditing'] = false;
                                         $va_placements[$vn_placement_id]['inlineEditingType'] = null;
                                         break;
                                 }
                             }
                             break;
                         default:
                             $va_placements[$vn_placement_id]['allowInlineEditing'] = false;
                             $va_placements[$vn_placement_id]['inlineEditingType'] = null;
                             break;
                     }
                 } else {
                     $va_placements[$vn_placement_id]['allowInlineEditing'] = false;
                     $va_placements[$vn_placement_id]['inlineEditingType'] = null;
                 }
             } else {
                 // Related bundles are never inline-editable (for now)
                 $va_placements[$vn_placement_id]['allowInlineEditing'] = false;
                 $va_placements[$vn_placement_id]['inlineEditingType'] = null;
             }
         }
     } else {
         if ($pb_return_all_available_if_empty) {
             $va_placements = $this->getAvailableBundles($this->get('table_num'));
         }
     }
     return ca_bundle_displays::$s_placement_list_cache[$vs_cache_key] = $va_placements;
 }
Exemple #16
0
 /**
  * Generate  export file of current result
  */
 protected function _genExport($po_result, $ps_template, $ps_output_filename, $ps_title = null)
 {
     if ($this->opo_result_context) {
         $this->opo_result_context->setParameter('last_export_type', $ps_output_type);
         $this->opo_result_context->saveContext();
     }
     if (substr($ps_template, 0, 5) === '_pdf_') {
         $va_template_info = caGetPrintTemplateDetails('results', substr($ps_template, 5));
     } elseif (substr($ps_template, 0, 9) === '_display_') {
         $vn_display_id = substr($ps_template, 9);
         $t_display = new ca_bundle_displays($vn_display_id);
         if ($vn_display_id && $t_display->haveAccessToDisplay($this->request->getUserID(), __CA_BUNDLE_DISPLAY_READ_ACCESS__)) {
             $this->view->setVar('display', $t_display);
             $va_placements = $t_display->getPlacements(array('settingsOnly' => true));
             foreach ($va_placements as $vn_placement_id => $va_display_item) {
                 $va_settings = caUnserializeForDatabase($va_display_item['settings']);
                 // get column header text
                 $vs_header = $va_display_item['display'];
                 if (isset($va_settings['label']) && is_array($va_settings['label'])) {
                     $va_tmp = caExtractValuesByUserLocale(array($va_settings['label']));
                     if ($vs_tmp = array_shift($va_tmp)) {
                         $vs_header = $vs_tmp;
                     }
                 }
                 $va_display_list[$vn_placement_id] = array('placement_id' => $vn_placement_id, 'bundle_name' => $va_display_item['bundle_name'], 'display' => $vs_header, 'settings' => $va_settings);
             }
             $this->view->setVar('display_list', $va_display_list);
         } else {
             $this->postError(3100, _t("Invalid format %1", $ps_template), "FindController->_genExport()");
             return;
         }
         $va_template_info = caGetPrintTemplateDetails('results', 'display');
     } else {
         $this->postError(3100, _t("Invalid format %1", $ps_template), "FindController->_genExport()");
         return;
     }
     //
     // PDF output
     //
     if (!is_array($va_template_info)) {
         $this->postError(3110, _t("Could not find view for PDF"), "FindController->_genExport()");
         return;
     }
     try {
         $this->view->setVar('base_path', $vs_base_path = pathinfo($va_template_info['path'], PATHINFO_DIRNAME));
         $this->view->addViewPath(array($vs_base_path, "{$vs_base_path}/local"));
         set_time_limit(600);
         $vs_content = $this->render($va_template_info['path']);
         $o_dompdf = new DOMPDF();
         $o_dompdf->load_html($vs_content);
         $o_dompdf->set_paper(caGetOption('pageSize', $va_template_info, 'letter'), caGetOption('pageOrientation', $va_template_info, 'portrait'));
         $o_dompdf->set_base_path(caGetPrintTemplateDirectoryPath('results'));
         $o_dompdf->render();
         $o_dompdf->stream(caGetOption('filename', $va_template_info, 'export_results.pdf'));
         $vb_printed_properly = true;
     } catch (Exception $e) {
         $vb_printed_properly = false;
         $this->postError(3100, _t("Could not generate PDF"), "FindController->_genExport()");
     }
     return;
 }
 public function renderWidget($ps_widget_id, &$pa_settings)
 {
     parent::renderWidget($ps_widget_id, $pa_settings);
     $this->opo_view->setVar('request', $this->getRequest());
     $this->opo_view->setVar('hours', $pa_settings['hours']);
     $vo_tq = new TaskQueue();
     $qr_completed = $this->opo_db->query("\n\t\t\t\tSELECT tq.*, u.fname, u.lname \n\t\t\t\tFROM ca_task_queue tq \n\t\t\t\tLEFT JOIN ca_users u ON u.user_id = tq.user_id \n\t\t\t\tWHERE tq.completed_on > ? \n\t\t\t\tORDER BY tq.completed_on desc\n\t\t\t", time() - 60 * 60 * $pa_settings['hours']);
     $va_completed = array();
     while ($qr_completed->nextRow()) {
         $va_row = $qr_completed->getRow();
         $va_params = caUnserializeForDatabase($va_row["parameters"]);
         $va_completed[$va_row["task_id"]]["handler_name"] = $vo_tq->getHandlerName($va_row['handler']);
         $va_completed[$va_row["task_id"]]["created"] = $va_row["created_on"];
         $va_completed[$va_row["task_id"]]["by"] = $va_row["fname"] . ' ' . $va_row['lname'];
         $va_completed[$va_row["task_id"]]["completed_on"] = $va_row["completed_on"];
         $va_completed[$va_row["task_id"]]["error_code"] = $va_row["error_code"];
         if ((int) $va_row["error_code"] > 0) {
             $o_e = new ApplicationError((int) $va_row["error_code"], '', '', '', false, false);
             $va_row["error_message"] = $o_e->getErrorMessage();
         } else {
             $va_row["error_message"] = '';
         }
         $va_completed[$va_row["task_id"]]["error_message"] = $va_row["error_message"];
         if (is_array($va_report = caUnserializeForDatabase($va_row["notes"]))) {
             $va_completed[$va_row["task_id"]]["processing_time"] = (double) $va_report['processing_time'];
         }
         $va_completed[$va_row["task_id"]]["status"] = $vo_tq->getParametersForDisplay($va_row);
     }
     $this->opo_view->setVar('jobs_done', $qr_completed->numRows());
     $this->opo_view->setVar('jobs_done_data', $va_completed);
     $qr_qd = $this->opo_db->query("\n\t\t\t\tSELECT * \n\t\t\t\tFROM ca_task_queue tq\n\t\t\t\tLEFT JOIN ca_users AS u ON tq.user_id = u.user_id\n\t\t\t\tWHERE tq.completed_on is NULL\n\t\t\t");
     $this->opo_view->setVar('jobs_queued_processing', $qr_qd->numRows());
     $va_qd_jobs = array();
     $va_pr_jobs = array();
     while ($qr_qd->nextRow()) {
         $va_row = $qr_qd->getRow();
         $va_params = caUnserializeForDatabase($va_row["parameters"]);
         if (!$vo_tq->rowKeyIsBeingProcessed($va_row["row_key"])) {
             $va_qd_jobs[$va_row["task_id"]]["handler_name"] = $vo_tq->getHandlerName($va_row['handler']);
             $va_qd_jobs[$va_row["task_id"]]["created"] = $va_row["created_on"];
             $va_qd_jobs[$va_row["task_id"]]["by"] = $va_row["fname"] . ' ' . $va_row['lname'];
             $va_qd_jobs[$va_row["task_id"]]["status"] = $vo_tq->getParametersForDisplay($va_row);
         } else {
             $va_pr_jobs[$va_row["task_id"]]["handler_name"] = $vo_tq->getHandlerName($va_row['handler']);
             $va_pr_jobs[$va_row["task_id"]]["created"] = $va_row["created_on"];
             $va_pr_jobs[$va_row["task_id"]]["by"] = $va_row["fname"] . ' ' . $va_row['lname'];
             $va_pr_jobs[$va_row["task_id"]]["status"] = $vo_tq->getParametersForDisplay($va_row);
         }
     }
     $this->opo_view->setVar('qd_job_data', $va_qd_jobs);
     $this->opo_view->setVar('pr_job_data', $va_pr_jobs);
     $this->opo_view->setVar('update_frequency', ($vn_freq = (int) $this->opo_config->get('update_frequency')) ? $vn_freq : 60);
     return $this->opo_view->render('main_html.php');
 }
 public function getItems()
 {
     if (!$this->getPrimaryKey()) {
         return false;
     }
     $vo_db = $this->getDb();
     $qr_items = $vo_db->query("\n\t\t\tSELECT * \n\t\t\tFROM ca_data_importer_items \n\t\t\tWHERE importer_id = ?\n\t\t", $this->getPrimaryKey());
     $va_return = array();
     while ($qr_items->nextRow()) {
         $va_return[$qr_items->get("item_id")] = $qr_items->getRow();
         $va_return[$qr_items->get("item_id")]['settings'] = caUnserializeForDatabase($va_return[$qr_items->get("item_id")]['settings']);
     }
     return $va_return;
 }
 public static function process()
 {
     if (self::lockAcquire()) {
         $o_db = new Db();
         $o_result = $o_db->query("SELECT * FROM ca_search_indexing_queue ORDER BY entry_id");
         if ($o_result && $o_result->numRows()) {
             $o_si = new SearchIndexer($o_db);
             while ($o_result->nextRow()) {
                 if (!$o_result->get('is_unindex')) {
                     // normal indexRow() call
                     $o_si->indexRow($o_result->get('table_num'), $o_result->get('row_id'), caUnserializeForDatabase($o_result->get('field_data')), (bool) $o_result->get('reindex'), null, caUnserializeForDatabase($o_result->get('changed_fields')), array_merge(caUnserializeForDatabase($o_result->get('options')), array('queueIndexing' => false)));
                 } else {
                     // is_unindex = 1, so it's a commitRowUnindexing() call
                     $o_si->commitRowUnIndexing($o_result->get('table_num'), $o_result->get('row_id'), array('queueIndexing' => false, 'dependencies' => caUnserializeForDatabase($o_result->get('dependencies'))));
                 }
                 $o_db->query('DELETE FROM ca_search_indexing_queue WHERE entry_id=?', $o_result->get('entry_id'));
             }
         }
         self::lockRelease();
     }
 }
// object representation
$t_item_rel = $this->getVar('t_item_rel');
$t_subject = $this->getVar('t_subject');
// object
$vs_add_label = $this->getVar('add_label');
$vb_allow_fetching_from_urls = $this->request->getAppConfig()->get('allow_fetching_of_media_from_remote_urls');
// generate list of inital form values; the bundle Javascript call will
// use the template to generate the initial form
$va_inital_values = array();
$va_reps = $t_subject->getRepresentations(array('thumbnail', 'original'));
$va_rep_type_list = $t_item->getTypeList();
$va_errors = array();
if (sizeof($va_reps)) {
    foreach ($va_reps as $va_rep) {
        $vn_num_multifiles = $va_rep['num_multifiles'];
        $vs_extracted_metadata = caFormatMediaMetadata(caUnserializeForDatabase($va_rep['media_metadata']));
        $vs_md5 = isset($va_rep['info']['original']['MD5']) ? _t('MD5 signature') . ': ' . $va_rep['info']['original']['MD5'] : '';
        $va_inital_values[$va_rep['representation_id']] = array('status' => $va_rep['status'], 'access' => $va_rep['access'], 'is_primary' => $va_rep['is_primary'] == 1 ? true : false, 'locale_id' => $va_rep['locale_id'], 'icon' => $va_rep['tags']['thumbnail'], 'type' => $va_rep['info']['original']['PROPERTIES']['typename'], 'dimensions' => $va_rep['dimensions']['original'], 'filename' => $va_rep['info']['original_filename'], 'num_multifiles' => $vn_num_multifiles ? $vn_num_multifiles == 1 ? _t('+ 1 additional preview') : _t('+ %1 additional previews', $vn_num_multifiles) : '', 'metadata' => $vs_extracted_metadata, 'md5' => $vs_md5, 'type_id' => $va_rep['type_id'], 'typename' => $va_rep_type_list[$va_rep['type_id']]['name_singular'], 'fetched_from' => $va_rep['fetched_from'], 'fetched_on' => date('c', $va_rep['fetched_on']));
        if (is_array($va_action_errors = $this->request->getActionErrors('ca_object_representations', $va_rep['representation_id']))) {
            foreach ($va_action_errors as $o_error) {
                $va_errors[$va_rep['representation_id']][] = array('errorDescription' => $o_error->getErrorDescription(), 'errorCode' => $o_error->getErrorNumber());
            }
        }
    }
}
$va_failed_inserts = array();
foreach ($this->request->getActionErrorSubSources('ca_object_representations') as $vs_error_subsource) {
    if (substr($vs_error_subsource, 0, 4) === 'new_') {
        $va_action_errors = $this->request->getActionErrors('ca_object_representations', $vs_error_subsource);
        foreach ($va_action_errors as $o_error) {
            $va_failed_inserts[] = array('icon' => '', '_errors' => array(array('errorDescription' => $o_error->getErrorDescription(), 'errorCode' => $o_error->getErrorNumber())));
 /**
  *
  */
 public function useBlobAsMediaField($pb_setting)
 {
     $this->FIELDS['value_blob']['FIELD_TYPE'] = $pb_setting ? FT_MEDIA : FT_TEXT;
     // We have to deserialize the FT_MEDIA info array ourselves since when we loaded the attribute value model
     // BaseModel didn't know it was an FT_MEDIA field
     $this->_FIELD_VALUES['value_blob'] = caUnserializeForDatabase($this->_FIELD_VALUES['value_blob']);
 }
 /**
  * Returns list of placements for the currently loaded form.
  *
  * @param array $pa_options Optional array of options. Supports the following options:
  * 		noCache = if set to true then the returned list if always generated directly from the database, otherwise it is returned from the cache if possible. Set this to true if you expect the cache may be stale. Default is false.
  *		returnAllAvailableIfEmpty = if set to true then the list of all available bundles will be returned if the currently loaded form has no placements, or if there is no form loaded
  *		table = if using the returnAllAvailableIfEmpty option and you expect a list of available bundles to be returned if no form is loaded, you must specify the table the bundles are intended for use with with this option. Either the table name or number may be used.
  *		user_id = if specified then placements are only returned if the user has at least read access to the form
  * @return array List of placements in display order. Array is keyed on bundle name. Values are arrays with the following keys:
  *		placement_id = primary key of ca_search_form_placements row - a unique id for the placement
  *		bundle_name = bundle name (a code - not for form)
  *		settings = array of placement settings. Keys are setting names.
  *		form = form string for bundle
  */
 public function getPlacements($pa_options = null)
 {
     $pb_no_cache = isset($pa_options['noCache']) ? (bool) $pa_options['noCache'] : false;
     $pb_settings_only = isset($pa_options['settingsOnly']) ? (bool) $pa_options['settingsOnly'] : false;
     $pb_return_all_available_if_empty = isset($pa_options['returnAllAvailableIfEmpty']) && !$pb_settings_only ? (bool) $pa_options['returnAllAvailableIfEmpty'] : false;
     $ps_table = isset($pa_options['table']) ? $pa_options['table'] : null;
     $pn_user_id = isset($pa_options['user_id']) ? $pa_options['user_id'] : null;
     if ($pn_user_id && !$this->haveAccessToForm($pn_user_id, __ca_search_form_READ_ACCESS__)) {
         return array();
     }
     if (!($vn_form_id = $this->getPrimaryKey())) {
         if ($pb_return_all_available_if_empty && $ps_table) {
             return ca_search_forms::$s_placement_list_cache[$vn_form_id] = $this->getAvailableBundles($ps_table);
         }
         return array();
     }
     if (!$pb_no_cache && isset(ca_search_forms::$s_placement_list_cache[$vn_form_id]) && ca_search_forms::$s_placement_list_cache[$vn_form_id]) {
         return ca_search_forms::$s_placement_list_cache[$vn_form_id];
     }
     $o_db = $this->getDb();
     $qr_res = $o_db->query("\n\t\t\tSELECT placement_id, bundle_name, settings\n\t\t\tFROM ca_search_form_placements\n\t\t\tWHERE\n\t\t\t\tform_id = ?\n\t\t\tORDER BY rank\n\t\t", (int) $vn_form_id);
     $va_available_bundles = $pb_settings_only ? array() : $this->getAvailableBundles();
     $va_placements = array();
     if ($qr_res->numRows() > 0) {
         $t_placement = new ca_search_form_placements();
         while ($qr_res->nextRow()) {
             $vs_bundle_name = $qr_res->get('bundle_name');
             $va_placements[$vn_placement_id = (int) $qr_res->get('placement_id')] = $qr_res->getRow();
             $va_placements[$vn_placement_id]['settings'] = $va_settings = caUnserializeForDatabase($qr_res->get('settings'));
             if (!$pb_settings_only) {
                 $t_placement->setSettingDefinitionsForPlacement($va_available_bundles[$vs_bundle_name]['settings']);
                 $va_placements[$vn_placement_id]['form'] = $va_available_bundles[$vs_bundle_name]['form'];
                 $va_placements[$vn_placement_id]['settingsForm'] = $t_placement->getHTMLSettingForm(array('id' => $vs_bundle_name . '_' . $vn_placement_id, 'settings' => $va_settings));
             }
         }
     } else {
         if ($pb_return_all_available_if_empty) {
             $va_placements = $this->getAvailableBundles($this->get('table_num'));
         }
     }
     ca_search_forms::$s_placement_list_cache[$vn_form_id] = $va_placements;
     return $va_placements;
 }
 /**
  *
  */
 public function getRecentChangesAsRawData($pn_table_num, $pn_num_seconds = 604800, $pn_limit = 0)
 {
     // 604800 = number of seconds in one week
     $o_db = new Db();
     $qs_log = $o_db->prepare("\n\t\t\tSELECT DISTINCT\n\t\t\t\twcl.log_id, wcl.log_datetime log_datetime, wcl.user_id, wcl.changetype, wcl.logged_table_num, wcl.logged_row_id,\n\t\t\t\twclsnap.snapshot, wcl.unit_id, wu.email, wu.fname, wu.lname, wcls.subject_table_num, wcls.subject_row_id\n\t\t\tFROM " . $this->ops_change_log_database . ".ca_change_log wcl\n\t\t\tINNER JOIN " . $this->ops_change_log_database . ".ca_change_log_snapshots AS wclsnap ON wclsnap.log_id = wcl.log_id\n\t\t\tLEFT JOIN " . $this->ops_change_log_database . ".ca_change_log_subjects AS wcls ON wcl.log_id = wcls.log_id\n\t\t\tLEFT JOIN ca_users AS wu ON wcl.user_id = wu.user_id\n\t\t\tWHERE\n\t\t\t\t(\n\t\t\t\t\t((wcl.logged_table_num = ?) AND (wcls.subject_table_num IS NULL))\n\t\t\t\t\tOR\n\t\t\t\t\t(wcls.subject_table_num = ?)\n\t\t\t\t)\n\t\t\t\tAND (wcl.log_datetime > ?)\n\t\t\tORDER BY wcl.log_datetime DESC\n\t\t");
     if ($pn_limit > 0) {
         $qs_log->setLimit($pn_limit);
     }
     if ($qr_res = $qs_log->execute($pn_table_num, $pn_table_num, time() - $pn_num_seconds)) {
         $va_log = array();
         while ($qr_res->nextRow()) {
             $va_log[] = $qr_res->getRow();
             $va_log[sizeof($va_log) - 1]['snapshot'] = caUnserializeForDatabase($va_log[sizeof($va_log) - 1]['snapshot']);
         }
         return array_reverse($va_log);
     }
     return array();
 }
 /**
  * Returns list of placements for the currently loaded screen.
  *
  * @param array $pa_options Optional array of options. Supports the following options:
  * 		noCache = if set to true then the returned list if always generated directly from the database, otherwise it is returned from the cache if possible. Set this to true if you expect the cache may be stale. Default is false.
  *		returnAllAvailableIfEmpty = if set to true then the list of all available bundles will be returned if the currently loaded screen has no placements, or if there is no display loaded
  *		table = if using the returnAllAvailableIfEmpty option and you expect a list of available bundles to be returned if no display is loaded, you must specify the table the bundles are intended for use with with this option. Either the table name or number may be used.
  *		user_id = if specified then placements are only returned if the user has at least read access to the display
  * @return array List of placements in display order. Array is keyed on bundle name. Values are arrays with the following keys:
  *		placement_id = primary key of ca_editor_ui_bundle_placements row - a unique id for the placement
  *		bundle_name = bundle name (a code - not for display)
  *		settings = array of placement settings. Keys are setting names.
  *		display = display string for bundle
  */
 public function getPlacements($pa_options = null)
 {
     $pb_no_cache = isset($pa_options['noCache']) ? (bool) $pa_options['noCache'] : false;
     $pb_settings_only = isset($pa_options['settingsOnly']) ? (bool) $pa_options['settingsOnly'] : false;
     $pb_return_all_available_if_empty = isset($pa_options['returnAllAvailableIfEmpty']) && !$pb_settings_only ? (bool) $pa_options['returnAllAvailableIfEmpty'] : false;
     $ps_table = isset($pa_options['table']) ? $pa_options['table'] : $this->getTableNum();
     $pn_user_id = isset($pa_options['user_id']) ? $pa_options['user_id'] : null;
     //if ($pn_user_id && !$this->haveAccessToDisplay($pn_user_id, __CA_BUNDLE_DISPLAY_READ_ACCESS__)) {
     //	return array();
     //}
     if (!($vn_screen_id = $this->getPrimaryKey())) {
         if ($pb_return_all_available_if_empty && $ps_table) {
             return ca_editor_ui_screens::$s_placement_list_cache[$vn_screen_id] = $this->getAvailableBundles($ps_table);
         }
         //	return array();
     }
     if (!$pb_no_cache && isset(ca_editor_ui_screens::$s_placement_list_cache[$vn_screen_id]) && ca_editor_ui_screens::$s_placement_list_cache[$vn_screen_id]) {
         return ca_editor_ui_screens::$s_placement_list_cache[$vn_screen_id];
     }
     $o_db = $this->getDb();
     $qr_res = $o_db->query("\n\t\t\tSELECT placement_id, bundle_name, placement_code, settings\n\t\t\tFROM ca_editor_ui_bundle_placements\n\t\t\tWHERE\n\t\t\t\tscreen_id = ?\n\t\t\tORDER BY rank\n\t\t", (int) $vn_screen_id);
     $va_available_bundles = $pb_settings_only ? array() : $this->getAvailableBundles();
     $va_placements = array();
     if ($qr_res->numRows() > 0) {
         $t_placement = new ca_editor_ui_bundle_placements();
         while ($qr_res->nextRow()) {
             $vs_bundle_name = $qr_res->get('bundle_name');
             $va_placements[$vn_placement_id = (int) $qr_res->get('placement_id')] = $qr_res->getRow();
             $va_placements[$vn_placement_id]['settings'] = $va_settings = caUnserializeForDatabase($qr_res->get('settings'));
             if (!$pb_settings_only) {
                 $t_placement->setSettingDefinitionsForPlacement($va_available_bundles[$vs_bundle_name]['settings']);
                 $va_placements[$vn_placement_id]['display'] = $va_available_bundles[$vs_bundle_name]['display'];
                 $va_placements[$vn_placement_id]['settingsForm'] = $t_placement->getHTMLSettingForm(array('id' => $vs_bundle_name . '_' . $vn_placement_id, 'settings' => $va_settings));
             } else {
                 $va_tmp = explode('.', $vs_bundle_name);
                 $t_instance = $this->_DATAMODEL->getInstanceByTableName($va_tmp[0], true);
                 $va_placements[$vn_placement_id]['display'] = $t_instance ? $t_instance->getDisplayLabel($vs_bundle_name) : "???";
             }
         }
     } else {
         if ($pb_return_all_available_if_empty) {
             $va_placements = $this->getAvailableBundles($this->getTableNum());
         }
     }
     ca_editor_ui_screens::$s_placement_list_cache[$vn_screen_id] = $va_placements;
     return $va_placements;
 }
 /** 
  * Set up basic "find" action
  */
 public function Index($pa_options = null)
 {
     $po_search = isset($pa_options['search']) ? $pa_options['search'] : null;
     $t_model = $this->opo_datamodel->getInstanceByTableName($this->ops_tablename, true);
     $vn_display_id = $this->opo_result_context->getCurrentBundleDisplay();
     // Make sure user has access to at least one type
     if (method_exists($t_model, 'getTypeFieldName') && $t_model->getTypeFieldName() && (!is_null($va_types = caGetTypeListForUser($this->ops_tablename, array('access' => __CA_BUNDLE_ACCESS_READONLY__))) && (is_array($va_types) && !sizeof($va_types)))) {
         $this->response->setRedirect($this->request->config->get('error_display_url') . '/n/2320?r=' . urlencode($this->request->getFullUrlPath()));
         return;
     }
     $va_display_list = array();
     $t_display = $this->opo_datamodel->getInstanceByTableName('ca_bundle_displays', true);
     $t_display->load($vn_display_id);
     $vs_view = $this->opo_result_context->getCurrentView();
     if ($vn_display_id && $t_display->haveAccessToDisplay($this->request->getUserID(), __CA_BUNDLE_DISPLAY_READ_ACCESS__)) {
         $va_placements = $t_display->getPlacements(array('settingsOnly' => true));
         foreach ($va_placements as $vn_placement_id => $va_display_item) {
             $va_settings = caUnserializeForDatabase($va_display_item['settings']);
             // get column header text
             $vs_header = $va_display_item['display'];
             if (isset($va_settings['label']) && is_array($va_settings['label'])) {
                 $va_tmp = caExtractValuesByUserLocale(array($va_settings['label']));
                 if ($vs_tmp = array_shift($va_tmp)) {
                     $vs_header = $vs_tmp;
                 }
             }
             $va_display_list[$vn_placement_id] = array('placement_id' => $vn_placement_id, 'bundle_name' => $va_display_item['bundle_name'], 'display' => $vs_header, 'settings' => $va_settings);
             if ($vs_view == 'editable') {
                 $va_display_list[$vn_placement_id] = array_merge($va_display_list[$vn_placement_id], array('allowInlineEditing' => $va_display_item['allowInlineEditing'], 'inlineEditingType' => $va_display_item['inlineEditingType'], 'inlineEditingListValues' => $va_display_item['inlineEditingListValues']));
                 AssetLoadManager::register('panel');
             }
         }
     }
     //
     // Default display list (if none are specifically defined)
     //
     if (!sizeof($va_display_list)) {
         if ($vs_idno_fld = $t_model->getProperty('ID_NUMBERING_ID_FIELD')) {
             $va_display_list[$this->ops_tablename . '.' . $vs_idno_fld] = array('placement_id' => $this->ops_tablename . '.' . $vs_idno_fld, 'bundle_name' => $this->ops_tablename . '.' . $vs_idno_fld, 'display' => $t_model->getDisplayLabel($this->ops_tablename . '.' . $vs_idno_fld), 'settings' => array(), 'allowInlineEditing' => true, 'inlineEditingType' => DT_FIELD, 'inlineEditingListValues' => array());
         }
         if (method_exists($t_model, 'getLabelTableInstance') && !($this->ops_tablename === 'ca_objects' && $this->request->config->get('ca_objects_dont_use_labels'))) {
             $t_label = $t_model->getLabelTableInstance();
             $va_display_list[$this->ops_tablename . '.preferred_labels'] = array('placement_id' => $this->ops_tablename . '.preferred_labels', 'bundle_name' => $this->ops_tablename . '.preferred_labels', 'display' => $t_label->getDisplayLabel($t_label->tableName() . '.' . $t_label->getDisplayField()), 'settings' => array(), 'allowInlineEditing' => true, 'inlineEditingType' => DT_FIELD, 'inlineEditingListValues' => array());
         }
         if ($vs_view == 'editable') {
             AssetLoadManager::register('panel');
         }
     }
     $this->view->setVar('current_display_list', $vn_display_id);
     $this->view->setVar('t_display', $t_display);
     if ($vs_view == 'editable') {
         $this->view->setVar('columns', $this->getInlineEditColumns($va_display_list, array('request' => $this->request)));
         $this->view->setVar('columnHeaders', caExtractValuesFromArrayList($va_display_list, 'display', array('preserveKeys' => false)));
         $this->view->setVar('rowHeaders', array());
     }
     // figure out which items in the display are sortable
     if (method_exists($t_model, 'getApplicableElementCodes')) {
         $va_sortable_elements = ca_metadata_elements::getSortableElements($t_model->tableName());
         $va_attribute_list = array_flip($t_model->getApplicableElementCodes($this->opo_result_context->getTypeRestriction($vb_dummy), false, false));
         $t_label = $t_model->getLabelTableInstance();
         $vs_label_table_name = $t_label->tableName();
         $vs_label_display_field = $t_label->getDisplayField();
         foreach ($va_display_list as $vn_i => $va_display_item) {
             $va_tmp = explode('.', $va_display_item['bundle_name']);
             if ($va_tmp[0] === $vs_label_table_name && $va_tmp[1] === $vs_label_display_field || $va_tmp[0] == $this->ops_tablename && $va_tmp[1] === 'preferred_labels') {
                 $va_display_list[$vn_i]['is_sortable'] = true;
                 $va_display_list[$vn_i]['bundle_sort'] = $vs_label_table_name . '.' . $vs_label_display_field;
                 continue;
             }
             if ($va_tmp[0] != $this->ops_tablename) {
                 continue;
             }
             if ($t_model->hasField($va_tmp[1])) {
                 $va_display_list[$vn_i]['is_sortable'] = true;
                 if ($t_model->hasField($va_tmp[1] . '_sort')) {
                     $va_display_list[$vn_i]['bundle_sort'] = $va_display_item['bundle_name'] . '_sort';
                 } else {
                     $va_display_list[$vn_i]['bundle_sort'] = $va_display_item['bundle_name'];
                 }
                 continue;
             }
             if (isset($va_attribute_list[$va_tmp[1]]) && $va_sortable_elements[$va_attribute_list[$va_tmp[1]]]) {
                 $va_display_list[$vn_i]['is_sortable'] = true;
                 $va_display_list[$vn_i]['bundle_sort'] = $va_display_item['bundle_name'];
                 continue;
             }
         }
     }
     $this->view->setVar('display_list', $va_display_list);
     // Get current display list
     $va_displays = array('0' => _t('Default'));
     foreach (caExtractValuesByUserLocale($t_display->getBundleDisplays(array('table' => $this->ops_tablename, 'user_id' => $this->request->getUserID(), 'access' => __CA_BUNDLE_DISPLAY_READ_ACCESS__))) as $va_display) {
         $va_displays[$va_display['display_id']] = $va_display['name'];
     }
     $this->view->setVar('display_lists', $va_displays);
     # --- print forms used for printing search results as labels - in tools show hide under page bar
     if ((bool) $this->request->config->get('use_legacy_print_labels_generator')) {
         $this->view->setVar('label_formats', $this->getLegacyPrintForms());
     } else {
         $this->view->setVar('label_formats', caGetAvailablePrintTemplates('labels', array('table' => $this->ops_tablename, 'type' => 'label')));
     }
     # --- export options used to export search results - in tools show hide under page bar
     $vn_table_num = $this->opo_datamodel->getTableNum($this->ops_tablename);
     //default export formats, not configureable
     $va_export_options = array(array('name' => _t('Tab delimited'), 'code' => '_tab'), array('name' => _t('Comma delimited (CSV)'), 'code' => '_csv'), array('name' => _t('Spreadsheet with media icons (XLSX)'), 'code' => '_xlsx'));
     // merge default formats with drop-in print templates
     $va_export_options = array_merge($va_export_options, caGetAvailablePrintTemplates('results', array('table' => $this->ops_tablename)));
     $this->view->setVar('export_formats', $va_export_options);
     $this->view->setVar('current_export_format', $this->opo_result_context->getParameter('last_export_type'));
     //
     // Available sets
     //
     $t_set = new ca_sets();
     $this->view->setVar('available_sets', caExtractValuesByUserLocale($t_set->getSets(array('table' => $this->ops_tablename, 'user_id' => $this->request->getUserID(), 'access' => __CA_SET_EDIT_ACCESS__, 'omitCounts' => true))));
     if (strlen($this->ops_tablename) > 0) {
         if (!$this->request->user->canDoAction("can_edit_{$this->ops_tablename}")) {
             $this->view->setVar("default_action", "Summary");
         } else {
             $this->view->setVar("default_action", "Edit");
         }
     }
     $this->view->setVar('result_context', $this->opo_result_context);
     $this->view->setVar('access_restrictions', AccessRestrictions::load());
 }
Exemple #26
0
 /**
  * Returns information on items in current set
  *
  * @param array $pa_options Optional array of options. Supported options are:
  *			user_id = user_id of the current user; used to determine paintings may be shown
  *			thumbnailVersions = A list of of a media versions to return with each item. Only used if the set content type is ca_objects.
  *			thumbnailVersion = Same as 'thumbnailVersions' except it is a single value. (Maintained for compatibility with older code.)
  *			limit = Limits the total number of records to be returned
  *			checkAccess = An array of row-level access values to check set members for, often produced by the caGetUserAccessValues() helper. Set members with access values not in the list will be omitted. If this option is not set or left null no access checking is done.
  *			returnRowIdsOnly = If true a simple array of row_ids (keys of the set members) for members of the set is returned rather than full item-level info for each set member.
  *			returnItemIdsOnly = If true a simple array of item_ids (keys for the ca_set_items rows themselves) is returned rather than full item-level info for each set member.
  *			returnItemAttributes = A list of attribute element codes for the ca_set_item record to return values for.
  * @return array An array of items. The format varies depending upon the options set. If returnRowIdsOnly or returnItemIdsOnly are set then the returned array is a 
  *			simple list of ids. The full return array is key'ed on ca_set_items.item_id and then on locale_id. The values are arrays with keys set to a number of fields including:
  *			set_id, item_id, row_id, rank, label_id, locale_id, caption (from the ca_set_items label), all instrinsic field content from the row_id, the display label of the row
  *			as 'set_item_label'. 
  *			If 'thumbnailVersion' is set then additional keys will be available for the selected media version:
  *				representation_tag, representation_url, representation_width and representation_height (the HTML tag, URL, pixel width and pixel height of the representation respectively)
  *			If 'thumbnailVersions' is set then additional keys will be available for the selected media versions:
  *				representation_tag_<version_name>, representation_url_<version_name>, representation_width_<version_name> and representation_height_<version_name> (the HTML tag, URL, pixel width and pixel height of the representation respectively)
  *			If 'returnItemAttributes' is set then there will be an additional key for each element_code prefixed with 'ca_attribute_' to ensure it doesn't conflict with any other key in the array.		
  *			
  */
 public function getItems($pa_options = null)
 {
     if (!($vn_set_id = $this->getPrimaryKey())) {
         return null;
     }
     if (!is_array($pa_options)) {
         $pa_options = array();
     }
     if ($pa_options['user_id'] && !$this->haveAccessToSet($pa_options['user_id'], __CA_SET_READ_ACCESS__)) {
         return false;
     }
     $o_db = $this->getDb();
     $o_dm = $this->getAppDatamodel();
     $t_rel_label_table = null;
     if (!($t_rel_table = $o_dm->getInstanceByTableNum($this->get('table_num'), true))) {
         return null;
     }
     if (method_exists($t_rel_table, 'getLabelTableName')) {
         if ($vs_label_table_name = $t_rel_table->getLabelTableName()) {
             $t_rel_label_table = $o_dm->getInstanceByTableName($vs_label_table_name, true);
         }
     }
     $vs_label_join_sql = '';
     if ($t_rel_label_table) {
         if ($t_rel_label_table->hasField("is_preferred")) {
             $vs_preferred_sql = " AND rel_label.is_preferred = 1 ";
         }
         $vs_label_join_sql = "LEFT JOIN " . $t_rel_label_table->tableName() . " AS rel_label ON rel." . $t_rel_table->primaryKey() . " = rel_label." . $t_rel_table->primaryKey() . " {$vs_preferred_sql}\n";
     }
     $vs_limit_sql = '';
     if (isset($pa_options['limit']) && $pa_options['limit'] > 0) {
         $vs_limit_sql = "LIMIT " . $pa_options['limit'];
     }
     // get set items
     $vs_access_sql = '';
     if (isset($pa_options['checkAccess']) && is_array($pa_options['checkAccess']) && sizeof($pa_options['checkAccess']) && $t_rel_table->hasField('access')) {
         $vs_access_sql = ' AND rel.access IN (' . join(',', $pa_options['checkAccess']) . ')';
     }
     $vs_deleted_sql = '';
     if ($t_rel_table->hasField('deleted')) {
         $vs_deleted_sql = ' AND rel.deleted = 0';
     }
     $va_representation_counts = array();
     $vs_rep_join_sql = $vs_rep_where_sql = $vs_rep_select = '';
     if ($t_rel_table->tableName() === 'ca_objects' && (isset($pa_options['thumbnailVersion']) || isset($pa_options['thumbnailVersions']))) {
         $vs_rep_join_sql = "LEFT JOIN ca_objects_x_object_representations AS coxor ON rel.object_id = coxor.object_id\nLEFT JOIN ca_object_representations AS cor ON coxor.representation_id = cor.representation_id\n";
         $vs_rep_where_sql = " AND (coxor.is_primary = 1 OR coxor.is_primary IS NULL)";
         $vs_rep_select = ', coxor.*, cor.media, cor.access rep_access';
         // get representation counts
         $qr_rep_counts = $o_db->query("\n\t\t\t\tSELECT \n\t\t\t\t\trel.object_id, count(*) c\n\t\t\t\tFROM ca_set_items casi\n\t\t\t\tINNER JOIN ca_objects AS rel ON rel.object_id = casi.row_id\n\t\t\t\tINNER JOIN ca_objects_x_object_representations AS coxor ON coxor.object_id = rel.object_id\n\t\t\t\tWHERE\n\t\t\t\t\tcasi.set_id = ? {$vs_access_sql} {$vs_deleted_sql}\n\t\t\t\tGROUP BY\n\t\t\t\t\trel.object_id\n\t\t\t", (int) $vn_set_id);
         while ($qr_rep_counts->nextRow()) {
             $va_representation_counts[(int) $qr_rep_counts->get('object_id')] = (int) $qr_rep_counts->get('c');
         }
     }
     // get row labels
     $qr_res = $o_db->query("\n\t\t\tSELECT \n\t\t\t\tcasi.set_id, casi.item_id, casi.row_id, casi.rank,\n\t\t\t\trel_label." . $t_rel_label_table->getDisplayField() . ", rel_label.locale_id\n\t\t\tFROM ca_set_items casi\n\t\t\tINNER JOIN " . $t_rel_table->tableName() . " AS rel ON rel." . $t_rel_table->primaryKey() . " = casi.row_id\n\t\t\t{$vs_label_join_sql}\n\t\t\tWHERE\n\t\t\t\tcasi.set_id = ? {$vs_access_sql} {$vs_deleted_sql}\n\t\t\tORDER BY \n\t\t\t\tcasi.rank ASC\n\t\t\t{$vs_limit_sql}\n\t\t", (int) $vn_set_id);
     $va_labels = array();
     while ($qr_res->nextRow()) {
         $va_labels[$qr_res->get('row_id')][$qr_res->get('locale_id')] = $qr_res->getRow();
     }
     $va_labels = caExtractValuesByUserLocale($va_labels);
     // get set items
     $vs_access_sql = '';
     if (isset($pa_options['checkAccess']) && is_array($pa_options['checkAccess']) && sizeof($pa_options['checkAccess']) && $t_rel_table->hasField('access')) {
         $vs_access_sql = ' AND rel.access IN (' . join(',', $pa_options['checkAccess']) . ')';
     }
     $qr_res = $o_db->query("\n\t\t\tSELECT \n\t\t\t\tcasi.set_id, casi.item_id, casi.row_id, casi.rank, casi.vars,\n\t\t\t\tcasil.label_id, casil.caption, casil.locale_id set_item_label_locale_id,\n\t\t\t\trel.*, rel_label." . $t_rel_label_table->getDisplayField() . " set_item_label, rel_label.locale_id rel_locale_id\n\t\t\t\t{$vs_rep_select}\n\t\t\tFROM ca_set_items casi\n\t\t\tLEFT JOIN ca_set_item_labels AS casil ON casi.item_id = casil.item_id\n\t\t\tINNER JOIN " . $t_rel_table->tableName() . " AS rel ON rel." . $t_rel_table->primaryKey() . " = casi.row_id\n\t\t\t{$vs_label_join_sql}\n\t\t\t{$vs_rep_join_sql}\n\t\t\tWHERE\n\t\t\t\tcasi.set_id = ? {$vs_rep_where_sql} {$vs_access_sql} {$vs_deleted_sql}\n\t\t\tORDER BY \n\t\t\t\tcasi.rank ASC\n\t\t\t{$vs_limit_sql}\n\t\t", (int) $vn_set_id);
     $va_items = array();
     while ($qr_res->nextRow()) {
         $va_row = $qr_res->getRow();
         unset($va_row['media']);
         if (isset($pa_options['returnRowIdsOnly']) && $pa_options['returnRowIdsOnly']) {
             $va_items[$qr_res->get('row_id')] = true;
             continue;
         }
         if (isset($pa_options['returnItemIdsOnly']) && $pa_options['returnItemIdsOnly']) {
             $va_items[$qr_res->get('item_id')] = true;
             continue;
         }
         $va_vars = caUnserializeForDatabase($va_row['vars']);
         $vb_has_access_to_media = true;
         if ($vs_rep_join_sql && isset($pa_options['checkAccess']) && is_array($pa_options['checkAccess']) && sizeof($pa_options['checkAccess'])) {
             $vb_has_access_to_media = in_array($va_row['rep_access'], $pa_options['checkAccess']);
         }
         if ($vs_rep_join_sql && $vb_has_access_to_media) {
             if (isset($pa_options['thumbnailVersion'])) {
                 $va_row['representation_tag'] = $qr_res->getMediaTag('media', $pa_options['thumbnailVersion']);
                 $va_row['representation_url'] = $qr_res->getMediaUrl('media', $pa_options['thumbnailVersion']);
                 $va_row['representation_width'] = $qr_res->getMediaInfo('media', $pa_options['thumbnailVersion'], 'WIDTH');
                 $va_row['representation_height'] = $qr_res->getMediaInfo('media', $pa_options['thumbnailVersion'], 'HEIGHT');
             }
             if (isset($pa_options['thumbnailVersions']) && is_array($pa_options['thumbnailVersions'])) {
                 foreach ($pa_options['thumbnailVersions'] as $vs_version) {
                     $va_row['representation_tag_' . $vs_version] = $qr_res->getMediaTag('media', $vs_version);
                     $va_row['representation_url_' . $vs_version] = $qr_res->getMediaUrl('media', $vs_version);
                     $va_row['representation_width_' . $vs_version] = $qr_res->getMediaInfo('media', $vs_version, 'WIDTH');
                     $va_row['representation_height_' . $vs_version] = $qr_res->getMediaInfo('media', $vs_version, 'HEIGHT');
                 }
             }
         }
         if ($t_rel_table->tableName() === 'ca_objects') {
             if (isset($va_vars['selected_services'])) {
                 $va_row['selected_services'] = array_keys($va_vars['selected_services']);
             } else {
                 $va_row['selected_services'] = array();
             }
             if (isset($va_vars['selected_representations'])) {
                 $va_row['selected_representations'] = array_keys($va_vars['selected_representations']);
             } else {
                 $va_row['selected_representations'] = array();
             }
             $va_row['representation_count'] = (int) $va_representation_counts[$qr_res->get('row_id')];
         }
         $va_row = array_merge($va_row, $va_labels[$qr_res->get('row_id')]);
         if (isset($pa_options['returnItemAttributes']) && is_array($pa_options['returnItemAttributes']) && sizeof($pa_options['returnItemAttributes'])) {
             // TODO: doing a load for each item is inefficient... must replace with a query
             $t_item = new ca_set_items($va_row['item_id']);
             foreach ($pa_options['returnItemAttributes'] as $vs_element_code) {
                 $va_row['ca_attribute_' . $vs_element_code] = $t_item->getAttributesForDisplay($vs_element_code);
             }
             $va_row['set_item_label'] = $t_item->getLabelForDisplay(false);
         }
         $va_items[$qr_res->get('item_id')][$qr_res->get('rel_locale_id') ? $qr_res->get('rel_locale_id') : 0] = $va_row;
     }
     return $va_items;
 }
Exemple #27
0
 /**
  * Get the value of a field in the current row.
  * Possible keys in the options array:
  * binary, unserialize, convertHTMLBreaks, urlEncode, filterHTMLSpecialCharacters, escapeForXML, stripSlashes
  *
  * @param string $ps_field field name
  * @param array $pa_options associative array of options, keys are names of the options, values are boolean.
  * @return mixed
  */
 function get($ps_field, $pa_options = null)
 {
     $va_field = isset(DbResult::$s_field_info_cache[$ps_field]) ? DbResult::$s_field_info_cache[$ps_field] : $this->getFieldInfo($ps_field);
     if (!isset($this->opa_current_row[$va_field["field"]])) {
         return null;
     }
     $vs_val = isset($this->opa_current_row[$va_field["field"]]) ? $this->opa_current_row[$va_field["field"]] : null;
     if (isset($pa_options["binary"]) && $pa_options["binary"]) {
         return $vs_val;
     }
     if (isset($pa_options["unserialize"]) && $pa_options["unserialize"]) {
         if (!isset($this->opa_unserialized_cache[$va_field["field"]]) || !($vm_data = $this->opa_unserialized_cache[$va_field["field"]])) {
             $vm_data = caUnserializeForDatabase($vs_val);
             $this->opa_unserialized_cache[$va_field["field"]] =& $vm_data;
         }
         return $vm_data;
     }
     if (isset($pa_options["convertHTMLBreaks"]) && $pa_options["convertHTMLBreaks"]) {
         # check for tags before converting breaks
         preg_match_all("/<[A-Za-z0-9]+/", $vs_val, $va_tags);
         $va_ok_tags = array("<b", "<i", "<u", "<strong", "<em", "<strike", "<sub", "<sup", "<a", "<img", "<span");
         $vb_convert_breaks = true;
         foreach ($va_tags[0] as $vs_tag) {
             if (!in_array($vs_tag, $va_ok_tags)) {
                 $vb_convert_breaks = false;
                 break;
             }
         }
         if ($vb_convert_breaks) {
             $vs_val = preg_replace("/(\n|\r\n){2}/", "<p/>", $vs_val);
             $vs_val = ereg_replace("\n", "<br/>", $vs_val);
         }
     }
     if (isset($pa_options["urlEncode"]) && $pa_options["urlEncode"]) {
         $vs_val = urlEncode($vs_val);
     }
     if (isset($pa_options["filterHTMLSpecialCharacters"]) && $pa_options["filterHTMLSpecialCharacters"]) {
         $vs_val = htmlentities(html_entity_decode($vs_val));
     }
     if (isset($pa_options["escapeForXML"]) && $pa_options["escapeForXML"]) {
         $vs_val = caEscapeForXML($vs_val);
     }
     if (get_magic_quotes_gpc() || $pa_options["stripSlashes"]) {
         $vs_val = stripSlashes($vs_val);
     }
     return $vs_val;
 }
Exemple #28
0
 public function getSetChangeLog($va_set_ids)
 {
     if (is_array($va_set_ids) && sizeof($va_set_ids)) {
         $o_dm = $this->getAppDatamodel();
         $o_db = $this->getDB();
         // 			$q_change_log_sets = $o_db->query("
         // 						SELECT DISTINCT
         // 							wcl.log_id, wcl.log_datetime, wcl.user_id, wcl.changetype, wcl.logged_table_num, wcl.logged_row_id,
         // 							wclsnap.snapshot, wcl.unit_id, wu.email, wu.fname, wu.lname
         // 						FROM ca_change_log wcl
         // 						INNER JOIN ca_change_log_snapshots AS wclsnap ON wclsnap.log_id = wcl.log_id
         // 						LEFT JOIN ca_change_log_subjects AS wcls ON wcl.log_id = wcls.log_id
         // 						LEFT JOIN ca_users AS wu ON wcl.user_id = wu.user_id
         // 						WHERE
         // 							(
         // 								(wcl.logged_table_num = ".((int)$o_dm->getTableNum("ca_set_items")).") AND (wcl.logged_row_id IN (".implode(", ", $va_set_ids)."))
         // 							)
         // 						ORDER BY wcl.log_datetime desc
         // 					");
         // 				$va_set_change_log = array();
         // 				if($q_change_log_sets->numRows()){
         // 					while($q_change_log_sets->nextRow()){
         // 						$va_tmp = array();
         // 						$va_tmp = $q_change_log_sets->getRow();
         // 						$va_tmp['snapshot'] = caUnserializeForDatabase($q_change_log_sets->get('snapshot'));
         // 						$va_set_change_log[$q_change_log_sets->get('log_datetime')] = $va_tmp;
         // 					}
         // 				}
         global $g_ui_locale_id;
         $q_change_log = $o_db->query("\n\t\t\t\t\t\tSELECT DISTINCT\n\t\t\t\t\t\t\twcl.log_id, wcl.log_datetime log_datetime, wcl.user_id, wcl.changetype, wcl.logged_table_num, wcl.logged_row_id,\n\t\t\t\t\t\t\twclsnap.snapshot, wcl.unit_id, wu.email, wu.fname, wu.lname, csl.name, wcl.logged_row_id set_id\n\t\t\t\t\t\tFROM ca_change_log wcl\n\t\t\t\t\t\tINNER JOIN ca_change_log_snapshots AS wclsnap ON wclsnap.log_id = wcl.log_id\n\t\t\t\t\t\tLEFT JOIN ca_change_log_subjects AS wcls ON wcl.log_id = wcls.log_id\n\t\t\t\t\t\tLEFT JOIN ca_users AS wu ON wcl.user_id = wu.user_id\n\t\t\t\t\t\tINNER JOIN ca_set_labels AS csl ON csl.set_id = wcl.logged_row_id\n\t\t\t\t\t\tWHERE\n\t\t\t\t\t\t\t(\n\t\t\t\t\t\t\t\t(wcl.logged_table_num = " . (int) $this->tableNum() . ") AND (wcl.logged_row_id IN (" . implode(", ", $va_set_ids) . "))\n\t\t\t\t\t\t\t\tAND (csl.locale_id = ?)\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\tUNION\n\t\t\t\t\t\tSELECT DISTINCT\n\t\t\t\t\t\t\twcl.log_id, wcl.log_datetime, wcl.user_id, wcl.changetype, wcl.logged_table_num, wcl.logged_row_id,\n\t\t\t\t\t\t\twclsnap.snapshot, wcl.unit_id, wu.email, wu.fname, wu.lname, csl.name, wcls.subject_row_id set_id\n\t\t\t\t\t\tFROM ca_change_log wcl\n\t\t\t\t\t\tINNER JOIN ca_change_log_snapshots AS wclsnap ON wclsnap.log_id = wcl.log_id\n\t\t\t\t\t\tLEFT JOIN ca_change_log_subjects AS wcls ON wcl.log_id = wcls.log_id\n\t\t\t\t\t\tLEFT JOIN ca_users AS wu ON wcl.user_id = wu.user_id\n\t\t\t\t\t\tINNER JOIN ca_set_labels AS csl ON csl.set_id = wcls.subject_row_id\n\t\t\t\t\t\tWHERE\n\t\t\t\t\t\t\t (\n\t\t\t\t\t\t\t\t(wcls.subject_table_num = " . (int) $this->tableNum() . ") AND (wcls.subject_row_id IN (" . implode(", ", $va_set_ids) . ")) AND wcl.logged_table_num IN (" . $o_dm->getTableNum("ca_set_items") . ", " . $o_dm->getTableNum("ca_sets_x_users") . ", " . $o_dm->getTableNum("ca_sets_x_user_groups") . ")\n\t\t\t\t\t\t\t\tAND (csl.locale_id = ?)\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\tORDER BY log_datetime desc\n\t\t\t\t\t", $g_ui_locale_id, $g_ui_locale_id);
         $va_set_change_log = array();
         if ($q_change_log->numRows()) {
             while ($q_change_log->nextRow()) {
                 $va_tmp = array();
                 $va_tmp = $q_change_log->getRow();
                 $va_tmp['snapshot'] = caUnserializeForDatabase($q_change_log->get('snapshot'));
                 $va_set_change_log[$q_change_log->get('log_datetime')] = $va_tmp;
             }
         }
         # --- comments
         # --- set comments
         $q_set_comments = $o_db->query("\n\t\t\t\t\t\t\t\tSELECT c.created_on log_datetime, c.comment, wu.email, wu.fname, wu.lname, c.table_num, c.row_id set_id, csl.name\n\t\t\t\t\t\t\t\tFROM ca_item_comments c\n\t\t\t\t\t\t\t\tLEFT JOIN ca_users AS wu ON c.user_id = wu.user_id\n\t\t\t\t\t\t\t\tINNER JOIN ca_set_labels AS csl ON csl.set_id = c.row_id\n\t\t\t\t\t\t\t\tWHERE c.table_num = " . (int) $this->tableNum() . " AND c.row_id IN (" . implode(", ", $va_set_ids) . ")\n\t\t\t\t\t\t\t\tORDER BY c.created_on desc\n\t\t\t\t\t\t\t");
         if ($q_set_comments->numRows()) {
             while ($q_set_comments->nextRow()) {
                 $va_tmp = array();
                 $va_tmp = $q_set_comments->getRow();
                 $va_tmp["logged_table_num"] = $o_dm->getTableNum("ca_item_comments");
                 $va_set_change_log[$q_set_comments->get('log_datetime')] = $va_tmp;
             }
         }
         # --- item comments
         $q_set_item_comments = $o_db->query("\n\t\t\t\t\t\t\t\tSELECT c.created_on log_datetime, c.comment, wu.email, wu.fname, wu.lname, c.table_num, si.set_id set_id, csl.name\n\t\t\t\t\t\t\t\tFROM ca_item_comments c\n\t\t\t\t\t\t\t\tLEFT JOIN ca_users AS wu ON c.user_id = wu.user_id\n\t\t\t\t\t\t\t\tINNER JOIN ca_set_items as si ON si.item_id = c.row_id\n\t\t\t\t\t\t\t\tINNER JOIN ca_set_labels AS csl ON csl.set_id = si.set_id\n\t\t\t\t\t\t\t\tWHERE c.table_num = " . $o_dm->getTableNum("ca_set_items") . " AND si.set_id IN (" . implode(", ", $va_set_ids) . ")\n\t\t\t\t\t\t\t\tORDER BY c.created_on desc\n\t\t\t\t\t\t\t");
         if ($q_set_item_comments->numRows()) {
             while ($q_set_item_comments->nextRow()) {
                 $va_tmp = array();
                 $va_tmp = $q_set_item_comments->getRow();
                 $va_tmp["logged_table_num"] = $o_dm->getTableNum("ca_item_comments");
                 $va_set_change_log[$q_set_item_comments->get('log_datetime')] = $va_tmp;
             }
         }
         ksort($va_set_change_log);
         return array_reverse($va_set_change_log);
     } else {
         return false;
     }
 }
 /**
  * Get primary representation for specified object
  *
  * @param int $object_id
  * @param array $pa_versions list of media versions that should be included in the result
  * @return array
  * @throws SoapFault
  */
 public function getPrimaryObjectRepresentation($object_id, $versions)
 {
     if (!($t_subject_instance = $this->getTableInstance("ca_objects", $object_id))) {
         throw new SoapFault("Server", "Invalid object_id");
     }
     $va_rep = $t_subject_instance->getPrimaryRepresentation($versions);
     $va_rep["media"] = caUnserializeForDatabase($va_rep["media"]);
     $va_rep["media_metadata"] = caUnserializeForDatabase($va_rep["media_metadata"]);
     return $va_rep;
 }
 /**
  * Export a record set as defined by the given search expression and the table_num for this exporter.
  * This function wraps the record-level exports using the settings 'wrap_before' and 'wrap_after' if they are set.
  * @param string $ps_exporter_code defines the exporter to use
  * @param SearchResult $po_result An existing SearchResult object
  * @param string $ps_filename Destination filename (we can't keep everything in memory here)
  * @param array $pa_options
  * 		progressCallback = callback function for asynchronous UI status reporting
  *		showCLIProgressBar = Show command-line progress bar. Default is false.
  *		logDirectory = path to directory where logs should be written
  *		logLevel = KLogger constant for minimum log level to record. Default is KLogger::INFO. Constants are, in descending order of shrillness:
  *			KLogger::EMERG = Emergency messages (system is unusable)
  *			KLogger::ALERT = Alert messages (action must be taken immediately)
  *			KLogger::CRIT = Critical conditions
  *			KLogger::ERR = Error conditions
  *			KLogger::WARN = Warnings
  *			KLogger::NOTICE = Notices (normal but significant conditions)
  *			KLogger::INFO = Informational messages
  *			KLogger::DEBUG = Debugging messages
  * @return boolean success state
  */
 public static function exportRecordsFromSearchResult($ps_exporter_code, $po_result, $ps_filename, $pa_options = array())
 {
     if (!$po_result instanceof SearchResult) {
         return false;
     }
     $vs_log_dir = caGetOption('logDirectory', $pa_options);
     if (!file_exists($vs_log_dir) || !is_writable($vs_log_dir)) {
         $vs_log_dir = caGetTempDirPath();
     }
     if (!($vn_log_level = caGetOption('logLevel', $pa_options))) {
         $vn_log_level = KLogger::INFO;
     }
     $o_log = new KLogger($vs_log_dir, $vn_log_level);
     ca_data_exporters::$s_exporter_cache = array();
     ca_data_exporters::$s_exporter_item_cache = array();
     $vb_show_cli_progress_bar = isset($pa_options['showCLIProgressBar']) && $pa_options['showCLIProgressBar'];
     $po_request = caGetOption('request', $pa_options, null);
     $vb_have_request = $po_request instanceof RequestHTTP;
     if (!($t_mapping = ca_data_exporters::loadExporterByCode($ps_exporter_code))) {
         return false;
     }
     $va_errors = ca_data_exporters::checkMapping($ps_exporter_code);
     if (sizeof($va_errors) > 0) {
         if ($po_request && isset($pa_options['progressCallback']) && ($ps_callback = $pa_options['progressCallback'])) {
             $ps_callback($po_request, 0, -1, _t('Export failed: %1', join("; ", $va_errors)), 0, memory_get_usage(true), 0);
         }
         return false;
     }
     $o_log->logInfo(_t("Starting SearchResult-based multi-record export for mapping %1.", $ps_exporter_code));
     $vn_start_time = time();
     $vs_wrap_before = $t_mapping->getSetting('wrap_before');
     $vs_wrap_after = $t_mapping->getSetting('wrap_after');
     $t_instance = $t_mapping->getAppDatamodel()->getInstanceByTableNum($t_mapping->get('table_num'));
     $vn_num_items = $po_result->numHits();
     $o_log->logInfo(_t("SearchResult contains %1 results. Now calling single-item export for each record.", $vn_num_items));
     if ($vs_wrap_before) {
         file_put_contents($ps_filename, $vs_wrap_before . "\n", FILE_APPEND);
     }
     if ($vb_show_cli_progress_bar) {
         print CLIProgressBar::start($vn_num_items, _t('Processing search result'));
     }
     if ($po_request && isset($pa_options['progressCallback']) && ($ps_callback = $pa_options['progressCallback'])) {
         if ($vn_num_items > 0) {
             $ps_callback($po_request, 0, $vn_num_items, _t("Exporting result"), time() - $vn_start_time, memory_get_usage(true), 0);
         } else {
             $ps_callback($po_request, 0, -1, _t('Found no records to export'), time() - $vn_start_time, memory_get_usage(true), 0);
         }
     }
     $vn_num_processed = 0;
     if ($t_mapping->getSetting('CSV_print_field_names')) {
         $va_header = $va_header_sources = array();
         $va_mapping_items = $t_mapping->getItems();
         foreach ($va_mapping_items as $vn_i => $va_mapping_item) {
             $va_settings = caUnserializeForDatabase($va_mapping_item['settings']);
             $va_header_sources[(int) $va_mapping_item['element']] = $va_settings['_id'] ? $va_settings['_id'] : $va_mapping_item['source'];
         }
         ksort($va_header_sources);
         foreach ($va_header_sources as $vn_element => $vs_source) {
             $va_tmp = explode(".", $vs_source);
             if ($t_table = $t_mapping->getAppDatamodel()->getInstanceByTableName($va_tmp[0], true)) {
                 $va_header[] = $t_table->getDisplayLabel($vs_source);
             } else {
                 $va_header[] = $vs_source;
             }
         }
         file_put_contents($ps_filename, join(",", $va_header) . "\n", FILE_APPEND);
     }
     $i = 0;
     while ($po_result->nextHit()) {
         // clear caches every once in a while. doesn't make much sense to keep them around while exporting
         if (++$i % 1000 == 0) {
             SearchResult::clearCaches();
             ca_data_exporters::clearCaches();
         }
         if ($vb_have_request) {
             if (!caCanRead($po_request->getUserID(), $t_instance->tableNum(), $po_result->get($t_instance->primaryKey()))) {
                 continue;
             }
         }
         $vs_item_export = ca_data_exporters::exportRecord($ps_exporter_code, $po_result->get($t_instance->primaryKey()), array('logger' => $o_log));
         file_put_contents($ps_filename, $vs_item_export . "\n", FILE_APPEND);
         if ($vb_show_cli_progress_bar) {
             print CLIProgressBar::next(1, _t("Exporting records ..."));
         }
         $vn_num_processed++;
         if ($vb_have_request && isset($pa_options['progressCallback']) && ($ps_callback = $pa_options['progressCallback'])) {
             $ps_callback($po_request, $vn_num_processed, $vn_num_items, _t("Exporting ... [%1/%2]", $vn_num_processed, $vn_num_items), time() - $vn_start_time, memory_get_usage(true), $vn_num_processed);
         }
     }
     if ($vs_wrap_after) {
         file_put_contents($ps_filename, $vs_wrap_after . "\n", FILE_APPEND);
     }
     if ($vb_show_cli_progress_bar) {
         print CLIProgressBar::finish();
     }
     if ($po_request && isset($pa_options['progressCallback']) && ($ps_callback = $pa_options['progressCallback'])) {
         $ps_callback($po_request, $vn_num_items, $vn_num_items, _t('Export completed'), time() - $vn_start_time, memory_get_usage(true), $vn_num_processed);
     }
     return true;
 }