/** * Apply media transformation to media in specified field of current loaded row. When a transformation is applied * it is applied to all versions, including the "original." A copy of the original is stashed in a "virtual" version named "_undo_" * to make it possible to recover the original media, if desired, by calling removeMediaTransformations(). * * @param string $ps_field The name of the media field * @param string $ps_op A valid media transformation op code, as defined by the media plugin handling the media being transformed. * @param array $pa_params The parameters for the op code, as defined by the media plugin handling the media being transformed. * @param array $pa_options An array of options. No options are currently implemented. * * @return bool True on success, false if an error occurred. */ public function applyMediaTransformation($ps_field, $ps_op, $pa_params, $pa_options = null) { $va_media_info = $this->getMediaInfo($ps_field); if (!is_array($va_media_info)) { return null; } if (isset($pa_options['revert']) && $pa_options['revert'] && isset($va_media_info['_undo_'])) { $vs_path = $vs_undo_path = $this->getMediaPath($ps_field, '_undo_'); $va_transformation_history = array(); } else { $vs_path = $this->getMediaPath($ps_field, 'original'); // Copy original into "undo" slot (if undo slot is empty) $vs_undo_path = !isset($va_media_info['_undo_']) ? $vs_path : $this->getMediaPath($ps_field, '_undo_'); if (!is_array($va_transformation_history = $va_media_info['TRANSFORMATION_HISTORY'])) { $va_transformation_history = array(); } } // TODO: Check if transformation valid for this media // Apply transformation to original $o_media = new Media(); $o_media->read($vs_path); $o_media->transform($ps_op, $pa_params); $va_transformation_history[$ps_op][] = $pa_params; $vs_tmp_basename = tempnam(caGetTempDirPath(), 'ca_media_rotation_tmp'); $o_media->write($vs_tmp_basename, $o_media->get('mimetype'), array()); // Regenerate derivatives $this->setMode(ACCESS_WRITE); $this->set($ps_field, $vs_tmp_basename . "." . $va_media_info['original']['EXTENSION'], $vs_undo_path ? array('undo' => $vs_undo_path, 'TRANSFORMATION_HISTORY' => $va_transformation_history) : array('TRANSFORMATION_HISTORY' => $va_transformation_history)); $this->setAsChanged($ps_field); $this->update(); return $this->numErrors() ? false : true; }
/** * Reindex PDF media by content for in-PDF search */ public static function reindex_pdfs($po_opts = null) { require_once __CA_LIB_DIR__ . "/core/Db.php"; require_once __CA_MODELS_DIR__ . "/ca_object_representations.php"; if (!caPDFMinerInstalled()) { CLIUtils::addError(_t("Can't reindex PDFs: PDFMiner is not installed.")); return false; } $o_db = new Db(); $t_rep = new ca_object_representations(); $t_rep->setMode(ACCESS_WRITE); $va_versions = array("original"); $va_kinds = ($vs_kinds = $po_opts->getOption("kinds")) ? explode(",", $vs_kinds) : array(); if (!is_array($va_kinds) || !sizeof($va_kinds)) { $va_kinds = array('all'); } $va_kinds = array_map('strtolower', $va_kinds); if (in_array('all', $va_kinds) || in_array('ca_object_representations', $va_kinds)) { if (!($vn_start = (int) $po_opts->getOption('start_id'))) { $vn_start = null; } if (!($vn_end = (int) $po_opts->getOption('end_id'))) { $vn_end = null; } if ($vn_id = (int) $po_opts->getOption('id')) { $vn_start = $vn_id; $vn_end = $vn_id; } $va_ids = array(); if ($vs_ids = (string) $po_opts->getOption('ids')) { if (sizeof($va_tmp = explode(",", $vs_ids))) { foreach ($va_tmp as $vn_id) { if ((int) $vn_id > 0) { $va_ids[] = (int) $vn_id; } } } } $vs_sql_where = null; $va_params = array(); if (sizeof($va_ids)) { $vs_sql_where = "WHERE representation_id IN (?)"; $va_params[] = $va_ids; } else { if ($vn_start > 0 && $vn_end > 0 && $vn_start <= $vn_end || $vn_start > 0 && $vn_end == null) { $vs_sql_where = "WHERE representation_id >= ?"; $va_params[] = $vn_start; if ($vn_end) { $vs_sql_where .= " AND representation_id <= ?"; $va_params[] = $vn_end; } } } if ($vs_sql_where) { $vs_sql_where .= " AND mimetype = 'application/pdf'"; } else { $vs_sql_where = " WHERE mimetype = 'application/pdf'"; } $qr_reps = $o_db->query("\n\t\t\t\t\tSELECT * \n\t\t\t\t\tFROM ca_object_representations \n\t\t\t\t\t{$vs_sql_where}\n\t\t\t\t\tORDER BY representation_id\n\t\t\t\t", $va_params); print CLIProgressBar::start($qr_reps->numRows(), _t('Reindexing PDF representations')); $vn_rep_table_num = $t_rep->tableNum(); while ($qr_reps->nextRow()) { $va_media_info = $qr_reps->getMediaInfo('media'); $vs_original_filename = $va_media_info['ORIGINAL_FILENAME']; print CLIProgressBar::next(1, _t("Reindexing PDF %1", $vs_original_filename ? $vs_original_filename . " (" . $qr_reps->get('representation_id') . ")" : $qr_reps->get('representation_id'))); $t_rep->load($qr_reps->get('representation_id')); $vn_rep_id = $t_rep->getPrimaryKey(); $m = new Media(); if ($m->read($vs_path = $t_rep->getMediaPath('media', 'original')) && is_array($va_locs = $m->getExtractedTextLocations())) { MediaContentLocationIndexer::clear($vn_rep_table_num, $vn_rep_id); foreach ($va_locs as $vs_content => $va_loc_list) { foreach ($va_loc_list as $va_loc) { MediaContentLocationIndexer::index($vn_rep_table_num, $vn_rep_id, $vs_content, $va_loc['p'], $va_loc['x1'], $va_loc['y1'], $va_loc['x2'], $va_loc['y2']); } } MediaContentLocationIndexer::write(); } else { //CLIUtils::addError(_t("[Warning] No content to reindex for PDF representation: %1", $vs_path)); } } print CLIProgressBar::finish(); } if (in_array('all', $va_kinds) || in_array('ca_attributes', $va_kinds)) { // get all Media elements $va_elements = ca_metadata_elements::getElementsAsList(false, null, null, true, false, true, array(16)); // 16=media $qr_c = $o_db->query("\n\t\t\t\t\tSELECT count(*) c \n\t\t\t\t\tFROM ca_attribute_values\n\t\t\t\t\tWHERE\n\t\t\t\t\t\telement_id in (?)\n\t\t\t\t", caExtractValuesFromArrayList($va_elements, 'element_id', array('preserveKeys' => false))); if ($qr_c->nextRow()) { $vn_count = $qr_c->get('c'); } else { $vn_count = 0; } $t_attr_val = new ca_attribute_values(); $vn_attr_table_num = $t_attr_val->tableNum(); print CLIProgressBar::start($vn_count, _t('Reindexing metadata attribute media')); foreach ($va_elements as $vs_element_code => $va_element_info) { $qr_vals = $o_db->query("SELECT value_id FROM ca_attribute_values WHERE element_id = ?", (int) $va_element_info['element_id']); $va_vals = $qr_vals->getAllFieldValues('value_id'); foreach ($va_vals as $vn_value_id) { $t_attr_val = new ca_attribute_values($vn_value_id); if ($t_attr_val->getPrimaryKey()) { $t_attr_val->setMode(ACCESS_WRITE); $t_attr_val->useBlobAsMediaField(true); $va_media_info = $t_attr_val->getMediaInfo('value_blob'); $vs_original_filename = $va_media_info['ORIGINAL_FILENAME']; if (!is_array($va_media_info) || $va_media_info['MIMETYPE'] !== 'application/pdf') { continue; } print CLIProgressBar::next(1, _t("Reindexing %1", $vs_original_filename ? $vs_original_filename . " ({$vn_value_id})" : $vn_value_id)); $m = new Media(); if ($m->read($vs_path = $t_attr_val->getMediaPath('value_blob', 'original')) && is_array($va_locs = $m->getExtractedTextLocations())) { MediaContentLocationIndexer::clear($vn_attr_table_num, $vn_attr_table_num); foreach ($va_locs as $vs_content => $va_loc_list) { foreach ($va_loc_list as $va_loc) { MediaContentLocationIndexer::index($vn_attr_table_num, $vn_value_id, $vs_content, $va_loc['p'], $va_loc['x1'], $va_loc['y1'], $va_loc['x2'], $va_loc['y2']); } } MediaContentLocationIndexer::write(); } else { //CLIUtils::addError(_t("[Warning] No content to reindex for PDF in metadata attribute: %1", $vs_path)); } } } } print CLIProgressBar::finish(); } return true; }
/** * Saves all bundles on the specified screen in the database by extracting * required data from the supplied request * $pm_screen can be a screen tag (eg. "Screen5") or a screen_id (eg. 5) * * Calls processBundlesBeforeBaseModelSave() method in subclass right before invoking insert() or update() on * the BaseModel, if the method is defined. Passes the following parameters to processBundlesBeforeBaseModelSave(): * array $pa_bundles An array of bundles to be saved * string $ps_form_prefix The form prefix * RequestHTTP $po_request The current request * array $pa_options Optional array of parameters; expected to be the same as that passed to saveBundlesForScreen() * * The processBundlesBeforeBaseModelSave() is useful for those odd cases where you need to do some processing before the basic * database record defined by the model (eg. intrinsic fields and hierarchy coding) is inserted or updated. You usually don't need * to use it. * * @param mixed $pm_screen * @param RequestHTTP $ps_request * @param array $pa_options Options are: * dryRun = Go through the motions of saving but don't actually write information to the database * batch = Process save in "batch" mode. Specifically this means honoring batch mode settings (add, replace, remove), skipping bundles that are not supported in batch mode and ignoring updates * existingRepresentationMap = an array of representation_ids key'ed on file path. If set saveBundlesForScreen() use link the specified representation to the row it is saving rather than processing the uploaded file. saveBundlesForScreen() will build the map as it goes, adding newly uploaded files. If you want it to process a file in a batch situation where it should be processed the first time and linked subsequently then pass an empty array here. saveBundlesForScreen() will use the empty array to build the map. */ public function saveBundlesForScreen($pm_screen, $po_request, &$pa_options) { $vb_we_set_transaction = false; $vs_form_prefix = caGetOption('formName', $pa_options, $po_request->getParameter('_formName', pString)); $vb_dryrun = caGetOption('dryRun', $pa_options, false); $vb_batch = caGetOption('batch', $pa_options, false); if (!$this->inTransaction()) { $this->setTransaction(new Transaction($this->getDb())); $vb_we_set_transaction = true; } else { if ($vb_dryrun) { $this->postError(799, _t('Cannot do dry run save when in transaction. Try again without setting a transaction.'), "BundlableLabelableBaseModelWithAttributes->saveBundlesForScreen()"); return false; } } $vb_read_only_because_deaccessioned = $this->hasField('is_deaccessioned') && (bool) $this->getAppConfig()->get('deaccession_dont_allow_editing') && (bool) $this->get('is_deaccessioned'); BaseModel::setChangeLogUnitID(); // get items on screen $t_ui = caGetOption('ui_instance', $pa_options, ca_editor_uis::loadDefaultUI($this->tableName(), $po_request, $this->getTypeID())); $va_bundle_lists = $this->getBundleListsForScreen($pm_screen, $po_request, $t_ui, $pa_options); // // Filter bundles to save if deaccessioned - only allow editing of the ca_objects_deaccession bundle // if ($vb_read_only_because_deaccessioned) { foreach ($va_bundle_lists['bundles'] as $vn_i => $va_bundle) { if ($va_bundle['bundle_name'] !== 'ca_objects_deaccession') { unset($va_bundle_lists['bundles'][$vn_i]); } } foreach ($va_bundle_lists['fields_by_type'] as $vs_type => $va_bundles) { foreach ($va_bundles as $vs_id => $vs_bundle_name) { if ($vs_bundle_name !== 'ca_objects_deaccession') { unset($va_bundle_lists['fields_by_type'][$vs_type][$vs_id]); } } } } $va_bundles = $va_bundle_lists['bundles']; $va_fields_by_type = $va_bundle_lists['fields_by_type']; // save intrinsic fields if (is_array($va_fields_by_type['intrinsic'])) { $vs_idno_field = $this->getProperty('ID_NUMBERING_ID_FIELD'); foreach ($va_fields_by_type['intrinsic'] as $vs_placement_code => $vs_f) { if ($vb_batch) { $vs_batch_mode = $po_request->getParameter("{$vs_placement_code}{$vs_form_prefix}_batch_mode", pString); if ($vs_batch_mode == '_disabled_') { continue; } } if (isset($_FILES["{$vs_placement_code}{$vs_form_prefix}{$vs_f}"]) && $_FILES["{$vs_placement_code}{$vs_form_prefix}{$vs_f}"]) { // media field $this->set($vs_f, $_FILES["{$vs_placement_code}{$vs_form_prefix}{$vs_f}"]['tmp_name'], array('original_filename' => $_FILES["{$vs_placement_code}{$vs_form_prefix}{$vs_f}"]['name'])); } else { switch ($vs_f) { case 'access': if ((bool) $this->getAppConfig()->get($this->tableName() . '_allow_access_inheritance') && $this->hasField('access_inherit_from_parent')) { $this->set('access_inherit_from_parent', $po_request->getParameter("{$vs_placement_code}{$vs_form_prefix}access_inherit_from_parent", pInteger)); } if (!(bool) $this->getAppConfig()->get($this->tableName() . '_allow_access_inheritance') || !$this->hasField('access_inherit_from_parent') || !(bool) $this->get('access_inherit_from_parent')) { $this->set('access', $po_request->getParameter("{$vs_placement_code}{$vs_form_prefix}access", pString)); } break; case $vs_idno_field: if ($this->opo_idno_plugin_instance) { $this->opo_idno_plugin_instance->setDb($this->getDb()); $this->set($vs_f, $vs_tmp = $this->opo_idno_plugin_instance->htmlFormValue($vs_idno_field)); } else { $this->set($vs_f, $po_request->getParameter("{$vs_placement_code}{$vs_form_prefix}{$vs_f}", pString)); } break; default: // Look for fully qualified intrinsic if (!strlen($vs_v = $po_request->getParameter("{$vs_placement_code}{$vs_form_prefix}{$vs_f}", pString))) { // fall back to simple field name intrinsic spec - still used for "mandatory" fields such as type_id and parent_id $vs_v = $po_request->getParameter("{$vs_f}", pString); } $this->set($vs_f, $vs_v); break; } } if ($this->numErrors() > 0) { foreach ($this->errors() as $o_e) { switch ($o_e->getErrorNumber()) { case 795: // field conflicts foreach ($this->getFieldConflicts() as $vs_conflict_field) { $po_request->addActionError($o_e, $vs_conflict_field); } break; default: $po_request->addActionError($o_e, $vs_f); break; } } } } } // save attributes $va_inserted_attributes_by_element = array(); if (isset($va_fields_by_type['attribute']) && is_array($va_fields_by_type['attribute'])) { // // name of attribute request parameters are: // For new attributes // {$vs_form_prefix}_attribute_{element_set_id}_{element_id|'locale_id'}_new_{n} // ex. ObjectBasicForm_attribute_6_locale_id_new_0 or ObjectBasicForm_attribute_6_desc_type_new_0 // // For existing attributes: // {$vs_form_prefix}_attribute_{element_set_id}_{element_id|'locale_id'}_{attribute_id} // // look for newly created attributes; look for attributes to delete $va_inserted_attributes = array(); $reserved_elements = array(); foreach ($va_fields_by_type['attribute'] as $vs_placement_code => $vs_f) { $vs_element_set_code = preg_replace("/^ca_attribute_/", "", $vs_f); //does the attribute's datatype have a saveElement method - if so, use that instead $vs_element = $this->_getElementInstance($vs_element_set_code); $vn_element_id = $vs_element->getPrimaryKey(); $vs_element_datatype = $vs_element->get('datatype'); $vs_datatype = Attribute::getValueInstance($vs_element_datatype); if (method_exists($vs_datatype, 'saveElement')) { $reserved_elements[] = $vs_element; continue; } $va_attributes_to_insert = array(); $va_attributes_to_delete = array(); $va_locales = array(); $vs_batch_mode = $_REQUEST[$vs_placement_code . $vs_form_prefix . '_attribute_' . $vn_element_id . '_batch_mode']; if ($vb_batch && $vs_batch_mode == '_delete_') { // Remove all attributes and continue $this->removeAttributes($vn_element_id, array('force' => true)); continue; } foreach ($_REQUEST as $vs_key => $vs_val) { // is it a newly created attribute? if (preg_match('/' . $vs_placement_code . $vs_form_prefix . '_attribute_' . $vn_element_id . '_([\\w\\d\\-_]+)_new_([\\d]+)/', $vs_key, $va_matches)) { if ($vb_batch) { switch ($vs_batch_mode) { case '_disabled_': // skip continue 2; break; case '_add_': // just try to add attribute as in normal non-batch save // noop break; case '_replace_': // remove all existing attributes before trying to save $this->removeAttributes($vn_element_id, array('force' => true)); continue; break; } } $vn_c = intval($va_matches[2]); // yep - grab the locale and value $vn_locale_id = isset($_REQUEST[$vs_placement_code . $vs_form_prefix . '_attribute_' . $vn_element_id . '_locale_id_new_' . $vn_c]) ? $_REQUEST[$vs_placement_code . $vs_form_prefix . '_attribute_' . $vn_element_id . '_locale_id_new_' . $vn_c] : null; $va_inserted_attributes_by_element[$vn_element_id][$vn_c]['locale_id'] = $va_attributes_to_insert[$vn_c]['locale_id'] = $vn_locale_id; $va_inserted_attributes_by_element[$vn_element_id][$vn_c][$va_matches[1]] = $va_attributes_to_insert[$vn_c][$va_matches[1]] = $vs_val; } else { // is it a delete key? if (preg_match('/' . $vs_placement_code . $vs_form_prefix . '_attribute_' . $vn_element_id . '_([\\d]+)_delete/', $vs_key, $va_matches)) { $vn_attribute_id = intval($va_matches[1]); $va_attributes_to_delete[$vn_attribute_id] = true; } } } // look for uploaded files as attributes foreach ($_FILES as $vs_key => $va_val) { if (preg_match('/' . $vs_placement_code . $vs_form_prefix . '_attribute_' . $vn_element_id . '_locale_id_new_([\\d]+)/', $vs_key, $va_locale_matches)) { $vn_locale_c = intval($va_locale_matches[1]); $va_locales[$vn_locale_c] = $vs_val; continue; } // is it a newly created attribute? if (preg_match('/' . $vs_placement_code . $vs_form_prefix . '_attribute_' . $vn_element_id . '_([\\w\\d\\-_]+)_new_([\\d]+)/', $vs_key, $va_matches)) { if (!$va_val['size']) { continue; } // skip empty files // yep - grab the value $vn_c = intval($va_matches[2]); $va_inserted_attributes_by_element[$vn_element_id][$vn_c]['locale_id'] = $va_attributes_to_insert[$vn_c]['locale_id'] = $va_locales[$vn_c]; $va_val['_uploaded_file'] = true; $va_inserted_attributes_by_element[$vn_element_id][$vn_c][$va_matches[1]] = $va_attributes_to_insert[$vn_c][$va_matches[1]] = $va_val; } } if (!$vb_batch) { // do deletes $this->clearErrors(); foreach ($va_attributes_to_delete as $vn_attribute_id => $vb_tmp) { $this->removeAttribute($vn_attribute_id, $vs_f, array('pending_adds' => $va_attributes_to_insert)); } } // do inserts foreach ($va_attributes_to_insert as $va_attribute_to_insert) { $this->clearErrors(); $this->addAttribute($va_attribute_to_insert, $vn_element_id, $vs_f); } if (!$vb_batch) { // check for attributes to update if (is_array($va_attrs = $this->getAttributesByElement($vn_element_id))) { $t_element = new ca_metadata_elements(); $va_attrs_update_list = array(); foreach ($va_attrs as $o_attr) { $this->clearErrors(); $vn_attribute_id = $o_attr->getAttributeID(); if (isset($va_inserted_attributes[$vn_attribute_id]) && $va_inserted_attributes[$vn_attribute_id]) { continue; } if (isset($va_attributes_to_delete[$vn_attribute_id]) && $va_attributes_to_delete[$vn_attribute_id]) { continue; } $vn_element_set_id = $o_attr->getElementID(); $va_attr_update = array('locale_id' => $po_request->getParameter($vs_placement_code . $vs_form_prefix . '_attribute_' . $vn_element_set_id . '_locale_id_' . $vn_attribute_id, pString)); // // Check to see if there are any values in the element set that are not in the attribute we're editing // If additional sub-elements were added to the set after the attribute we're updating was created // those sub-elements will not have corresponding values returned by $o_attr->getValues() above. // Because we use the element_ids in those values to pull request parameters, if an element_id is missing // it effectively becomes invisible and cannot be set. This is a fairly unusual case but it happens, and when it does // it's really annoying. It would be nice and efficient to simply create the missing values at configuration time, but we wouldn't // know what to set the values to. So what we do is, after setting all of the values present in the attribute from the request, grab // the configuration for the element set and see if there are any elements in the set that we didn't get values for. // $va_sub_elements = $t_element->getElementsInSet($vn_element_set_id); foreach ($va_sub_elements as $vn_i => $va_element_info) { if ($va_element_info['datatype'] == 0) { continue; } //$vn_element_id = $o_attr_val->getElementID(); $vn_element_id = $va_element_info['element_id']; $vs_k = $vs_placement_code . $vs_form_prefix . '_attribute_' . $vn_element_set_id . '_' . $vn_element_id . '_' . $vn_attribute_id; if (isset($_FILES[$vs_k]) && ($va_val = $_FILES[$vs_k])) { if ($va_val['size'] > 0) { // is there actually a file? $va_val['_uploaded_file'] = true; $va_attr_update[$vn_element_id] = $va_val; continue; } } $vs_attr_val = $po_request->getParameter($vs_k, pString); $va_attr_update[$vn_element_id] = $vs_attr_val; } $this->clearErrors(); $this->editAttribute($vn_attribute_id, $vn_element_set_id, $va_attr_update, $vs_f); } } } } } if (!$vb_batch) { // hierarchy moves are not supported in batch mode if (is_array($va_fields_by_type['special'])) { foreach ($va_fields_by_type['special'] as $vs_placement_code => $vs_bundle) { if ($vs_bundle !== 'hierarchy_location') { continue; } $va_parent_tmp = explode("-", $po_request->getParameter("{$vs_placement_code}{$vs_form_prefix}_new_parent_id", pString)); // Hierarchy browser sets new_parent_id param to "X" if user wants to extract item from hierarchy $vn_parent_id = ($vn_parent_id = array_pop($va_parent_tmp)) == 'X' ? -1 : (int) $vn_parent_id; if (sizeof($va_parent_tmp) > 0) { $vs_parent_table = array_pop($va_parent_tmp); } else { $vs_parent_table = $this->tableName(); } if ($this->getPrimaryKey() && $this->HIERARCHY_PARENT_ID_FLD && $vn_parent_id > 0) { if ($vs_parent_table == $this->tableName()) { $this->set($this->HIERARCHY_PARENT_ID_FLD, $vn_parent_id); } else { if ((bool) $this->getAppConfig()->get('ca_objects_x_collections_hierarchy_enabled') && $vs_parent_table == 'ca_collections' && $this->tableName() == 'ca_objects' && ($vs_coll_rel_type = $this->getAppConfig()->get('ca_objects_x_collections_hierarchy_relationship_type'))) { // link object to collection $this->removeRelationships('ca_collections', $vs_coll_rel_type); $this->set($this->HIERARCHY_PARENT_ID_FLD, null); $this->set($this->HIERARCHY_ID_FLD, $this->getPrimaryKey()); if (!$this->addRelationship('ca_collections', $vn_parent_id, $vs_coll_rel_type)) { $this->postError(2510, _t('Could not move object under collection: %1', join("; ", $this->getErrors())), "BundlableLabelableBaseModelWithAttributes->saveBundlesForScreen()"); } } } } else { if ($this->getPrimaryKey() && $this->HIERARCHY_PARENT_ID_FLD && $this->HIERARCHY_TYPE == __CA_HIER_TYPE_ADHOC_MONO__ && isset($_REQUEST["{$vs_placement_code}{$vs_form_prefix}_new_parent_id"]) && $vn_parent_id <= 0) { $this->set($this->HIERARCHY_PARENT_ID_FLD, null); $this->set($this->HIERARCHY_ID_FLD, $this->getPrimaryKey()); // Support for collection-object cross-table hierarchies if ((bool) $this->getAppConfig()->get('ca_objects_x_collections_hierarchy_enabled') && $this->tableName() == 'ca_objects' && ($vs_coll_rel_type = $this->getAppConfig()->get('ca_objects_x_collections_hierarchy_relationship_type')) && $vn_parent_id == -1) { // -1 = extract from hierarchy $this->removeRelationships('ca_collections', $vs_coll_rel_type); } } } break; } } } // // Call processBundlesBeforeBaseModelSave() method in sub-class, if it is defined. The method is passed // a list of bundles, the form prefix, the current request and the options passed to saveBundlesForScreen() – // everything needed to perform custom processing using the incoming form content that is being saved. // // A processBundlesBeforeBaseModelSave() method is rarely needed, but can be handy when you need to do something model-specific // right before the basic database record is committed via insert() (for new records) or update() (for existing records). // For example, the media in ca_object_representations is set in a "special" bundle, which provides a specialized media upload UI. Unfortunately "special's" // are handled after the basic database record is saved via insert() or update(), while the actual media must be set prior to the save. // processBundlesBeforeBaseModelSave() allows special logic in the ca_object_representations model to be invoked to set the media before the insert() or update(). // The "special" takes care of other functions after the insert()/update() // if (method_exists($this, "processBundlesBeforeBaseModelSave")) { $this->processBundlesBeforeBaseModelSave($va_bundles, $vs_form_prefix, $po_request, $pa_options); } $this->setMode(ACCESS_WRITE); $vb_is_insert = false; if ($this->getPrimaryKey()) { $this->update(); } else { $this->insert(); $vb_is_insert = true; } if ($this->numErrors() > 0) { $va_errors = array(); foreach ($this->errors() as $o_e) { switch ($o_e->getErrorNumber()) { case 2010: $po_request->addActionErrors(array($o_e), 'hierarchy_location'); break; case 795: // field conflict foreach ($this->getFieldConflicts() as $vs_conflict_field) { $po_request->addActionError($o_e, $vs_conflict_field); } break; case 1100: if ($vs_idno_field = $this->getProperty('ID_NUMBERING_ID_FIELD')) { $po_request->addActionError($o_e, $this->getProperty('ID_NUMBERING_ID_FIELD')); } break; default: $va_errors[] = $o_e; break; } } $po_request->addActionErrors($va_errors); if ($vb_is_insert) { BaseModel::unsetChangeLogUnitID(); if ($vb_we_set_transaction) { $this->removeTransaction(false); } return false; // bail on insert error } } if (!$this->getPrimaryKey()) { BaseModel::unsetChangeLogUnitID(); if ($vb_we_set_transaction) { $this->removeTransaction(false); } return false; } // bail if insert failed $this->clearErrors(); //save reserved elements - those with a saveElement method if (isset($reserved_elements) && is_array($reserved_elements)) { foreach ($reserved_elements as $res_element) { $res_element_id = $res_element->getPrimaryKey(); $res_element_datatype = $res_element->get('datatype'); $res_datatype = Attribute::getValueInstance($res_element_datatype); $res_datatype->saveElement($this, $res_element, $vs_form_prefix, $po_request); } } // save preferred labels if ($this->getProperty('LABEL_TABLE_NAME')) { $vb_check_for_dupe_labels = $this->_CONFIG->get('allow_duplicate_labels_for_' . $this->tableName()) ? false : true; $vb_error_inserting_pref_label = false; if (is_array($va_fields_by_type['preferred_label'])) { foreach ($va_fields_by_type['preferred_label'] as $vs_placement_code => $vs_f) { if (!$vb_batch) { // check for existing labels to update (or delete) $va_preferred_labels = $this->getPreferredLabels(null, false); foreach ($va_preferred_labels as $vn_item_id => $va_labels_by_locale) { foreach ($va_labels_by_locale as $vn_locale_id => $va_label_list) { foreach ($va_label_list as $va_label) { if ($vn_label_locale_id = $po_request->getParameter($vs_placement_code . $vs_form_prefix . '_Pref' . 'locale_id_' . $va_label['label_id'], pString)) { if (is_array($va_label_values = $this->getLabelUIValuesFromRequest($po_request, $vs_placement_code . $vs_form_prefix, $va_label['label_id'], true))) { if ($vb_check_for_dupe_labels && $this->checkForDupeLabel($vn_label_locale_id, $va_label_values)) { $this->postError(1125, _t('Value <em>%1</em> is already used and duplicates are not allowed', join("/", $va_label_values)), "BundlableLabelableBaseModelWithAttributes->saveBundlesForScreen()", $this->tableName() . '.preferred_labels'); $po_request->addActionErrors($this->errors(), 'preferred_labels'); continue; } $vn_label_type_id = $po_request->getParameter($vs_placement_code . $vs_form_prefix . '_Pref' . 'type_id_' . $va_label['label_id'], pInteger); $this->editLabel($va_label['label_id'], $va_label_values, $vn_label_locale_id, $vn_label_type_id, true); if ($this->numErrors()) { foreach ($this->errors() as $o_e) { switch ($o_e->getErrorNumber()) { case 795: // field conflicts $po_request->addActionError($o_e, 'preferred_labels'); break; default: $po_request->addActionError($o_e, $vs_f); break; } } } } } else { if ($po_request->getParameter($vs_placement_code . $vs_form_prefix . '_PrefLabel_' . $va_label['label_id'] . '_delete', pString)) { // delete $this->removeLabel($va_label['label_id']); } } } } } } // check for new labels to add foreach ($_REQUEST as $vs_key => $vs_value) { if (!preg_match('/' . $vs_placement_code . $vs_form_prefix . '_Pref' . 'locale_id_new_([\\d]+)/', $vs_key, $va_matches)) { continue; } if ($vb_batch) { $vs_batch_mode = $po_request->getParameter($vs_placement_code . $vs_form_prefix . '_Pref_batch_mode', pString); switch ($vs_batch_mode) { case '_disabled_': // skip continue 2; break; case '_replace_': // remove all existing preferred labels before trying to save $this->removeAllLabels(__CA_LABEL_TYPE_PREFERRED__); continue; case '_delete_': // remove all existing preferred labels $this->removeAllLabels(__CA_LABEL_TYPE_PREFERRED__); continue 2; case '_add_': break; } } $vn_c = intval($va_matches[1]); if ($vn_new_label_locale_id = $po_request->getParameter($vs_placement_code . $vs_form_prefix . '_Pref' . 'locale_id_new_' . $vn_c, pString)) { if (is_array($va_label_values = $this->getLabelUIValuesFromRequest($po_request, $vs_placement_code . $vs_form_prefix, 'new_' . $vn_c, true))) { // make sure we don't add multiple pref labels for one locale in batch mode if ($vb_batch && $vs_batch_mode == '_add_') { // first remove [BLANK] labels for this locale if there are any, as we are about to add a new one $va_labels_for_this_locale = $this->getPreferredLabels(array($vn_new_label_locale_id)); if (is_array($va_labels_for_this_locale)) { foreach ($va_labels_for_this_locale as $vn_id => $va_labels_by_locale) { foreach ($va_labels_by_locale as $vn_locale_id => $va_labels) { foreach ($va_labels as $vn_i => $va_label) { if (isset($va_label[$this->getLabelDisplayField()]) && $va_label[$this->getLabelDisplayField()] == '[' . _t('BLANK') . ']') { $this->removeLabel($va_label['label_id']); } } } } } // if there are non-[BLANK] labels for this locale, don't add this new one $va_labels_for_this_locale = $this->getPreferredLabels(array($vn_new_label_locale_id), true, array('forDisplay' => true)); if (is_array($va_labels_for_this_locale) && sizeof($va_labels_for_this_locale) > 0) { $this->postError(1125, _t('A preferred label for this locale already exists. Only one preferred label per locale is allowed.'), "BundlableLabelableBaseModelWithAttributes->saveBundlesForScreen()", $this->tableName() . '.preferred_labels'); $po_request->addActionErrors($this->errors(), $vs_f); $vb_error_inserting_pref_label = true; continue; } } if ($vb_check_for_dupe_labels && $this->checkForDupeLabel($vn_new_label_locale_id, $va_label_values)) { $this->postError(1125, _t('Value <em>%1</em> is already used and duplicates are not allowed', join("/", $va_label_values)), "BundlableLabelableBaseModelWithAttributes->saveBundlesForScreen()", $this->tableName() . '.preferred_labels'); $po_request->addActionErrors($this->errors(), 'preferred_labels'); $vb_error_inserting_pref_label = true; continue; } $vn_label_type_id = $po_request->getParameter($vs_placement_code . $vs_form_prefix . '_Pref' . 'type_id_new_' . $vn_c, pInteger); $this->addLabel($va_label_values, $vn_new_label_locale_id, $vn_label_type_id, true); if ($this->numErrors()) { $po_request->addActionErrors($this->errors(), $vs_f); $vb_error_inserting_pref_label = true; } } } } } } } // Add default label if needed (ie. if the user has failed to set at least one label or if they have deleted all existing labels) // This ensures at least one label is present for the record. If no labels are present then the // record may not be found in queries if ($this->getProperty('LABEL_TABLE_NAME')) { if ($vb_error_inserting_pref_label || !$this->addDefaultLabel($vn_new_label_locale_id)) { if (!$vb_error_inserting_pref_label) { $po_request->addActionErrors($this->errors(), 'preferred_labels'); } if ($vb_we_set_transaction) { $this->removeTransaction(false); } if ($vb_is_insert) { $this->_FIELD_VALUES[$this->primaryKey()] = null; // clear primary key, which doesn't actually exist since we rolled back the transaction foreach ($va_inserted_attributes_by_element as $vn_element_id => $va_failed_inserts) { // set attributes as "failed" (but with no error messages) so they stay set $this->setFailedAttributeInserts($vn_element_id, $va_failed_inserts); } } return false; } } unset($va_inserted_attributes_by_element); // save non-preferred labels if ($this->getProperty('LABEL_TABLE_NAME') && isset($va_fields_by_type['nonpreferred_label']) && is_array($va_fields_by_type['nonpreferred_label'])) { if (!$vb_batch) { foreach ($va_fields_by_type['nonpreferred_label'] as $vs_placement_code => $vs_f) { // check for existing labels to update (or delete) $va_nonpreferred_labels = $this->getNonPreferredLabels(null, false); foreach ($va_nonpreferred_labels as $vn_item_id => $va_labels_by_locale) { foreach ($va_labels_by_locale as $vn_locale_id => $va_label_list) { foreach ($va_label_list as $va_label) { if ($vn_label_locale_id = $po_request->getParameter($vs_placement_code . $vs_form_prefix . '_NPref' . 'locale_id_' . $va_label['label_id'], pString)) { if (is_array($va_label_values = $this->getLabelUIValuesFromRequest($po_request, $vs_placement_code . $vs_form_prefix, $va_label['label_id'], false))) { $vn_label_type_id = $po_request->getParameter($vs_placement_code . $vs_form_prefix . '_NPref' . 'type_id_' . $va_label['label_id'], pInteger); $this->editLabel($va_label['label_id'], $va_label_values, $vn_label_locale_id, $vn_label_type_id, false); if ($this->numErrors()) { foreach ($this->errors() as $o_e) { switch ($o_e->getErrorNumber()) { case 795: // field conflicts $po_request->addActionError($o_e, 'nonpreferred_labels'); break; default: $po_request->addActionError($o_e, $vs_f); break; } } } } } else { if ($po_request->getParameter($vs_placement_code . $vs_form_prefix . '_NPrefLabel_' . $va_label['label_id'] . '_delete', pString)) { // delete $this->removeLabel($va_label['label_id']); } } } } } } } // check for new labels to add foreach ($va_fields_by_type['nonpreferred_label'] as $vs_placement_code => $vs_f) { if ($vb_batch) { $vs_batch_mode = $po_request->getParameter($vs_placement_code . $vs_form_prefix . '_NPref_batch_mode', pString); switch ($vs_batch_mode) { case '_disabled_': // skip continue 2; break; case '_add_': // just try to add attribute as in normal non-batch save // noop break; case '_replace_': // remove all existing nonpreferred labels before trying to save $this->removeAllLabels(__CA_LABEL_TYPE_NONPREFERRED__); continue; case '_delete_': // remove all existing nonpreferred labels $this->removeAllLabels(__CA_LABEL_TYPE_NONPREFERRED__); continue 2; break; } } foreach ($_REQUEST as $vs_key => $vs_value) { if (!preg_match('/^' . $vs_placement_code . $vs_form_prefix . '_NPref' . 'locale_id_new_([\\d]+)/', $vs_key, $va_matches)) { continue; } $vn_c = intval($va_matches[1]); if ($vn_new_label_locale_id = $po_request->getParameter($vs_placement_code . $vs_form_prefix . '_NPref' . 'locale_id_new_' . $vn_c, pString)) { if (is_array($va_label_values = $this->getLabelUIValuesFromRequest($po_request, $vs_placement_code . $vs_form_prefix, 'new_' . $vn_c, false))) { $vn_new_label_type_id = $po_request->getParameter($vs_placement_code . $vs_form_prefix . '_NPref' . 'type_id_new_' . $vn_c, pInteger); $this->addLabel($va_label_values, $vn_new_label_locale_id, $vn_new_label_type_id, false); if ($this->numErrors()) { $po_request->addActionErrors($this->errors(), $vs_f); } } } } } } // save data in related tables if (isset($va_fields_by_type['related_table']) && is_array($va_fields_by_type['related_table'])) { foreach ($va_fields_by_type['related_table'] as $vs_placement_code => $vs_f) { $vn_table_num = $this->_DATAMODEL->getTableNum($vs_f); // get settings $va_bundle_settings = array(); foreach ($va_bundles as $va_bundle_info) { if ($va_bundle_info['placement_code'] == $vs_placement_code) { $va_bundle_settings = $va_bundle_info['settings']; break; } } switch ($vs_f) { # ------------------------------------- case 'ca_object_representations': // check for existing representations to update (or delete) $vs_prefix_stub = $vs_placement_code . $vs_form_prefix . '_'; $vb_allow_fetching_of_urls = (bool) $this->_CONFIG->get('allow_fetching_of_media_from_remote_urls'); $va_rep_ids_sorted = $va_rep_sort_order = explode(';', $po_request->getParameter($vs_prefix_stub . 'ObjectRepresentationBundleList', pString)); sort($va_rep_ids_sorted, SORT_NUMERIC); $va_reps = $this->getRepresentations(); if (!$vb_batch && is_array($va_reps)) { foreach ($va_reps as $vn_i => $va_rep) { $this->clearErrors(); if (strlen($po_request->getParameter($vs_prefix_stub . 'access_' . $va_rep['representation_id'], pInteger)) > 0) { if ($vb_allow_fetching_of_urls && ($vs_path = $_REQUEST[$vs_prefix_stub . 'media_url_' . $va_rep['representation_id']])) { $va_tmp = explode('/', $vs_path); $vs_original_name = array_pop($va_tmp); } else { $vs_path = $_FILES[$vs_prefix_stub . 'media_' . $va_rep['representation_id']]['tmp_name']; $vs_original_name = $_FILES[$vs_prefix_stub . 'media_' . $va_rep['representation_id']]['name']; } $vn_is_primary = $po_request->getParameter($vs_prefix_stub . 'is_primary_' . $va_rep['representation_id'], pString) != '' ? $po_request->getParameter($vs_prefix_stub . 'is_primary_' . $va_rep['representation_id'], pInteger) : null; $vn_locale_id = $po_request->getParameter($vs_prefix_stub . 'locale_id_' . $va_rep['representation_id'], pInteger); $vs_idno = $po_request->getParameter($vs_prefix_stub . 'idno_' . $va_rep['representation_id'], pString); $vn_access = $po_request->getParameter($vs_prefix_stub . 'access_' . $va_rep['representation_id'], pInteger); $vn_status = $po_request->getParameter($vs_prefix_stub . 'status_' . $va_rep['representation_id'], pInteger); $vs_rep_label = trim($po_request->getParameter($vs_prefix_stub . 'rep_label_' . $va_rep['representation_id'], pString)); //$vn_rep_type_id = $po_request->getParameter($vs_prefix_stub.'rep_type_id'.$va_rep['representation_id'], pInteger); // Get user-specified center point (images only) $vn_center_x = $po_request->getParameter($vs_prefix_stub . 'center_x_' . $va_rep['representation_id'], pString); $vn_center_y = $po_request->getParameter($vs_prefix_stub . 'center_y_' . $va_rep['representation_id'], pString); $vn_rank = null; if (($vn_rank_index = array_search($va_rep['representation_id'], $va_rep_sort_order)) !== false) { $vn_rank = $va_rep_ids_sorted[$vn_rank_index]; } $this->editRepresentation($va_rep['representation_id'], $vs_path, $vn_locale_id, $vn_status, $vn_access, $vn_is_primary, array('idno' => $vs_idno), array('original_filename' => $vs_original_name, 'rank' => $vn_rank, 'centerX' => $vn_center_x, 'centerY' => $vn_center_y)); if ($this->numErrors()) { //$po_request->addActionErrors($this->errors(), $vs_f, $va_rep['representation_id']); foreach ($this->errors() as $o_e) { switch ($o_e->getErrorNumber()) { case 795: // field conflicts $po_request->addActionError($o_e, $vs_f, $va_rep['representation_id']); break; default: $po_request->addActionError($o_e, $vs_f, $va_rep['representation_id']); break; } } } if ($vs_rep_label) { // // Set representation label // $t_rep = new ca_object_representations(); if ($this->inTransaction()) { $t_rep->setTransaction($this->getTransaction()); } global $g_ui_locale_id; if ($t_rep->load($va_rep['representation_id'])) { $t_rep->setMode(ACCESS_WRITE); $t_rep->replaceLabel(array('name' => $vs_rep_label), $g_ui_locale_id, null, true); if ($t_rep->numErrors()) { $po_request->addActionErrors($t_rep->errors(), $vs_f, $va_rep['representation_id']); } } } } else { // is it a delete key? $this->clearErrors(); if ($po_request->getParameter($vs_prefix_stub . $va_rep['representation_id'] . '_delete', pInteger) > 0) { // delete! $this->removeRepresentation($va_rep['representation_id']); if ($this->numErrors()) { $po_request->addActionErrors($this->errors(), $vs_f, $va_rep['representation_id']); } } } } } if ($vb_batch) { $vs_batch_mode = $_REQUEST[$vs_prefix_stub . 'batch_mode']; if ($vs_batch_mode == '_disabled_') { break; } if ($vs_batch_mode == '_replace_') { $this->removeAllRepresentations(); } if ($vs_batch_mode == '_delete_') { $this->removeAllRepresentations(); break; } } // check for new representations to add $va_file_list = $_FILES; foreach ($_REQUEST as $vs_key => $vs_value) { if (!preg_match('/^' . $vs_prefix_stub . 'media_url_new_([\\d]+)$/', $vs_key, $va_matches)) { continue; } $va_file_list[$vs_key] = array('url' => $vs_value); } foreach ($va_file_list as $vs_key => $va_values) { $this->clearErrors(); if (!preg_match('/^' . $vs_prefix_stub . 'media_new_([\\d]+)$/', $vs_key, $va_matches) && ($vb_allow_fetching_of_urls && !preg_match('/^' . $vs_prefix_stub . 'media_url_new_([\\d]+)$/', $vs_key, $va_matches) || !$vb_allow_fetching_of_urls)) { continue; } if ($vs_upload_type = $po_request->getParameter($vs_prefix_stub . 'upload_typenew_' . $va_matches[1], pString)) { $po_request->user->setVar('defaultRepresentationUploadType', $vs_upload_type); } $vn_type_id = $po_request->getParameter($vs_prefix_stub . 'type_id_new_' . $va_matches[1], pInteger); if ($vn_existing_rep_id = $po_request->getParameter($vs_prefix_stub . 'idnew_' . $va_matches[1], pInteger)) { $this->addRelationship('ca_object_representations', $vn_existing_rep_id, $vn_type_id); } else { if ($vb_allow_fetching_of_urls && ($vs_path = $va_values['url'])) { $va_tmp = explode('/', $vs_path); $vs_original_name = array_pop($va_tmp); } else { $vs_path = $va_values['tmp_name']; $vs_original_name = $va_values['name']; } if (!$vs_path) { continue; } $vn_rep_type_id = $po_request->getParameter($vs_prefix_stub . 'rep_type_id_new_' . $va_matches[1], pInteger); if (!$vn_rep_type_id && !($vn_rep_type_id = caGetDefaultItemID('object_representation_types'))) { require_once __CA_MODELS_DIR__ . '/ca_lists.php'; $t_list = new ca_lists(); if (is_array($va_rep_type_ids = $t_list->getItemsForList('object_representation_types', array('idsOnly' => true, 'enabledOnly' => true)))) { $vn_rep_type_id = array_shift($va_rep_type_ids); } } if (is_array($pa_options['existingRepresentationMap']) && isset($pa_options['existingRepresentationMap'][$vs_path]) && $pa_options['existingRepresentationMap'][$vs_path]) { $this->addRelationship('ca_object_representations', $pa_options['existingRepresentationMap'][$vs_path], $vn_type_id); break; } $vs_rep_label = trim($po_request->getParameter($vs_prefix_stub . 'rep_label_new_' . $va_matches[1], pString)); $vn_locale_id = $po_request->getParameter($vs_prefix_stub . 'locale_id_new_' . $va_matches[1], pInteger); $vs_idno = $po_request->getParameter($vs_prefix_stub . 'idno_new_' . $va_matches[1], pString); $vn_status = $po_request->getParameter($vs_prefix_stub . 'status_new_' . $va_matches[1], pInteger); $vn_access = $po_request->getParameter($vs_prefix_stub . 'access_new_' . $va_matches[1], pInteger); $vn_is_primary = $po_request->getParameter($vs_prefix_stub . 'is_primary_new_' . $va_matches[1], pInteger); // Get user-specified center point (images only) $vn_center_x = $po_request->getParameter($vs_prefix_stub . 'center_x_new_' . $va_matches[1], pString); $vn_center_y = $po_request->getParameter($vs_prefix_stub . 'center_y_new_' . $va_matches[1], pString); $t_rep = $this->addRepresentation($vs_path, $vn_rep_type_id, $vn_locale_id, $vn_status, $vn_access, $vn_is_primary, array('name' => $vs_rep_label, 'idno' => $vs_idno), array('original_filename' => $vs_original_name, 'returnRepresentation' => true, 'centerX' => $vn_center_x, 'centerY' => $vn_center_y, 'type_id' => $vn_type_id)); // $vn_type_id = *relationship* type_id (as opposed to representation type) if ($this->numErrors()) { $po_request->addActionErrors($this->errors(), $vs_f, 'new_' . $va_matches[1]); } else { if ($t_rep && is_array($pa_options['existingRepresentationMap'])) { $pa_options['existingRepresentationMap'][$vs_path] = $t_rep->getPrimaryKey(); } } } } break; # ------------------------------------- # ------------------------------------- case 'ca_entities': case 'ca_places': case 'ca_objects': case 'ca_collections': case 'ca_occurrences': case 'ca_list_items': case 'ca_object_lots': case 'ca_storage_locations': case 'ca_loans': case 'ca_movements': case 'ca_tour_stops': $this->_processRelated($po_request, $vs_f, $vs_form_prefix, $vs_placement_code, array('batch' => $vb_batch, 'settings' => $va_bundle_settings)); break; # ------------------------------------- # ------------------------------------- case 'ca_representation_annotations': if ($vb_batch) { break; } // not supported in batch mode $this->_processRepresentationAnnotations($po_request, $vs_form_prefix, $vs_placement_code); break; # ------------------------------------- } } } // save data for "specials" if (isset($va_fields_by_type['special']) && is_array($va_fields_by_type['special'])) { foreach ($va_fields_by_type['special'] as $vs_placement_code => $vs_f) { // get settings $va_bundle_settings = array(); foreach ($va_bundles as $va_bundle_info) { if ('P' . $va_bundle_info['placement_id'] == $vs_placement_code) { $va_bundle_settings = $va_bundle_info['settings']; break; } } switch ($vs_f) { # ------------------------------------- // This bundle is only available when editing objects of type ca_representation_annotations case 'ca_representation_annotation_properties': if ($vb_batch) { break; } // not supported in batch mode if (!$this->useInEditor()) { break; } foreach ($this->getPropertyList() as $vs_property) { $this->setPropertyValue($vs_property, $po_request->getParameter("{$vs_placement_code}{$vs_form_prefix}{$vs_property}", pString)); } if (!$this->validatePropertyValues()) { $po_request->addActionErrors($this->errors(), 'ca_representation_annotation_properties', 'general'); } $this->update(); break; # ------------------------------------- // This bundle is only available for types which support set membership # ------------------------------------- // This bundle is only available for types which support set membership case 'ca_sets': // check for existing labels to delete (no updating supported) require_once __CA_MODELS_DIR__ . '/ca_sets.php'; require_once __CA_MODELS_DIR__ . '/ca_set_items.php'; $t_set = new ca_sets(); if (!$vb_batch) { $va_sets = caExtractValuesByUserLocale($t_set->getSetsForItem($this->tableNum(), $this->getPrimaryKey(), array('user_id' => $po_request->getUserID()))); foreach ($va_sets as $vn_set_id => $va_set_info) { $vn_item_id = $va_set_info['item_id']; if ($po_request->getParameter("{$vs_placement_code}{$vs_form_prefix}_set_id_{$vn_item_id}_delete", pString)) { // delete $t_set->load($va_set_info['set_id']); $t_set->removeItem($this->getPrimaryKey(), $po_request->getUserID()); // remove *all* instances of the item in the set, not just the specified id if ($t_set->numErrors()) { $po_request->addActionErrors($t_set->errors(), $vs_f); } } } } if ($vb_batch) { $vs_batch_mode = $_REQUEST["{$vs_placement_code}{$vs_form_prefix}_batch_mode"]; if ($vs_batch_mode == '_disabled_') { break; } if ($vs_batch_mode == '_replace_') { $t_set->removeItemFromAllSets($this->tableNum(), $this->getPrimaryKey()); } if ($vs_batch_mode == '_delete_') { $t_set->removeItemFromAllSets($this->tableNum(), $this->getPrimaryKey()); break; } } foreach ($_REQUEST as $vs_key => $vs_value) { if (!preg_match("/{$vs_placement_code}{$vs_form_prefix}_set_id_new_([\\d]+)/", $vs_key, $va_matches)) { continue; } $vn_c = intval($va_matches[1]); if ($vn_new_set_id = $po_request->getParameter("{$vs_placement_code}{$vs_form_prefix}_set_id_new_{$vn_c}", pString)) { $t_set->load($vn_new_set_id); $t_set->addItem($this->getPrimaryKey(), null, $po_request->getUserID()); if ($t_set->numErrors()) { $po_request->addActionErrors($t_set->errors(), $vs_f); } } } break; # ------------------------------------- // This bundle is only available for types which support set membership # ------------------------------------- // This bundle is only available for types which support set membership case 'ca_set_items': if ($vb_batch) { break; } // not supported in batch mode // check for existing labels to delete (no updating supported) require_once __CA_MODELS_DIR__ . '/ca_sets.php'; require_once __CA_MODELS_DIR__ . '/ca_set_items.php'; $va_rids = explode(';', $po_request->getParameter("{$vs_placement_code}{$vs_form_prefix}setRowIDList", pString)); $this->reorderItems($va_rids, array('user_id' => $po_request->getUserID(), 'treatRowIDsAsRIDs' => true, 'deleteExcludedItems' => true)); break; # ------------------------------------- // This bundle is only available for ca_search_forms # ------------------------------------- // This bundle is only available for ca_search_forms case 'ca_search_form_elements': if ($vb_batch) { break; } // not supported in batch mode // save settings $va_settings = $this->getAvailableSettings(); foreach ($va_settings as $vs_setting => $va_setting_info) { if (isset($_REQUEST['setting_' . $vs_setting])) { $vs_setting_val = $po_request->getParameter('setting_' . $vs_setting, pString); $this->setSetting($vs_setting, $vs_setting_val); $this->update(); } } break; # ------------------------------------- // This bundle is only available for ca_bundle_displays # ------------------------------------- // This bundle is only available for ca_bundle_displays case 'ca_bundle_display_placements': if ($vb_batch) { break; } // not supported in batch mode $this->savePlacementsFromHTMLForm($po_request, $vs_form_prefix, $vs_placement_code); break; # ------------------------------------- // This bundle is only available for ca_bundle_displays # ------------------------------------- // This bundle is only available for ca_bundle_displays case 'ca_bundle_display_type_restrictions': if ($vb_batch) { break; } // not supported in batch mode $this->saveTypeRestrictionsFromHTMLForm($po_request, $vs_form_prefix, $vs_placement_code); break; # ------------------------------------- // This bundle is only available for ca_search_forms # ------------------------------------- // This bundle is only available for ca_search_forms case 'ca_search_form_placements': if ($vb_batch) { break; } // not supported in batch mode $this->savePlacementsFromHTMLForm($po_request, $vs_form_prefix, $vs_placement_code); break; # ------------------------------------- // This bundle is only available for ca_editor_ui # ------------------------------------- // This bundle is only available for ca_editor_ui case 'ca_editor_ui_screens': if ($vb_batch) { break; } // not supported in batch mode global $g_ui_locale_id; require_once __CA_MODELS_DIR__ . '/ca_editor_ui_screens.php'; $va_screen_ids = explode(';', $po_request->getParameter("{$vs_placement_code}{$vs_form_prefix}_ScreenBundleList", pString)); foreach ($_REQUEST as $vs_key => $vs_val) { if (is_array($vs_val)) { continue; } if (!($vs_val = trim($vs_val))) { continue; } if (preg_match("!^{$vs_placement_code}{$vs_form_prefix}_name_new_([\\d]+)\$!", $vs_key, $va_matches)) { if (!($t_screen = $this->addScreen($vs_val, $g_ui_locale_id, 'screen_' . $this->getPrimaryKey() . '_' . $va_matches[1]))) { break; } if ($vn_fkey = array_search("new_" . $va_matches[1], $va_screen_ids)) { $va_screen_ids[$vn_fkey] = $t_screen->getPrimaryKey(); } else { $va_screen_ids[] = $t_screen->getPrimaryKey(); } continue; } if (preg_match("!^{$vs_placement_code}{$vs_form_prefix}_([\\d]+)_delete\$!", $vs_key, $va_matches)) { $this->removeScreen($va_matches[1]); if ($vn_fkey = array_search($va_matches[1], $va_screen_ids)) { unset($va_screen_ids[$vn_fkey]); } } } $this->reorderScreens($va_screen_ids); break; # ------------------------------------- // This bundle is only available for ca_editor_ui_screens # ------------------------------------- // This bundle is only available for ca_editor_ui_screens case 'ca_editor_ui_bundle_placements': if ($vb_batch) { break; } // not supported in batch mode $this->savePlacementsFromHTMLForm($po_request, $vs_form_prefix, $vs_placement_code); break; # ------------------------------------- // This bundle is only available for ca_editor_uis # ------------------------------------- // This bundle is only available for ca_editor_uis case 'ca_editor_ui_type_restrictions': if ($vb_batch) { break; } // not supported in batch mode $this->saveTypeRestrictionsFromHTMLForm($po_request, $vs_form_prefix, $vs_placement_code); break; # ------------------------------------- // This bundle is only available for ca_editor_ui_screens # ------------------------------------- // This bundle is only available for ca_editor_ui_screens case 'ca_editor_ui_screen_type_restrictions': if ($vb_batch) { break; } // not supported in batch mode $this->saveTypeRestrictionsFromHTMLForm($po_request, $vs_form_prefix, $vs_placement_code); break; # ------------------------------------- // This bundle is only available for ca_tours # ------------------------------------- // This bundle is only available for ca_tours case 'ca_tour_stops_list': if ($vb_batch) { break; } // not supported in batch mode global $g_ui_locale_id; require_once __CA_MODELS_DIR__ . '/ca_tour_stops.php'; $va_stop_ids = explode(';', $po_request->getParameter("{$vs_placement_code}{$vs_form_prefix}_StopBundleList", pString)); foreach ($_REQUEST as $vs_key => $vs_val) { if (!($vs_val = trim($vs_val))) { continue; } if (preg_match("!^{$vs_placement_code}{$vs_form_prefix}_name_new_([\\d]+)\$!", $vs_key, $va_matches)) { $vn_type_id = $_REQUEST["{$vs_placement_code}{$vs_form_prefix}_type_id_new_" . $va_matches[1]]; if (!($t_stop = $this->addStop($vs_val, $vn_type_id, $g_ui_locale_id, mb_substr(preg_replace('![^A-Za-z0-9_]+!', '_', $vs_val), 0, 255)))) { break; } if ($vn_fkey = array_search("new_" . $va_matches[1], $va_stop_ids)) { $va_stop_ids[$vn_fkey] = $t_stop->getPrimaryKey(); } else { $va_stop_ids[] = $t_stop->getPrimaryKey(); } continue; } if (preg_match("!^{$vs_placement_code}{$vs_form_prefix}_([\\d]+)_delete\$!", $vs_key, $va_matches)) { $this->removeStop($va_matches[1]); if ($vn_fkey = array_search($va_matches[1], $va_stop_ids)) { unset($va_stop_ids[$vn_fkey]); } } } $this->reorderStops($va_stop_ids); break; # ------------------------------------- # ------------------------------------- case 'ca_user_groups': if ($vb_batch) { break; } // not supported in batch mode if (!$po_request->user->canDoAction('is_administrator') && $po_request->getUserID() != $this->get('user_id')) { break; } // don't save if user is not owner require_once __CA_MODELS_DIR__ . '/ca_user_groups.php'; $va_groups_to_set = $va_group_effective_dates = array(); foreach ($_REQUEST as $vs_key => $vs_val) { if (preg_match("!^{$vs_placement_code}{$vs_form_prefix}_id(.*)\$!", $vs_key, $va_matches)) { $vs_effective_date = $po_request->getParameter("{$vs_placement_code}{$vs_form_prefix}_effective_date_" . $va_matches[1], pString); $vn_group_id = (int) $po_request->getParameter("{$vs_placement_code}{$vs_form_prefix}_id" . $va_matches[1], pInteger); $vn_access = $po_request->getParameter("{$vs_placement_code}{$vs_form_prefix}_access_" . $va_matches[1], pInteger); if ($vn_access > 0) { $va_groups_to_set[$vn_group_id] = $vn_access; $va_group_effective_dates[$vn_group_id] = $vs_effective_date; } } } $this->setUserGroups($va_groups_to_set, $va_group_effective_dates, array('user_id' => $po_request->getUserID())); break; # ------------------------------------- # ------------------------------------- case 'ca_users': if ($vb_batch) { break; } // not supported in batch mode if (!$po_request->user->canDoAction('is_administrator') && $po_request->getUserID() != $this->get('user_id')) { break; } // don't save if user is not owner require_once __CA_MODELS_DIR__ . '/ca_users.php'; $va_users_to_set = $va_user_effective_dates = array(); foreach ($_REQUEST as $vs_key => $vs_val) { if (preg_match("!^{$vs_placement_code}{$vs_form_prefix}_id(.*)\$!", $vs_key, $va_matches)) { $vs_effective_date = $po_request->getParameter("{$vs_placement_code}{$vs_form_prefix}_effective_date_" . $va_matches[1], pString); $vn_user_id = (int) $po_request->getParameter("{$vs_placement_code}{$vs_form_prefix}_id" . $va_matches[1], pInteger); $vn_access = $po_request->getParameter("{$vs_placement_code}{$vs_form_prefix}_access_" . $va_matches[1], pInteger); if ($vn_access > 0) { $va_users_to_set[$vn_user_id] = $vn_access; $va_user_effective_dates[$vn_user_id] = $vs_effective_date; } } } $this->setUsers($va_users_to_set, $va_user_effective_dates); break; # ------------------------------------- # ------------------------------------- case 'settings': if ($vb_batch) { break; } // not supported in batch mode $this->setSettingsFromHTMLForm($po_request, array('id' => $vs_form_prefix . '_', 'placement_code' => $vs_placement_code)); break; # ------------------------------- // This bundle is only available when editing objects of type ca_object_representations # ------------------------------- // This bundle is only available when editing objects of type ca_object_representations case 'ca_object_representations_media_display': if ($vb_batch) { break; } // not supported in batch mode $va_versions_to_process = null; if ($vb_use_options = (bool) $po_request->getParameter("{$vs_placement_code}{$vs_form_prefix}_derivative_options_selector", pInteger)) { // update only specified versions $va_versions_to_process = $po_request->getParameter("{$vs_placement_code}{$vs_form_prefix}_set_versions", pArray); } if (!is_array($va_versions_to_process) || !sizeof($va_versions_to_process)) { $va_versions_to_process = array('_all'); } if ($vb_use_options && $po_request->getParameter("{$vs_placement_code}{$vs_form_prefix}_derivative_options_mode", pString) == 'timecode') { // timecode if (!(string) ($vs_timecode = $po_request->getParameter("{$vs_placement_code}{$vs_form_prefix}_derivative_options_mode_timecode_value", pString))) { $vs_timecode = "1s"; } // $o_media = new Media(); if ($o_media->read($this->getMediaPath('media', 'original'))) { $va_files = $o_media->writePreviews(array('force' => true, 'outputDirectory' => $this->_CONFIG->get("taskqueue_tmp_directory"), 'minNumberOfFrames' => 1, 'maxNumberOfFrames' => 1, 'startAtTime' => $vs_timecode, 'endAtTime' => $vs_timecode, 'width' => 720, 'height' => 540)); if (sizeof($va_files)) { $this->set('media', array_shift($va_files)); } } } else { if ($vb_use_options && $po_request->getParameter("{$vs_placement_code}{$vs_form_prefix}_derivative_options_mode", pString) == 'page') { if (!(int) ($vn_page = $po_request->getParameter("{$vs_placement_code}{$vs_form_prefix}_derivative_options_mode_page_value", pInteger))) { $vn_page = 1; } // $o_media = new Media(); if ($o_media->read($this->getMediaPath('media', 'original'))) { $va_files = $o_media->writePreviews(array('force' => true, 'outputDirectory' => $this->_CONFIG->get("taskqueue_tmp_directory"), 'numberOfPages' => 1, 'startAtPage' => $vn_page, 'width' => 2048, 'height' => 2048)); if (sizeof($va_files)) { $this->set('media', array_shift($va_files)); } } } else { // process file as new upload $vs_key = "{$vs_placement_code}{$vs_form_prefix}_url"; if (($vs_media_url = trim($po_request->getParameter($vs_key, pString))) && isURL($vs_media_url)) { $this->set('media', $vs_media_url); } else { $vs_key = "{$vs_placement_code}{$vs_form_prefix}_media"; if (isset($_FILES[$vs_key])) { $this->set('media', $_FILES[$vs_key]['tmp_name'], array('original_filename' => $_FILES[$vs_key]['name'])); } } } } if ($this->changed('media')) { $this->update($vs_version != '_all' ? array('updateOnlyMediaVersions' => $va_versions_to_process) : array()); if ($this->numErrors()) { $po_request->addActionErrors($this->errors(), 'ca_object_representations_media_display', 'general'); } } break; # ------------------------------- // This bundle is only available when editing objects of type ca_object_representations # ------------------------------- // This bundle is only available when editing objects of type ca_object_representations case 'ca_object_representation_captions': if ($vb_batch) { return null; } // not supported in batch mode $va_users_to_set = array(); foreach ($_REQUEST as $vs_key => $vs_val) { if (preg_match("!^{$vs_placement_code}{$vs_form_prefix}_locale_id(.*)\$!", $vs_key, $va_matches)) { $vn_locale_id = (int) $po_request->getParameter("{$vs_placement_code}{$vs_form_prefix}_locale_id" . $va_matches[1], pInteger); $this->addCaptionFile($_FILES["{$vs_placement_code}{$vs_form_prefix}_caption_file" . $va_matches[1]]['tmp_name'], $vn_locale_id, array('originalFilename' => $_FILES["{$vs_placement_code}{$vs_form_prefix}_captions_caption_file" . $va_matches[1]]['name'])); } else { // any to delete? if (preg_match("!^{$vs_placement_code}{$vs_form_prefix}_([\\d]+)_delete\$!", $vs_key, $va_matches)) { $this->removeCaptionFile((int) $va_matches[1]); } } } break; # ------------------------------- // This bundle is only available for relationships that include an object on one end # ------------------------------- // This bundle is only available for relationships that include an object on one end case 'ca_object_representation_chooser': if ($vb_batch) { return null; } // not supported in batch mode if (!is_array($va_rep_ids = $po_request->getParameter("{$vs_placement_code}{$vs_form_prefix}", pArray))) { $va_rep_ids = array(); } if ($vs_element_code = caGetOption(array('elementCode', 'element_code'), $va_bundle_settings, null)) { if (!is_array($va_current_rep_ids = $this->get($this->tableName() . "." . $vs_element_code, array('returnAsArray' => true, 'idsOnly' => true)))) { $va_current_rep_ids = $va_current_rep_id_with_structure = array(); } else { $va_current_rep_id_with_structure = $this->get($this->tableName() . "." . $vs_element_code, array('returnWithStructure' => true, 'idsOnly' => true)); } $va_rep_to_attr_id = array(); foreach ($va_rep_ids as $vn_rep_id) { if (in_array($vn_rep_id, $va_current_rep_ids)) { continue; } $this->addAttribute(array($vs_element_code => $vn_rep_id), $vs_element_code); } foreach ($va_current_rep_id_with_structure as $vn_id => $va_vals_by_attr_id) { foreach ($va_vals_by_attr_id as $vn_attribute_id => $va_val) { if (!in_array($va_val[$vs_element_code], $va_rep_ids)) { $this->removeAttribute($vn_attribute_id); } } } $this->update(); } break; # ------------------------------- // This bundle is only available for objects # ------------------------------- // This bundle is only available for objects case 'ca_objects_location': if ($vb_batch) { return null; } // not supported in batch mode if (!$po_request->user->canDoAction('can_edit_ca_objects')) { break; } if ($vn_location_id = $po_request->getParameter("{$vs_placement_code}{$vs_form_prefix}_location_idnew_0", pInteger)) { if (is_array($va_relationship_types = caGetOption('ca_storage_locations_relationshipType', $va_bundle_settings, null)) && ($vn_relationship_type_id = array_shift($va_relationship_types))) { $this->addRelationship('ca_storage_locations', $vn_location_id, $vn_relationship_type_id, null, null, null, null, array('allowDuplicates' => true)); if ($this->numErrors()) { $po_request->addActionErrors($this->errors(), 'ca_objects_location', 'general'); } } } break; # ------------------------------- // This bundle is only available for objects # ------------------------------- // This bundle is only available for objects case 'ca_objects_history': if ($vb_batch) { return null; } // not supported in batch mode if (!$po_request->user->canDoAction('can_edit_ca_objects')) { break; } // set storage location if ($vn_location_id = $po_request->getParameter("{$vs_placement_code}{$vs_form_prefix}_location_idnew_0", pInteger)) { if (is_array($va_relationship_types = caGetOption('ca_storage_locations_showRelationshipTypes', $va_bundle_settings, null)) && ($vn_relationship_type_id = array_shift($va_relationship_types))) { $this->addRelationship('ca_storage_locations', $vn_location_id, $vn_relationship_type_id, null, null, null, null, array('allowDuplicates' => true)); if ($this->numErrors()) { $po_request->addActionErrors($this->errors(), 'ca_objects_history', 'general'); } } } // set loan if ($vn_loan_id = $po_request->getParameter("{$vs_placement_code}{$vs_form_prefix}_loan_idnew_0", pInteger)) { if ($vn_loan_type_id = $po_request->getParameter("{$vs_placement_code}{$vs_form_prefix}_loan_type_idnew_0", pInteger)) { $this->addRelationship('ca_loans', $vn_loan_id, $vn_loan_type_id); if ($this->numErrors()) { $po_request->addActionErrors($this->errors(), 'ca_objects_history', 'general'); } } } break; # ------------------------------- // This bundle is only available for objects # ------------------------------- // This bundle is only available for objects case 'ca_objects_deaccession': // object deaccession information if (!$vb_batch && !$this->getPrimaryKey()) { return null; } // not supported for new records if (!$po_request->user->canDoAction('can_edit_ca_objects')) { break; } $this->set('is_deaccessioned', $vb_is_deaccessioned = $po_request->getParameter("{$vs_placement_code}{$vs_form_prefix}is_deaccessioned", pInteger)); $this->set('deaccession_notes', $po_request->getParameter("{$vs_placement_code}{$vs_form_prefix}deaccession_notes", pString)); $this->set('deaccession_type_id', $x = $po_request->getParameter("{$vs_placement_code}{$vs_form_prefix}deaccession_type_id", pString)); $this->set('deaccession_date', $po_request->getParameter("{$vs_placement_code}{$vs_form_prefix}deaccession_date", pString)); if ($vb_is_deaccessioned && (bool) $this->getAppConfig()->get('deaccession_force_access_private')) { $this->get('access', 0); } // set access to private for accessioned items $this->update(); break; # ------------------------------- // This bundle is only available for objects # ------------------------------- // This bundle is only available for objects case 'ca_object_checkouts': // object checkout information if ($vb_batch) { return null; } // not supported in batch mode if (!$vb_batch && !$this->getPrimaryKey()) { return null; } // not supported for new records if (!$po_request->user->canDoAction('can_edit_ca_objects')) { break; } // NOOP (for now) break; # ------------------------------- } } } BaseModel::unsetChangeLogUnitID(); $va_bundle_names = array(); foreach ($va_bundles as $va_bundle) { $vs_bundle_name = str_replace('ca_attribute_', '', $va_bundle['bundle_name']); if (!$this->getAppDatamodel()->getInstanceByTableName($vs_bundle_name, true)) { $vs_bundle_name = $this->tableName() . '.' . $vs_bundle_name; } $va_bundle_names[] = $vs_bundle_name; } // validate metadata dictionary rules $va_violations = $this->validateUsingMetadataDictionaryRules(array('bundles' => $va_bundle_names)); if (sizeof($va_violations)) { if ($vb_we_set_transaction && isset($va_violations['ERR']) && is_array($va_violations['ERR']) && sizeof($va_violations['ERR']) > 0) { BaseModel::unsetChangeLogUnitID(); $this->removeTransaction(false); $this->_FIELD_VALUES[$this->primaryKey()] = null; // clear primary key since transaction has been rolled back foreach ($va_violations['ERR'] as $vs_bundle => $va_errs_by_bundle) { foreach ($va_errs_by_bundle as $vn_i => $va_rule) { $vs_bundle = str_replace($this->tableName() . ".", "", $vs_bundle); $po_request->addActionErrors(array(new Error(1100, $va_rule['rule_settings']['violationMessage'], "BundlableLabelableBaseModelWithAttributes->saveBundlesForScreen()", 'MetadataDictionary', false, false)), $vs_bundle, 'general'); } } return false; } } // prepopulate fields $vs_prepopulate_cfg = $this->getAppConfig()->get('prepopulate_config'); $o_prepopulate_conf = Configuration::load($vs_prepopulate_cfg); if ($o_prepopulate_conf->get('prepopulate_fields_on_save')) { $this->prepopulateFields(array('prepopulateConfig' => $vs_prepopulate_cfg)); } if ($vb_dryrun) { $this->removeTransaction(false); } if ($vb_we_set_transaction) { $this->removeTransaction(true); } return true; }
/** * Update annotation. If time code of annotation has changed media preview will be regenerated. * You can force the media preview to be regenerated whether the time code has changed or not * by passing the 'forcePreviewGeneration' option. * * @param array $pa_options An array of options: * forcePreviewGeneration = if set preview media will be regenerated whether time code has changed or not. Default is false. * @return bool True on success, false on failure */ public function update($pa_options = null) { $this->set('type_code', $vs_type = $this->getAnnotationType()); if (!$this->opo_annotations_properties->validate()) { $this->errors = $this->opo_annotations_properties->errors; return false; } $this->set('props', $this->opo_annotations_properties->getPropertyValues()); if (!$this->getAppConfig()->get('dont_generate_annotation_previews') && $this->getPrimaryKey() && ($this->changed('props') || isset($pa_options['forcePreviewGeneration']) && $pa_options['forcePreviewGeneration'])) { $vs_start = $this->getPropertyValue('startTimecode'); $vs_end = $this->getPropertyValue('endTimecode'); $va_data['start'] = $vs_start; $va_data['end'] = $vs_end; $t_rep = new ca_object_representations($this->get('representation_id')); if (($vs_file = $t_rep->getMediaPath('media', 'original')) && file_exists($vs_file)) { $o_media = new Media(); if ($o_media->read($vs_file)) { if ($o_media->writeClip($vs_file = tempnam(caGetTempDirPath(), 'annotationPreview'), $vs_start, $vs_end)) { $this->set('preview', $vs_file); } } } } $vn_rc = parent::update($pa_options); if (!$this->numErrors()) { $this->opo_annotations_properties = $this->loadProperties($vs_type); } if ($vs_file) { @unlink($vs_file); } return $vn_rc; }
function render($po_pdf, $pn_x = null, $pn_y = null) { switch (get_class($this->opo_form)) { case 'PrintForms': if ($va_element_info = $this->opa_element_info) { $vn_x = $this->opo_form->getValueInPoints($va_element_info['left']); $vn_y = $this->opo_form->getFormSetting('pageHeight') - $this->opo_form->getValueInPoints($va_element_info['top']); } break; case 'PrintSubForms': if ($va_element_info = $this->opa_element_info) { $vn_x = $pn_x + $this->opo_form->getValueInPoints($va_element_info['left']); $vn_y = $pn_y - $this->opo_form->getValueInPoints($va_element_info['top']); } break; default: $this->opo_form->postError(2275, _t("Invalid class '%1'", get_class($this->opo_form)), "PrintFormImageElement->render()"); break; } $va_style = $this->opo_form->getStyle($va_element_info['style']); $vn_w = $this->opo_form->getValueInPoints($va_element_info['width']); $vn_h = $this->opo_form->getValueInPoints($va_element_info['height']); if ($this->opo_form->getPDFLibrary() == __PDF_LIBRARY_ZEND__) { $o_media = new Media(); if ($o_media->read($this->getValue())) { $va_properties = $o_media->getProperties(); $vn_image_width = $va_properties['width']; $vn_image_height = $va_properties['height']; if ($vn_image_width > $vn_image_height) { $vn_r = $vn_w / $vn_image_width; } else { $vn_r = $vn_h / $vn_image_height; } $vn_image_width *= $vn_r; $vn_image_height *= $vn_r; $po_page = $po_pdf->pages[sizeof($po_pdf->pages) - 1]; try { if ($vo_image = $this->opo_form->loadImage($po_pdf, $this->getValue())) { $po_page->drawImage($vo_image, $vn_x, $vn_y - $vn_h, $vn_x + $vn_image_width, $vn_y - $vn_h + $vn_image_height); } else { return false; } } catch (Exception $e) { return false; } } } else { if ($vn_image_ref = $this->opo_form->loadImage($po_pdf, $this->getValue())) { if (!($vs_display = $va_element_info['display'])) { $vs_display = $va_style['display']; } if (!in_array($vs_display, array('nofit', 'clip', 'meet', 'auto', 'slice', 'entire'))) { $vs_display = 'meet'; } $vs_opts = "fitmethod={$vs_display} boxsize={" . $vn_w . " " . $vn_h . "}"; if ($va_element_info['rotate']) { $vs_opts .= ' rotate=' . intval($va_element_info['rotate']); } else { if ($va_style['rotate']) { $vs_opts .= ' rotate=' . intval($va_style['rotate']); } } $po_pdf->fit_image($vn_image_ref, $vn_x, $vn_y - $vn_h, $vs_opts); } } return true; }
public function write($filepath, $mimetype, $pa_options = null) { if (!$this->handle) { return false; } if (!($ext = $this->info["EXPORT"][$mimetype])) { # this plugin can't write this mimetype return false; } # is mimetype valid? switch ($mimetype) { # ------------------------------------ case 'image/jpeg': $vn_preview_width = $this->properties["width"]; $vn_preview_height = $this->properties["height"]; if (caMediaPluginFFfmpegInstalled($this->ops_path_to_ffmpeg)) { if (($vn_start_secs = $this->properties["duration"] / 8) > 120) { $vn_start_secs = 120; // always take a frame from the first two minutes to ensure performance (ffmpeg gets slow if it has to seek far into a movie to extract a frame) } exec($this->ops_path_to_ffmpeg . " -ss " . $vn_start_secs . " -i " . caEscapeShellArg($this->filepath) . " -f mjpeg -t 0.001 -y " . caEscapeShellArg($filepath . "." . $ext), $va_output, $vn_return); if ($vn_return < 0 || $vn_return > 1 || !@filesize($filepath . "." . $ext)) { @unlink($filepath . "." . $ext); // don't throw error as ffmpeg cannot generate frame still from all files } else { // resize image to desired dimensions $o_media = new Media(); $o_media->read($filepath . "." . $ext); $o_media->transform('SCALE', array('width' => $vn_preview_width, 'height' => $vn_preview_height, 'mode' => 'bounding_box', 'antialiasing' => 0.5)); $o_media->write($filepath . "_tmp", 'image/jpeg', array()); if (!$o_media->numErrors()) { rename($filepath . "_tmp." . $ext, $filepath . "." . $ext); } else { @unlink($filepath . "_tmp." . $ext); } } } // if output file doesn't exist, ffmpeg failed or isn't installed // so use default icons if (!file_exists($filepath . "." . $ext)) { return __CA_MEDIA_VIDEO_DEFAULT_ICON__; } $this->properties["mimetype"] = $mimetype; $this->properties["typename"] = isset($this->typenames[$mimetype]) ? $this->typenames[$mimetype] : $mimetype; break; # ------------------------------------ # ------------------------------------ default: if ($mimetype != $this->handle["mime_type"]) { # this plugin can't write this mimetype (no conversions allowed) $this->postError(1610, _t("Can't convert '%1' to %2", $this->handle["mime_type"], $mimetype), "WLPlugQuicktimeVR->write()"); return false; } # write the file if (!copy($this->filepath, $filepath . "." . $ext)) { $this->postError(1610, _t("Couldn't write file to '%1'", $filepath), "WLPlugQuicktimeVR->write()"); return false; } break; # ------------------------------------ } return $filepath . "." . $ext; }
/** * @param array $pa_options Options include: * dontUseDefaultIcons = If set to true, write will fail rather than use default icons when preview can't be generated. Default is false – to use default icons. * */ public function write($ps_filepath, $ps_mimetype, $pa_options = null) { if (!$this->handle) { return false; } $vb_dont_allow_default_icons = isset($pa_options['dontUseDefaultIcons']) && $pa_options['dontUseDefaultIcons'] ? true : false; # is mimetype valid? if (!($vs_ext = $this->info["EXPORT"][$ps_mimetype])) { $this->postError(1610, _t("Can't convert file to %1", $ps_mimetype), "WLPlugPDFWand->write()"); return false; } # write the file if ($ps_mimetype == "application/pdf") { if (!copy($this->filepath, $ps_filepath . ".pdf")) { $this->postError(1610, _t("Couldn't write file to '%1'", $ps_filepath), "WLPlugPDFWand->write()"); return false; } } else { $vb_use_default_icon = true; if (caMediaPluginGhostscriptInstalled($this->ops_ghostscript_path)) { $vn_scaling_correction = $this->get("scaling_correction"); $vs_res = "72x72"; if (ceil($this->get("resolution")) > 0) { $vn_res = $this->get("resolution"); if ($vn_scaling_correction) { $vn_res *= 2; } $vs_res = ceil($vn_res) . "x" . ceil($vn_res); } $vn_page = ceil($this->get("page")); $vn_quality = ceil($this->get("quality")); if ($vn_quality > 100) { $vn_quality = 100; } if ($vn_quality < 1) { $vn_quality = 50; } if ($vn_page < 1) { $vn_page = 1; } if ($this->get("antialiasing")) { $vs_antialiasing = "-dTextAlphaBits=4 -dGraphicsAlphaBits=4"; } else { $vs_antialiasing = ""; } $vb_processed_preview = false; switch ($ps_mimetype) { case 'image/jpeg': exec($this->ops_ghostscript_path . " -dNOPAUSE -dBATCH -sDEVICE=" . ($vn_scaling_correction ? "tiff24nc" : "jpeg") . " {$vs_antialiasing} -dJPEGQ=" . $vn_quality . " -dFirstPage=" . $vn_page . " -dLastPage=" . $vn_page . " -sOutputFile=" . caEscapeShellArg($ps_filepath . "." . $vs_ext) . " -r" . $vs_res . " " . caEscapeShellArg($this->handle["filepath"]), $va_output, $vn_return); if ($vn_return == 0) { $vb_processed_preview = true; } break; case 'image/tiff': case 'image/png': case 'image/gif': exec($this->ops_ghostscript_path . " -dNOPAUSE -dBATCH -sDEVICE=tiff24nc {$vs_antialiasing} -dFirstPage=" . $vn_page . " -dLastPage=" . $vn_page . " -sOutputFile=" . caEscapeShellArg($ps_filepath . "." . $vs_ext) . " -r" . $vs_res . " " . caEscapeShellArg($this->handle["filepath"]), $va_output, $vn_return); if ($vn_return == 0) { $vb_processed_preview = true; } break; default: //die("Unsupported output type in PDF plug-in: $ps_mimetype [this shouldn't happen]"); break; } if ($vb_processed_preview) { if ($vs_crop = $this->get("crop")) { $o_media = new Media(); list($vn_w, $vn_h) = explode("x", $vs_crop); if ($vn_w > 0 && $vn_h > 0) { $o_media->read($ps_filepath . "." . $vs_ext); if (!$o_media->numErrors()) { $o_media->transform('SCALE', array('mode' => 'fill_box', 'antialiasing' => 0.5, 'width' => $vn_w, 'height' => $vn_h)); $o_media->write($ps_filepath, $ps_mimetype, array()); if (!$o_media->numErrors()) { $this->properties["width"] = $vn_w; $this->properties["height"] = $vn_h; $vb_use_default_icon = false; } } } } else { if ($vn_scaling_correction) { $o_media = new Media(true); $o_media->read($ps_filepath . "." . $vs_ext); if (!$o_media->numErrors()) { $vn_w = $o_media->get('width') * $vn_scaling_correction; $vn_h = $o_media->get('height') * $vn_scaling_correction; if ($vn_w > $vn_h || $this->get("target_height") == 0) { $vn_r = $this->get("target_width") / $vn_w; $vn_w = $this->get("target_width"); $vn_h *= $vn_r; } else { $vn_r = $this->get("target_height") / $vn_h; $vn_h = $this->get("target_height"); $vn_w *= $vn_r; } $vn_w = ceil($vn_w); $vn_h = ceil($vn_h); $this->properties["width"] = $vn_w; $this->properties["height"] = $vn_h; $o_media->transform('SCALE', array('mode' => 'bounding_box', 'antialiasing' => 0.5, 'width' => $vn_w, 'height' => $vn_h)); $o_media->transform('UNSHARPEN_MASK', array('sigma' => 0.5, 'radius' => 1, 'threshold' => 1.0, 'amount' => 0.1)); $o_media->set('quality', $vn_quality); $o_media->write($ps_filepath, $ps_mimetype, array()); if (!$o_media->numErrors()) { $vb_use_default_icon = false; } } } else { $vb_use_default_icon = false; } } } } if ($vb_use_default_icon) { return $vb_dont_allow_default_icons ? null : __CA_MEDIA_DOCUMENT_DEFAULT_ICON__; } } $this->properties["mimetype"] = $ps_mimetype; $this->properties["filesize"] = filesize($ps_filepath . "." . $vs_ext); $this->properties["typename"] = $this->typenames[$ps_mimetype]; return $ps_filepath . "." . $vs_ext; }
/** * Method invoked when the task queue needs to actually execute the task. For mediaproc this means * actually doing the processing of media! * * Return false on failure/error and sets the error property with an error description. Returns an array * with processing details on success. * * @param array $pa_parameters An unserialized parameters array for the current task (eg. unserialized data from ca_task_queue.parameters) * @return array Returns false on error, or an array with processing details on success */ public function process($pa_parameters) { $vs_table = $pa_parameters["TABLE"]; // name of table of record we're processing $vs_field = $pa_parameters["FIELD"]; // name of field in record we're processing $vs_pk = $pa_parameters["PK"]; // Field name of primary key of record we're processing $vn_id = $pa_parameters["PK_VAL"]; // Value of primary key $vs_input_mimetype = $pa_parameters["INPUT_MIMETYPE"]; // Mimetype of input file $vs_input_file = $pa_parameters["FILENAME"]; // Full path to input file // Array of media versions to process; keys are version names, // values are arrays with info about processing for that version // Currently the info array contains a single key, 'VOLUME', which indicates // the volume the version should be written to $va_versions = $pa_parameters["VERSIONS"]; $va_options = $pa_parameters["OPTIONS"]; // Array of processing options; names of options to employ are keys, settings are values // If true, then input media is *not* deleted $vb_dont_delete_original_media = (bool) $pa_parameters["DONT_DELETE_OLD_MEDIA"]; $va_report = array('errors' => array(), 'notes' => array()); $o_dm = Datamodel::load(); $o_media_volumes = new MediaVolumes(); $o_media = new Media(); $o_media_proc_settings = new MediaProcessingSettings($vs_table, $vs_field); $vs_media_type = $o_media_proc_settings->canAccept($vs_input_mimetype); $va_version_info = $o_media_proc_settings->getMediaTypeVersions($vs_media_type); if (!file_exists($vs_input_file)) { $o_eventlog = new EventLog(); $o_eventlog->log(array("CODE" => "DEBG", "SOURCE" => "TaskQueue->mediaproc->process()", "MESSAGE" => "Record {$vs_table}.field = file '{$vs_input_file}' did not exist; queued file was discarded")); $va_report['errors'][] = _t("Record %1.field = file '%2' did not exist; queued file was discarded", $vs_table, $vs_input_file); return $va_report; } if ($t_instance = $o_dm->getInstanceByTableName($vs_table, true)) { if ($t_instance->hasField($vs_field)) { if (!$t_instance->load($vn_id)) { # record no longer exists if (!$vb_dont_delete_original_media) { @unlink($vs_input_file); } $o_eventlog = new EventLog(); $o_eventlog->log(array("CODE" => "DEBG", "SOURCE" => "TaskQueue->mediaproc->process()", "MESSAGE" => "Record {$vs_table}.field = {$vn_id} did not exist; queued file was discarded")); $o_media->cleanup(); $va_report['errors'][] = _t("Record %1.field = %2 did not exist; queued file was discarded", $vs_table, $vn_id); return $va_report; } } else { # bad field name $this->error->setError(551, _t("Invalid media field '%1' in table '%2'", $vs_field, $vs_table), "mediaproc->process()"); return false; } } else { # bad table name $this->error->setError(550, _t("Invalid media field table '%1'", $vs_table), "mediaproc->process()"); return false; } $va_old_media_to_delete = array(); foreach ($va_versions as $v => $va_version_settings) { $vs_use_icon = null; if (!file_exists($vs_input_file)) { $this->error->setError(505, _t("Input media file '%1' does not exist", $vs_input_file), "mediaproc->process()"); $o_media->cleanup(); return false; } if (!is_readable($vs_input_file)) { $this->error->setError(506, _t("Denied permission to read input media file '%1'", $vs_input_file), "mediaproc->process()"); $o_media->cleanup(); return false; } if (!$o_media->read($vs_input_file)) { $this->error->setError(1600, _t("Could not process input media file '%1': %2", $vs_input_file, join('; ', $o_media->getErrors())), "mediaproc->process()"); $o_media->cleanup(); return false; } $vs_rule = isset($va_version_info[$v]['RULE']) ? $va_version_info[$v]['RULE'] : ''; $va_rules = $o_media_proc_settings->getMediaTransformationRule($vs_rule); $va_volume_info = $o_media_volumes->getVolumeInformation($va_version_settings['VOLUME']); if (sizeof($va_rules) == 0) { $vs_output_mimetype = $vs_input_mimetype; # # don't process this media, just copy the file # $vs_ext = $o_media->mimetype2extension($vs_output_mimetype); if (!$vs_ext) { $this->error->setError(1600, _t("File could not be copied for %1; can't convert mimetype %2 to extension", $vs_field, $vs_output_mimetype), "mediaproc->process()"); $o_media->cleanup(); return false; } if (($vs_dirhash = $this->_getDirectoryHash($va_volume_info["absolutePath"], $vn_id)) === false) { $this->error->setError(1600, _t("Couldn't create subdirectory for file for %1", $vs_field), "mediaproc->process()"); $o_media->cleanup(); return false; } $vs_magic = rand(0, 99999); $vs_filepath = $va_volume_info["absolutePath"] . "/" . $vs_dirhash . "/" . $vs_magic . "_" . $vs_table . "_" . $vs_field . "_" . $vn_id . "_" . $v . "." . $vs_ext; if (!copy($vs_input_file, $vs_filepath)) { $this->error->setError(504, _t("File could not be copied for %1", $vs_field), "mediaproc->process()"); $o_media->cleanup(); return false; } if (is_array($va_volume_info["mirrors"]) && sizeof($va_volume_info["mirrors"]) > 0) { $entity_key = join("/", array($vs_table, $vs_field, $vn_id, $v)); $row_key = join("/", array($vs_table, $vn_id)); foreach ($va_volume_info["mirrors"] as $vs_mirror_code => $va_mirror_info) { $vs_mirror_method = $va_mirror_info["method"]; $vs_queue = $vs_mirror_method . "mirror"; $tq = new TaskQueue(); if (!$tq->cancelPendingTasksForEntity($entity_key)) { $this->error->setError(560, _t("Could not cancel pending tasks"), "mediaproc->process()"); $o_media->cleanup(); return false; } if ($tq->addTask($vs_queue, array("MIRROR" => $vs_mirror_code, "VOLUME" => $va_version_settings['VOLUME'], "FIELD" => $vs_field, "TABLE" => $vs_table, "VERSION" => $v, "FILES" => array(array("FILE_PATH" => $vs_filepath, "ABS_PATH" => $va_volume_info["absolutePath"], "HASH" => $vs_dirhash, "FILENAME" => $vs_magic . "_" . $vs_table . "_" . $vs_field . "_" . $vn_id . "_" . $v . "." . $vs_ext)), "MIRROR_INFO" => $va_mirror_info, "PK" => $vs_pk, "PK_VAL" => $vn_id), array("priority" => 100, "entity_key" => $entity_key, "row_key" => $row_key))) { continue; } else { $this->error->setError(100, _t("Couldn't queue mirror using '%1' for version '%2' (handler '%3')", $vs_mirror_method, $v, $vs_queue), "mediaproc->process()"); } } } $media_desc[$v] = array("VOLUME" => $va_version_settings['VOLUME'], "MIMETYPE" => $vs_output_mimetype, "WIDTH" => $o_media->get("width"), "HEIGHT" => $o_media->get("height"), "PROPERTIES" => $o_media->getProperties(), "FILENAME" => $vs_table . "_" . $vs_field . "_" . $vn_id . "_" . $v . "." . $vs_ext, "HASH" => $vs_dirhash, "MAGIC" => $vs_magic, "EXTENSION" => $vs_ext, "MD5" => md5_file($vs_filepath)); } else { $o_media->set('version', $v); while (list($operation, $pa_parameters) = each($va_rules)) { if ($operation === 'SET') { foreach ($pa_parameters as $pp => $pv) { if ($pp == 'format') { $vs_output_mimetype = $pv; } else { $o_media->set($pp, $pv); } } } else { if (!$o_media->transform($operation, $pa_parameters)) { $this->error = $o_media->errors[0]; $o_media->cleanup(); return false; } } } if (!$vs_output_mimetype) { $vs_output_mimetype = $vs_input_mimetype; } if (!($vs_ext = $o_media->mimetype2extension($vs_output_mimetype))) { $this->error->setError(1600, _t("File could not be processed for %1; can't convert mimetype %2 to extension", $vs_field, $vs_output_mimetype), "mediaproc->process()"); $o_media->cleanup(); return false; } if (($vs_dirhash = $this->_getDirectoryHash($va_volume_info["absolutePath"], $vn_id)) === false) { $this->error->setError(1600, _t("Couldn't create subdirectory for file for %1", $vs_field), "mediaproc->process()"); $o_media->cleanup(); return false; } $vs_magic = rand(0, 99999); $vs_filepath = $va_volume_info["absolutePath"] . "/" . $vs_dirhash . "/" . $vs_magic . "_" . $vs_table . "_" . $vs_field . "_" . $vn_id . "_" . $v; if (!($vs_output_file = $o_media->write($vs_filepath, $vs_output_mimetype, $va_options))) { $this->error = $o_media->errors[0]; $o_media->cleanup(); return false; } else { if ($vs_output_file === __CA_MEDIA_VIDEO_DEFAULT_ICON__ || $vs_output_file === __CA_MEDIA_AUDIO_DEFAULT_ICON__ || $vs_output_file === __CA_MEDIA_DOCUMENT_DEFAULT_ICON__) { $vs_use_icon = $vs_output_file; } else { $va_output_files[] = $vs_output_file; } } if (is_array($va_volume_info["mirrors"]) && sizeof($va_volume_info["mirrors"]) > 0) { $entity_key = join("/", array($vs_table, $vs_field, $vn_id, $v)); $row_key = join("/", array($vs_table, $vn_id)); foreach ($va_volume_info["mirrors"] as $vs_mirror_code => $va_mirror_info) { $vs_mirror_method = $va_mirror_info["method"]; $vs_queue = $vs_mirror_method . "mirror"; $tq = new TaskQueue(); if (!$tq->cancelPendingTasksForEntity($entity_key)) { $this->error->setError(560, _t("Could not cancel pending tasks"), "mediaproc->process()"); $o_media->cleanup(); return false; } if ($tq->addTask($vs_queue, array("MIRROR" => $vs_mirror_code, "VOLUME" => $va_version_settings['VOLUME'], "FIELD" => $vs_field, "TABLE" => $vs_table, "VERSION" => $v, "FILES" => array(array("FILE_PATH" => $vs_filepath, "ABS_PATH" => $va_volume_info["absolutePath"], "HASH" => $vs_dirhash, "FILENAME" => $vs_magic . "_" . $vs_table . "_" . $vs_field . "_" . $vn_id . "_" . $v . "." . $vs_ext)), "MIRROR_INFO" => $va_mirror_info, "PK" => $vs_pk, "PK_VAL" => $vn_id), array("priority" => 100, "entity_key" => $entity_key, "row_key" => $row_key))) { continue; } else { $this->error->setError(100, _t("Couldn't queue mirror using '%1' for version '%2' (handler '%3')", $vs_mirror_method, $v, $vs_queue), "mediaproc->process()"); } } } if ($vs_use_icon) { $media_desc[$v] = array("MIMETYPE" => $vs_output_mimetype, "USE_ICON" => $vs_use_icon, "WIDTH" => $o_media->get("width"), "HEIGHT" => $o_media->get("height")); } else { $media_desc[$v] = array("VOLUME" => $va_version_settings['VOLUME'], "MIMETYPE" => $vs_output_mimetype, "WIDTH" => $o_media->get("width"), "HEIGHT" => $o_media->get("height"), "PROPERTIES" => $o_media->getProperties(), "FILENAME" => $vs_table . "_" . $vs_field . "_" . $vn_id . "_" . $v . "." . $vs_ext, "HASH" => $vs_dirhash, "MAGIC" => $vs_magic, "EXTENSION" => $vs_ext, "MD5" => md5_file($vs_filepath . "." . $vs_ext)); } } if (!$vb_dont_delete_original_media) { $vs_old_media_path = $t_instance->getMediaPath($vs_field, $v); if ($vs_old_media_path && $vs_filepath . "." . $vs_ext != $vs_old_media_path && $vs_input_file != vs_old_media_path) { //@unlink($t_instance->getMediaPath($vs_field, $v)); $va_old_media_to_delete[] = $vs_old_media_path; } } } # # Update record # if ($t_instance->load($vn_id)) { if (method_exists($t_instance, "useBlobAsMediaField")) { // support for attributes - force field to be FT_MEDIA $t_instance->useBlobAsMediaField(true); } $md = $t_instance->get($vs_field); $va_merged_media_desc = is_array($md) ? $md : array(); foreach ($media_desc as $vs_k => $va_v) { $va_merged_media_desc[$vs_k] = $va_v; } $t_instance->setMode(ACCESS_WRITE); $t_instance->setMediaInfo($vs_field, $va_merged_media_desc); $t_instance->update(); if ($t_instance->numErrors()) { # get rid of files we just created foreach ($va_output_files as $vs_to_delete) { @unlink($vs_to_delete); } $this->error->setError(560, _t("Could not update %1.%2: %3", $vs_table, $vs_field, join(", ", $t_instance->getErrors())), "mediaproc->process()"); $o_media->cleanup(); return false; } $va_report['notes'][] = _t("Processed file %1", $vs_input_file); // Generate preview frames for media that support that (Eg. video) // and add them as "multifiles" assuming the current model supports that (ca_object_representations does) $o_config = Configuration::load(); if (((bool) $o_config->get('video_preview_generate_frames') || (bool) $o_config->get('document_preview_generate_pages')) && method_exists($t_instance, 'addFile')) { $o_media->read($vs_input_file); $va_preview_frame_list = $o_media->writePreviews(array('width' => $o_media->get("width"), 'height' => $o_media->get("height"), 'numberOfFrames' => $o_config->get('video_preview_max_number_of_frames'), 'numberOfPages' => $o_config->get('document_preview_max_number_of_pages'), 'frameInterval' => $o_config->get('video_preview_interval_between_frames'), 'pageInterval' => $o_config->get('document_preview_interval_between_pages'), 'startAtTime' => $o_config->get('video_preview_start_at'), 'endAtTime' => $o_config->get('video_preview_end_at'), 'startAtPage' => $o_config->get('document_preview_start_page'), 'outputDirectory' => __CA_APP_DIR__ . '/tmp')); $t_instance->removeAllFiles(); // get rid of any previously existing frames (they might be hanging around if we're editing an existing record) if (is_array($va_preview_frame_list)) { foreach ($va_preview_frame_list as $vn_time => $vs_frame) { $t_instance->addFile($vs_frame, $vn_time, true); // the resource path for each frame is it's time, in seconds (may be fractional) for video, or page number for documents @unlink($vs_frame); // clean up tmp preview frame file } } } if (!$vb_dont_delete_original_media) { @unlink($vs_input_file); } foreach ($va_old_media_to_delete as $vs_to_delete) { @unlink($vs_to_delete); } $o_media->cleanup(); return $va_report; } else { # record no longer exists if (!$vb_dont_delete_original_media) { @unlink($vs_input_file); } $o_eventlog = new EventLog(); $o_eventlog->log(array("CODE" => "DEBG", "SOURCE" => "TaskQueue->mediaproc->process()", "MESSAGE" => "Record {$vs_table}.field = {$vn_id} did not exist; queued file was discarded")); $o_media->cleanup(); $va_report['errors'][] = _t("Record {$vs_table}.field = {$vn_id} did not exist; queued file was discarded"); return $va_report; } }
/** * */ public function &writePreviews($ps_filepath, $pa_options) { if ($vs_pdf_path = WLPlugMediaOffice::$s_pdf_conv_cache[$this->filepath]) { $o_media = new Media(); if ($o_media->read($vs_pdf_path)) { return $o_media->writePreviews(array_merge($pa_options, array('dontUseDefaultIcons' => true))); } } return null; }
/** * */ public function getClip() { $pn_id = $this->opo_request->getParameter('id', pInteger); $va_data = array(); $t_annotation = new ca_representation_annotations($pn_id); if ($t_annotation->getPrimaryKey()) { $vs_start = $t_annotation->getPropertyValue('startTimecode'); $vs_end = $t_annotation->getPropertyValue('endTimecode'); $va_data['start'] = $vs_start; $va_data['end'] = $vs_end; $t_rep = new ca_object_representations($t_annotation->get('representation_id')); $va_data['file'] = $vs_file = $t_rep->getMediaPath('media', 'original'); $o_media = new Media(); if ($o_media->read($vs_file)) { $o_media->writeClip($vs_file = tempnam('/tmp', 'meow'), $vs_start, $vs_end); } header("Content-type: audio/mpeg"); header("Content-length: " . @filesize($vs_file)); readfile($vs_file); return; } return $this->makeResponse($va_data, 500, "No such clip"); }