Exemplo n.º 1
0
/**
 * Generate URL tag for graphic in current theme; if graphic is not available the graphic in the default theme will be returned.
 *
 * @param RequestHTTP $po_request
 * @param string $ps_file_path
 * @param array $pa_options
 * @return string 
 */
function caGetThemeGraphicURL($po_request, $ps_file_path, $pa_options = null)
{
    $vs_base_path = $po_request->getThemeUrlPath();
    $vs_file_path = '/assets/pawtucket/graphics/' . $ps_file_path;
    if (!file_exists($po_request->getThemeDirectoryPath() . $vs_file_path)) {
        $vs_base_path = $po_request->getDefaultThemeUrlPath();
    }
    return $vs_base_path . $vs_file_path;
}
 public function testImproperInstantiation()
 {
     global $_SERVER;
     // emulate client request
     $_SERVER["REQUEST_METHOD"] = "FOOBAR";
     $_SERVER["SCRIPT_NAME"] = "/service.php";
     $vo_response = new ResponseHTTP();
     $vo_request = new RequestHTTP($vo_response, array("dont_create_new_session" => true));
     $vo_request->setRawPostData('This is not JSON!');
     $vo_service = new BaseJSONService($vo_request, "invalid_table");
     $this->assertTrue($vo_service->hasErrors());
     // we don't check error messages because they tend to change frequently but
     // the above code should generate 3 errors (invalid table, no JSON request body
     // and invalid request method)
     $this->assertEquals(3, sizeof($vo_service->getErrors()));
 }
Exemplo n.º 3
0
    /**
     * This part of the service is basically a wrapper around BaseModel::get so we don't
     * need to test that extensively here. We "just" have to make sure the integration works.
     */
    public function testGetSpecificItemInfo()
    {
        global $_SERVER;
        // emulate client request
        $_SERVER["REQUEST_METHOD"] = "GET";
        $_SERVER["SCRIPT_NAME"] = "/service.php";
        $vo_response = new ResponseHTTP();
        $vo_request = new RequestHTTP($vo_response);
        $vs_request_body = <<<JSON
{
\t"bundles" : {
\t\t"ca_objects.access" : {
\t\t\t"convertCodesToDisplayText" : true
\t\t},
\t\t"ca_objects.preferred_labels.name" : {
\t\t\t"delimiter" : "; "
\t\t},
\t\t"ca_entities.entity_id" : {
\t\t\t"returnAsArray" : true
\t\t}
\t}
}
JSON;
        $vo_request->setParameter("id", 27, "GET");
        $vo_request->setRawPostData($vs_request_body);
        $vo_service = new ItemService($vo_request, "ca_objects");
        $va_return = $vo_service->dispatch();
        $this->assertFalse($vo_service->hasErrors());
        $this->assertEquals("Public", $va_return["ca_objects.access"]);
        $this->assertEquals("Astroland arcade, Surf Avenue", $va_return["ca_objects.preferred_labels.name"]);
        $this->assertEquals(array("4"), $va_return["ca_entities.entity_id"]);
    }
Exemplo n.º 4
0
/**
 * Checks if current user is privileged. Currently only checks if IP address of user is on
 * a privileged network, as defined by the 'privileged_networks' configuration directive. May 
 * be expanded in the future to consider user's access rights and/or other parameters.
 *
 * @param RequestHTTP $po_request The current request
 * @param array $pa_options Optional options. If omitted settings are taken application configuration file is used. Any array passed to this function should include "privileged_networks" as a key with a value listing all privileged networks
 * @return boolean True if user is privileged, false if not
 */
function caUserIsPrivileged($po_request, $pa_options = null)
{
    $va_privileged_networks = isset($pa_options['privileged_networks']) && is_array($pa_options['privileged_networks']) ? $pa_options['privileged_networks'] : (array) $po_request->config->getList('privileged_networks');
    if (!($va_priv_ips = $va_privileged_networks)) {
        $va_priv_ips = array();
    }
    $va_user_ip = explode('.', $po_request->getClientIP());
    if (is_array($va_priv_ips)) {
        foreach ($va_priv_ips as $vs_priv_ip) {
            $va_priv_ip = explode('.', $vs_priv_ip);
            $vb_is_match = true;
            for ($vn_i = 0; $vn_i < sizeof($va_priv_ip); $vn_i++) {
                if ($va_priv_ip[$vn_i] != '*' && $va_priv_ip[$vn_i] != $va_user_ip[$vn_i]) {
                    continue 2;
                }
            }
            return true;
        }
    }
    return false;
}
Exemplo n.º 5
0
 /**
  * Get BaseModel instance for given table and optionally load the record with the specified ID
  * @param string $ps_table table name, e.g. "ca_objects"
  * @param mixed $pn_id integer primary key value of the record to load, or string idno value for the record to load 
  * @return BaseModel
  */
 protected function _getTableInstance($ps_table, $pn_id = null)
 {
     // $pn_id might be a string if the user is fetching by idno
     if (!in_array($ps_table, $this->opa_valid_tables)) {
         $this->opa_errors[] = _t("Accessing this table directly is not allowed");
         return false;
     }
     $vb_include_deleted = intval($this->opo_request->getParameter("include_deleted", pInteger));
     $t_instance = $this->opo_dm->getInstanceByTableName($ps_table);
     if ($pn_id && !is_numeric($pn_id) && ($vs_idno_fld = $t_instance->getProperty('ID_NUMBERING_ID_FIELD')) && preg_match("!^[A-Za-z0-9_\\-\\.,\\[\\]]+\$!", $pn_id)) {
         // User is loading by idno
         $va_load_spec = array($vs_idno_fld => $pn_id);
         if (!$vb_include_deleted && $t_instance->hasField('deleted')) {
             $va_load_spec['deleted'] = 0;
         }
         if (!$t_instance->load($va_load_spec)) {
             $this->opa_errors[] = _t("idno does not exist");
             return false;
         } else {
             if (!$vb_include_deleted && $t_instance->get("deleted")) {
                 $this->opa_errors[] = _t("idno does not exist");
                 return false;
             }
         }
     } else {
         if ($pn_id > 0) {
             if (!$t_instance->load($pn_id)) {
                 $this->opa_errors[] = _t("ID does not exist");
                 return false;
             } else {
                 if (!$vb_include_deleted && $t_instance->get("deleted")) {
                     $this->opa_errors[] = _t("ID does not exist");
                     return false;
                 }
             }
         }
     }
     return $t_instance;
 }
Exemplo n.º 6
0
/**
 * Return rendered HTML for media viewer for both re
 *
 * @param RequestHTTP $po_request
 * @param array $pa_options
 * @param array $pa_additional_display_options
 * @return string HTML output
 */
function caGetMediaViewerHTMLBundle($po_request, $pa_options = null, $pa_additional_display_options = null)
{
    $va_access_values = isset($pa_options['access']) && is_array($pa_options['access']) ? $pa_options['access'] : array();
    $vs_display_type = isset($pa_options['display']) && $pa_options['display'] ? $pa_options['display'] : 'media_overlay';
    $vs_container_dom_id = isset($pa_options['containerID']) && $pa_options['containerID'] ? $pa_options['containerID'] : null;
    $t_subject = isset($pa_options['t_subject']) && $pa_options['t_subject'] ? $pa_options['t_subject'] : null;
    $t_rep = isset($pa_options['t_representation']) && $pa_options['t_representation'] ? $pa_options['t_representation'] : null;
    $vn_representation_id = $t_rep ? $t_rep->getPrimaryKey() : null;
    $t_attr_val = isset($pa_options['t_attribute_value']) && $pa_options['t_attribute_value'] ? $pa_options['t_attribute_value'] : null;
    $vn_value_id = $t_attr_val ? $t_attr_val->getPrimaryKey() : null;
    $vn_item_id = isset($pa_options['item_id']) && $pa_options['item_id'] ? $pa_options['item_id'] : null;
    $vn_order_item_id = isset($pa_options['order_item_id']) && $pa_options['order_item_id'] ? $pa_options['order_item_id'] : null;
    $vb_media_editor = isset($pa_options['mediaEditor']) && $pa_options['mediaEditor'] ? true : false;
    $vb_no_controls = isset($pa_options['noControls']) && $pa_options['noControls'] ? true : false;
    $vn_item_id = isset($pa_options['item_id']) && $pa_options['item_id'] ? $pa_options['item_id'] : null;
    $vn_subject_id = $t_subject ? $t_subject->getPrimaryKey() : null;
    if (!$vn_value_id && !$vn_representation_id) {
        $t_rep->load($t_subject->getPrimaryRepresentationID(array('checkAccess' => $va_access_values)));
    }
    $o_view = new View($po_request, $po_request->getViewsDirectoryPath() . '/bundles/');
    $t_set_item = new ca_set_items();
    if ($vn_item_id) {
        $t_set_item->load($vn_item_id);
    }
    $t_order_item = new ca_commerce_order_items();
    if ($vn_order_item_id) {
        $t_order_item->load($vn_order_item_id);
    }
    $o_view->setVar('containerID', $vs_container_dom_id);
    $o_view->setVar('t_subject', $t_subject);
    $o_view->setVar('t_representation', $t_rep);
    if ($vn_representation_id && (!sizeof($va_access_values) || in_array($t_rep->get('access'), $va_access_values))) {
        // check rep access
        $va_rep_display_info = caGetMediaDisplayInfo($vs_display_type, $t_rep->getMediaInfo('media', 'INPUT', 'MIMETYPE'));
        $va_rep_display_info['poster_frame_url'] = $t_rep->getMediaUrl('media', $va_rep_display_info['poster_frame_version']);
        $o_view->setVar('num_multifiles', $t_rep->numFiles());
        if (isset($pa_options['use_book_viewer'])) {
            $va_rep_display_info['use_book_viewer'] = (bool) $pa_options['use_book_viewer'];
        }
        $o_view->setVar('display_type', $vs_display_type);
        if (is_array($pa_additional_display_options)) {
            $va_rep_display_info = array_merge($va_rep_display_info, $pa_additional_display_options);
        }
        $o_view->setVar('display_options', $va_rep_display_info);
        $o_view->setVar('representation_id', $vn_representation_id);
        $o_view->setVar('versions', $va_versions = $t_rep->getMediaVersions('media'));
        $t_media = new Media();
        $o_view->setVar('version_type', $t_media->getMimetypeTypename($t_rep->getMediaInfo('media', 'original', 'MIMETYPE')));
        if ($vn_subject_id) {
            $o_view->setVar('reps', $va_reps = $t_subject->getRepresentations(array('icon'), null, array("return_with_access" => $va_access_values)));
            $vn_next_rep = $vn_prev_rep = null;
            $va_rep_list = array_values($va_reps);
            foreach ($va_rep_list as $vn_i => $va_rep) {
                if ($va_rep['representation_id'] == $vn_representation_id) {
                    if (isset($va_rep_list[$vn_i - 1])) {
                        $vn_prev_rep = $va_rep_list[$vn_i - 1]['representation_id'];
                    }
                    if (isset($va_rep_list[$vn_i + 1])) {
                        $vn_next_rep = $va_rep_list[$vn_i + 1]['representation_id'];
                    }
                    $o_view->setVar('representation_index', $vn_i + 1);
                }
            }
            $o_view->setVar('previous_representation_id', $vn_prev_rep);
            $o_view->setVar('next_representation_id', $vn_next_rep);
        }
        $ps_version = $po_request->getParameter('version', pString);
        if (!in_array($ps_version, $va_versions)) {
            if (!($ps_version = $va_rep_display_info['display_version'])) {
                $ps_version = null;
            }
        }
        $o_view->setVar('version', $ps_version);
        $o_view->setVar('version_info', $t_rep->getMediaInfo('media', $ps_version));
        $o_view->setVar('t_set_item', $t_set_item);
        $o_view->setVar('t_order_item', $t_order_item);
        $o_view->setVar('use_media_editor', $vb_media_editor);
        $o_view->setVar('noControls', $vb_no_controls);
    } else {
        //$t_attr = new ca_attributes($t_attr_val->get('attribute_id'));
        $t_attr_val->useBlobAsMediaField(true);
        $va_rep_display_info = caGetMediaDisplayInfo($vs_display_type, $t_attr_val->getMediaInfo('value_blob', 'INPUT', 'MIMETYPE'));
        $va_rep_display_info['poster_frame_url'] = $t_attr_val->getMediaUrl('value_blob', $va_rep_display_info['poster_frame_version']);
        $o_view->setVar('num_multifiles', $t_attr_val->numFiles());
        if (isset($pa_options['use_book_viewer'])) {
            $va_rep_display_info['use_book_viewer'] = (bool) $pa_options['use_book_viewer'];
        }
        $o_view->setVar('display_type', $vs_display_type);
        if (is_array($pa_additional_display_options)) {
            $va_rep_display_info = array_merge($va_rep_display_info, $pa_additional_display_options);
        }
        $o_view->setVar('display_options', $va_rep_display_info);
        $o_view->setVar('representation_id', $vn_representation_id);
        $o_view->setVar('t_attribute_value', $t_attr_val);
        $o_view->setVar('versions', $va_versions = $t_attr_val->getMediaVersions('value_blob'));
        $t_media = new Media();
        $o_view->setVar('version_type', $t_media->getMimetypeTypename($t_attr_val->getMediaInfo('value_blob', 'original', 'MIMETYPE')));
        $o_view->setVar('reps', array());
        $ps_version = $po_request->getParameter('version', pString);
        if (!in_array($ps_version, $va_versions)) {
            if (!($ps_version = $va_rep_display_info['display_version'])) {
                $ps_version = null;
            }
        }
        $o_view->setVar('version', $ps_version);
        $o_view->setVar('version_info', $t_attr_val->getMediaInfo('value_blob', $ps_version));
        $o_view->setVar('t_subject', $t_subject);
        $o_view->setVar('t_set_item', $t_set_item);
        $o_view->setVar('t_order_item', $t_order_item);
        $o_view->setVar('use_media_editor', $vb_media_editor);
        $o_view->setVar('noControls', $vb_no_controls);
    }
    return $o_view->render('representation_viewer_html.php');
}
/**
 * Formats communication for display in messages list in Pawtucket
 *
 * @param RequestHTTP $po_request
 * @param array $pa_data
 * @param array $pa_options
 *		viewContentDivID = 
 *		additionalMessages =
 *		isAdditionalMessage =
 *
 * @return string 
 */
function caClientServicesFormatMessageSummaryPawtucket($po_request, $pa_data, $pa_options = null)
{
    $vb_is_additional_message = (bool) (isset($pa_options['isAdditionalMessage']) && $pa_options['isAdditionalMessage']);
    $vb_is_unread = !(bool) $pa_data['read_on'];
    $vs_unread_class = $vb_is_unread ? "caClientCommunicationsMessageSummaryUnread" : "";
    if ($po_request->getUserID() == $pa_data['from_user_id']) {
        $vb_is_unread = false;
        $vs_unread_class = '';
    }
    // if the message was created by the user it's already show as "read"
    if ($vb_is_additional_message) {
        $vs_class = $vb_is_unread ? "caClientCommunicationsAdditionalMessageSummary caClientCommunicationsMessageSummaryUnread" : "caClientCommunicationsAdditionalMessageSummary";
        $vs_buf = "<div class='{$vs_class}' id='caClientCommunicationsMessage_" . $pa_data['communication_id'] . "'>";
    } else {
        $vs_class = $vb_is_unread ? "caClientCommunicationsMessageSummary caClientCommunicationsMessageSummaryUnread" : "caClientCommunicationsMessageSummary";
        $vs_buf = "<div class='{$vs_class}'>";
    }
    $vs_buf .= "<div class='caClientCommunicationsMessageSummaryContainer' id='caClientCommunicationsMessage_" . $pa_data['communication_id'] . "'>";
    $vs_buf .= "<div class='caClientCommunicationsViewMessageIcon'>+</div>";
    TooltipManager::add(".caClientCommunicationsViewMessageIcon", _t("View entire message and associated media"));
    $vs_buf .= "<div class='caClientCommunicationsMessageSummaryFrom {$vs_unread_class}'><span class='caClientCommunicationsMessageSummaryHeading'>" . _t("From") . ":</span> " . caClientServicesGetSenderName($pa_data) . "</div>";
    $vs_buf .= "<div class='caClientCommunicationsMessageSummaryDate {$vs_unread_class}'><span class='caClientCommunicationsMessageSummaryHeading'>" . _t("Date") . ":</span> " . caGetLocalizedDate($pa_data['created_on'], array('dateFormat' => 'delimited')) . "</div>";
    $vs_buf .= "<div class='caClientCommunicationsMessageSummarySubject {$vs_unread_class}'><span class='caClientCommunicationsMessageSummaryHeading'>" . _t("Subject") . ":</span> " . $pa_data['subject'] . "</div>";
    $vs_buf .= "<div class='caClientCommunicationsMessageSummaryText'>" . (mb_strlen($pa_data['message']) > 300 ? mb_substr($pa_data['message'], 0, 300) . "..." : $pa_data['message']) . "</div>";
    $vs_buf .= "</div>";
    $vs_buf .= "</div>\n";
    $vn_num_additional_messages = is_array($pa_options['additionalMessages']) ? sizeof($pa_options['additionalMessages']) : 0;
    if ($vn_num_additional_messages) {
        $vs_buf .= "<div class='caClientCommunicationsMessageSummaryViewButton' id='caClientCommunicationsMessageAdditionalCount" . $pa_data['communication_id'] . "'><a href='#' onclick='jQuery(\"#caClientCommunicationsMessageAdditional" . $pa_data['communication_id'] . "\").slideToggle(250); jQuery(\".caClientCommunicationsMessageSummaryViewButton\").hide(); return false;' >" . _t("View thread") . " &rsaquo;</a></div>";
    }
    if ($vn_num_additional_messages) {
        $vs_buf .= "<div class='caClientCommunicationsMessageAdditional' id='caClientCommunicationsMessageAdditional" . $pa_data['communication_id'] . "'>";
        $pa_additional_options = $pa_options;
        unset($pa_additional_options['additionalMessages']);
        $pa_additional_options['isAdditionalMessage'] = true;
        foreach ($pa_options['additionalMessages'] as $va_additional_message) {
            $vs_buf .= caClientServicesFormatMessageSummaryPawtucket($po_request, $va_additional_message, $pa_additional_options);
        }
        $vs_buf .= "</div>";
    }
    return $vs_buf;
}
Exemplo n.º 8
0
/**
 * 
 *
 * @param RequestHTTP $po_request
 * @param array $pa_options
 * @param array $pa_additional_display_options
 * @return string HTML output
 */
function caRepresentationViewerHTMLBundleForSearchResult($po_data, $po_request, $pa_options = null, $pa_additional_display_options = null)
{
    $ps_version = $po_request->getParameter('version', pString);
    $va_access_values = isset($pa_options['access']) && is_array($pa_options['access']) ? $pa_options['access'] : array();
    $vs_display_type = isset($pa_options['display']) && $pa_options['display'] ? $pa_options['display'] : 'media_overlay';
    $vs_container_dom_id = isset($pa_options['containerID']) && $pa_options['containerID'] ? $pa_options['containerID'] : null;
    $vn_object_id = isset($pa_options['object_id']) && $pa_options['object_id'] ? $pa_options['object_id'] : null;
    $vn_item_id = isset($pa_options['item_id']) && $pa_options['item_id'] ? $pa_options['item_id'] : null;
    $vn_order_item_id = isset($pa_options['order_item_id']) && $pa_options['order_item_id'] ? $pa_options['order_item_id'] : null;
    $vb_media_editor = isset($pa_options['mediaEditor']) && $pa_options['mediaEditor'] ? true : false;
    $vb_no_controls = isset($pa_options['noControls']) && $pa_options['noControls'] ? true : false;
    $vn_item_id = isset($pa_options['item_id']) && $pa_options['item_id'] ? $pa_options['item_id'] : null;
    $t_object = new ca_objects($vn_object_id);
    //if (!$t_object->getPrimaryKey()) { return false; }
    if (!$po_data->getPrimaryKey() && $t_object->getPrimaryKey() && method_exists($po_data, 'load')) {
        $po_data->load($t_object->getPrimaryRepresentationID(array('checkAccess' => $va_access_values)));
    }
    $t_set_item = new ca_set_items();
    if ($vn_item_id) {
        $t_set_item->load($vn_item_id);
    }
    $t_order_item = new ca_commerce_order_items();
    if ($vn_order_item_id) {
        $t_order_item->load($vn_order_item_id);
    }
    $o_view = new View($po_request, $po_request->getViewsDirectoryPath() . '/bundles/');
    $o_view->setVar('t_object', $t_object);
    $o_view->setVar('t_set_item', $t_set_item);
    $o_view->setVar('t_order_item', $t_order_item);
    $o_view->setVar('use_media_editor', $vb_media_editor);
    $o_view->setVar('noControls', $vb_no_controls);
    $va_rep_display_info = array();
    if (isset($pa_options['use_book_viewer'])) {
        $va_rep_display_info['use_book_viewer'] = (bool) $pa_options['use_book_viewer'];
    }
    if ($t_object->getPrimaryKey()) {
        $o_view->setVar('reps', $va_reps = $t_object->getRepresentations(array('icon'), null, array("return_with_access" => $va_access_values)));
    }
    $t_media = new Media();
    $va_buf = array();
    while ($po_data->nextHit()) {
        if (method_exists($po_data, 'numFiles')) {
            $o_view->setVar('num_multifiles', $po_data->numFiles());
        }
        $o_view->setVar('t_object_representation', $po_data);
        if (($vn_representation_id = $po_data->getPrimaryKey()) && (!sizeof($va_access_values) || in_array($po_data->get('access'), $va_access_values))) {
            // check rep access
            $va_rep_display_info = caGetMediaDisplayInfo($vs_display_type, $vs_mimetype = $po_data->getMediaInfo('media', 'INPUT', 'MIMETYPE'));
            $va_rep_display_info['poster_frame_url'] = $po_data->getMediaUrl('media', $va_rep_display_info['poster_frame_version']);
            $va_additional_display_options = array();
            if (is_array($pa_additional_display_options) && isset($pa_additional_display_options[$vs_mimetype]) && is_array($pa_additional_display_options[$vs_mimetype])) {
                $va_additional_display_options = $pa_additional_display_options[$vs_mimetype];
            }
            $o_view->setVar('display_options', caGetMediaDisplayInfo('detail', $vs_mimetype));
            $o_view->setVar('display_type', $vs_display_type);
            $o_view->setVar('representation_id', $vn_representation_id);
            $o_view->setVar('t_object_representation', $po_data);
            $o_view->setVar('versions', $va_versions = $po_data->getMediaVersions('media'));
            $o_view->setVar('containerID', $vs_container_dom_id . $vn_representation_id);
            $o_view->setVar('version_type', $t_media->getMimetypeTypename($po_data->getMediaInfo('media', 'original', 'MIMETYPE')));
            if ($t_object->getPrimaryKey()) {
                $vn_next_rep = $vn_prev_rep = null;
                $va_rep_list = array_values($va_reps);
                foreach ($va_rep_list as $vn_i => $va_rep) {
                    if ($va_rep['representation_id'] == $vn_representation_id) {
                        if (isset($va_rep_list[$vn_i - 1])) {
                            $vn_prev_rep = $va_rep_list[$vn_i - 1]['representation_id'];
                        }
                        if (isset($va_rep_list[$vn_i + 1])) {
                            $vn_next_rep = $va_rep_list[$vn_i + 1]['representation_id'];
                        }
                        $o_view->setVar('representation_index', $vn_i + 1);
                    }
                }
                $o_view->setVar('previous_representation_id', $vn_prev_rep);
                $o_view->setVar('next_representation_id', $vn_next_rep);
            }
            if (!in_array($ps_version, $va_versions)) {
                if (!($ps_version = $va_rep_display_info['display_version'])) {
                    $ps_version = null;
                }
            }
            $o_view->setVar('version_info', $po_data->getMediaInfo('media', $ps_version));
            $o_view->setVar('version', $ps_version);
        }
        $va_buf[$vn_representation_id] = $o_view->render('representation_viewer_html.php');
    }
    return $va_buf;
}
Exemplo n.º 9
0
 /**
  * @param array $pa_config
  * @param RequestHTTP $po_request
  * @return array
  * @throws Exception
  */
 private static function runSearchEndpoint($pa_config, $po_request)
 {
     $o_dm = Datamodel::load();
     // load blank instance
     $t_instance = $o_dm->getInstance($pa_config['table']);
     if (!$t_instance instanceof BundlableLabelableBaseModelWithAttributes) {
         throw new Exception('invalid table');
     }
     if (!($ps_q = $po_request->getParameter('q', pString))) {
         throw new Exception('No query specified');
     }
     $o_search = caGetSearchInstance($pa_config['table']);
     // restrictToTypes
     if ($pa_config['restrictToTypes'] && is_array($pa_config['restrictToTypes']) && sizeof($pa_config['restrictToTypes']) > 0) {
         $va_type_filter = array();
         foreach ($pa_config['restrictToTypes'] as $vs_type_code) {
             $va_type_filter[] = caGetListItemID($t_instance->getTypeListCode(), $vs_type_code);
         }
         $o_search->addResultFilter($t_instance->tableName() . '.type_id', 'IN', join(",", $va_type_filter));
     }
     $o_res = $o_search->search($ps_q, array('sort' => $po_request->getParameter('sort', pString), 'sortDirection' => $po_request->getParameter('sortDirection', pString), 'start' => $po_request->getParameter('start', pInteger), 'limit' => $po_request->getParameter('limit', pInteger), 'checkAccess' => $pa_config['checkAccess']));
     $va_return = array();
     while ($o_res->nextHit()) {
         $va_hit = array();
         foreach ($pa_config['content'] as $vs_key => $vs_template) {
             $va_hit[self::sanitizeKey($vs_key)] = $o_res->getWithTemplate($vs_template);
         }
         $va_return[$o_res->get($t_instance->primaryKey(true))] = $va_hit;
     }
     return $va_return;
 }
 /**
  * @param RequestHTTP $po_request
  * @param string $ps_form_prefix
  * @param string $ps_placement_code
  */
 public function _processRelatedSets($po_request, $ps_form_prefix, $ps_placement_code)
 {
     require_once __CA_MODELS_DIR__ . '/ca_sets.php';
     foreach ($_REQUEST as $vs_key => $vs_value) {
         // check for new relationships to add
         if (preg_match("/^{$ps_placement_code}{$ps_form_prefix}_idnew_([\\d]+)/", $vs_key, $va_matches)) {
             $vn_c = intval($va_matches[1]);
             if ($vn_new_id = $po_request->getParameter("{$ps_placement_code}{$ps_form_prefix}_idnew_{$vn_c}", pString)) {
                 $t_set = new ca_sets($vn_new_id);
                 $t_set->addItem($this->getPrimaryKey(), null, $po_request->getUserID());
             }
         }
         // check for delete keys
         if (preg_match("/^{$ps_placement_code}{$ps_form_prefix}_([\\d]+)_delete/", $vs_key, $va_matches)) {
             $vn_c = intval($va_matches[1]);
             $t_set = new ca_sets($vn_c);
             $t_set->removeItem($this->getPrimaryKey());
         }
     }
 }
Exemplo n.º 11
0
 private function _evaluateRequirements(&$pa_requirements)
 {
     if (sizeof($pa_requirements) == 0) {
         return true;
     }
     // empty requirements means anyone may access the nav item
     $vs_result = $vs_value = null;
     foreach ($pa_requirements as $vs_requirement => $vs_boolean) {
         $vs_boolean = strtoupper($vs_boolean) == "AND" ? "AND" : "OR";
         $va_tmp = explode(':', $vs_requirement);
         switch (strtolower($va_tmp[0])) {
             case 'availabletypes':
                 $vn_min_access = sizeof($va_tmp) >= 3 ? constant($va_tmp[2]) : __CA_BUNDLE_ACCESS_EDIT__;
                 $vn_min_types = sizeof($va_tmp) >= 4 ? (int) $va_tmp[3] : 1;
                 $va_types = caGetTypeListForUser($va_tmp[1], array('access' => $vn_min_access));
                 $vs_value = sizeof($va_types) >= $vn_min_types ? true : false;
                 break;
             case 'session':
                 if (isset($va_tmp[2])) {
                     $vs_value = $this->opo_request->session->getVar($va_tmp[1]) == $va_tmp[2] ? true : false;
                 } else {
                     $vs_value = $this->opo_request->session->getVar($va_tmp[1]) ? true : false;
                 }
                 break;
             case 'action':
                 if ($va_tmp[1]) {
                     $vs_value = $this->opo_request->user->canDoAction($va_tmp[1]) ? 1 : 0;
                 } else {
                     $vs_value = 1;
                 }
                 break;
             case 'parameter':
                 if (isset($va_tmp[2])) {
                     $vs_value = $this->opo_request->getParameter($va_tmp[1], pString) == $va_tmp[2] ? true : false;
                 } else {
                     $vs_value = $this->opo_request->getParameter($va_tmp[1], pString) ? true : false;
                 }
                 break;
             case 'configuration':
                 $vs_pref = $va_tmp[1];
                 if ($vb_not = substr($vs_pref, 0, 1) == '!' ? true : false) {
                     $vs_pref = substr($vs_pref, 1);
                 }
                 if ($vb_not && !intval($this->opo_request->config->get($vs_pref)) || !$vb_not && intval($this->opo_request->config->get($vs_pref))) {
                     $vs_value = true;
                 } else {
                     $vs_value = false;
                 }
                 break;
             case 'global':
                 if (isset($va_tmp[2])) {
                     $vs_value = $GLOBALS[$va_tmp[1]] == $va_tmp[2] ? true : false;
                 } else {
                     $vs_value = $GLOBALS[$va_tmp[1]] ? true : false;
                 }
                 break;
             default:
                 $vs_value = $vs_value ? true : false;
                 break;
         }
         if (is_null($vs_result)) {
             $vs_result = $vs_value;
         } else {
             if ($vs_boolean == "AND") {
                 $vs_result = $vs_result && $vs_value;
             } else {
                 $vs_result = $vs_result || $vs_value;
             }
         }
     }
     return $vs_result;
 }
Exemplo n.º 12
0
 /**
  * Sets and saves form element settings, taking parameters off of the request as needed. Does an update()
  * on the ca_search_forms instance to save settings to the database
  *
  * @param RequestHTTP $po_request
  * @param array|null $pa_options
  * @return mixed
  */
 public function setSettingsFromHTMLForm($po_request, $pa_options = null)
 {
     $va_locales = ca_locales::getLocaleList(array('sort_field' => '', 'sort_order' => 'asc', 'index_by_code' => true, 'available_for_cataloguing_only' => true));
     $va_available_settings = $this->getAvailableSettings();
     $this->o_instance->setMode(ACCESS_WRITE);
     $va_values = array();
     $vs_id_prefix = caGetOption('id', $pa_options, 'setting');
     $vs_placement_code = caGetOption('placement_code', $pa_options, '');
     foreach (array_keys($va_available_settings) as $vs_setting) {
         $va_properties = $va_available_settings[$vs_setting];
         if (isset($va_properties['takesLocale']) && $va_properties['takesLocale']) {
             foreach ($va_locales as $vs_locale => $va_locale_info) {
                 $va_values[$vs_setting][$va_locale_info['locale_id']] = $po_request->getParameter("{$vs_placement_code}{$vs_id_prefix}{$vs_setting}_{$vs_locale}", pString);
             }
         } else {
             if (isset($va_properties['useRelationshipTypeList']) && $va_properties['useRelationshipTypeList'] && $va_properties['height'] > 1 || isset($va_properties['useList']) && $va_properties['useList'] && $va_properties['height'] > 1 || isset($va_properties['showLists']) && $va_properties['showLists'] && $va_properties['height'] > 1 || isset($va_properties['showVocabularies']) && $va_properties['showVocabularies'] && $va_properties['height'] > 1) {
                 $va_values[$vs_setting] = $po_request->getParameter("{$vs_placement_code}{$vs_id_prefix}{$vs_setting}", pArray);
             } else {
                 switch ($va_properties['formatType']) {
                     case FT_BIT:
                         // skip bits if they're not set in the form; otherwise they default to 'No' even
                         // though the default might be set to 'Yes' the settings definition.
                         $vs_val = $po_request->getParameter("{$vs_placement_code}{$vs_id_prefix}{$vs_setting}", pString);
                         if ($vs_val == '') {
                             continue;
                         }
                         $va_values[$vs_setting] = $vs_val;
                         break;
                     default:
                         $va_values[$vs_setting] = $po_request->getParameter("{$vs_placement_code}{$vs_id_prefix}{$vs_setting}", pString);
                         break;
                 }
             }
         }
         foreach ($va_values as $vs_setting_key => $vs_value) {
             $this->setSetting($vs_setting, $vs_value);
         }
     }
     return $this->o_instance->update();
 }
Exemplo n.º 13
0
 /**
  * Returns semi-persistent storage object supporting getVar()/setVar() interface
  * This is always a Session object
  *
  * @param RequestHTTP $po_request The current request
  * @return Session The storage object
  */
 static function _semipersistentStorageInstance($po_request)
 {
     return $po_request->getSession();
 }
Exemplo n.º 14
0
 /**
  * @param RequestHTTP $po_request
  * @param null|array $pa_options
  *		progressCallback =
  *		reportCallback =
  *		sendMail =
  *		log = log directory path
  *		logLevel = KLogger constant for minimum log level to record. Default is KLogger::INFO. Constants are, in descending order of shrillness:
  *			KLogger::EMERG = Emergency messages (system is unusable)
  *			KLogger::ALERT = Alert messages (action must be taken immediately)
  *			KLogger::CRIT = Critical conditions
  *			KLogger::ERR = Error conditions
  *			KLogger::WARN = Warnings
  *			KLogger::NOTICE = Notices (normal but significant conditions)
  *			KLogger::INFO = Informational messages
  *			KLogger::DEBUG = Debugging messages
  * @return array
  */
 public static function importMediaFromDirectory($po_request, $pa_options = null)
 {
     global $g_ui_locale_id;
     $vs_log_dir = caGetOption('log', $pa_options, __CA_APP_DIR__ . "/log");
     $vs_log_level = caGetOption('logLevel', $pa_options, "INFO");
     if (!is_writeable($vs_log_dir)) {
         $vs_log_dir = caGetTempDirPath();
     }
     $vn_log_level = BatchProcessor::_logLevelStringToNumber($vs_log_level);
     $o_log = new KLogger($vs_log_dir, $vn_log_level);
     $vs_import_target = caGetOption('importTarget', $pa_options, 'ca_objects');
     $t_instance = $po_request->getAppDatamodel()->getInstance($vs_import_target);
     $o_eventlog = new Eventlog();
     $t_set = new ca_sets();
     $va_notices = $va_errors = array();
     $vb_we_set_transaction = false;
     $o_trans = isset($pa_options['transaction']) && $pa_options['transaction'] ? $pa_options['transaction'] : null;
     if (!$o_trans) {
         $vb_we_set_transaction = true;
         $o_trans = new Transaction($t_set->getDb());
     }
     $o_batch_log = new Batchlog(array('user_id' => $po_request->getUserID(), 'batch_type' => 'MI', 'table_num' => (int) $t_instance->tableNum(), 'notes' => '', 'transaction' => $o_trans));
     if (!is_dir($pa_options['importFromDirectory'])) {
         $o_eventlog->log(array("CODE" => 'ERR', "SOURCE" => "mediaImport", "MESSAGE" => $vs_msg = _t("Specified import directory '%1' is invalid", $pa_options['importFromDirectory'])));
         $o_log->logError($vs_msg);
         return null;
     }
     $vs_batch_media_import_root_directory = $po_request->config->get('batch_media_import_root_directory');
     if (!preg_match("!^{$vs_batch_media_import_root_directory}!", $pa_options['importFromDirectory'])) {
         $o_eventlog->log(array("CODE" => 'ERR', "SOURCE" => "mediaImport", "MESSAGE" => $vs_msg = _t("Specified import directory '%1' is invalid", $pa_options['importFromDirectory'])));
         $o_log->logError($vs_msg);
         return null;
     }
     if (preg_match("!\\.\\./!", $pa_options['importFromDirectory'])) {
         $o_eventlog->log(array("CODE" => 'ERR', "SOURCE" => "mediaImport", "MESSAGE" => $vs_msg = _t("Specified import directory '%1' is invalid", $pa_options['importFromDirectory'])));
         $o_log->logError($vs_msg);
         return null;
     }
     $vb_include_subdirectories = (bool) $pa_options['includeSubDirectories'];
     $vb_delete_media_on_import = (bool) $pa_options['deleteMediaOnImport'];
     $vs_import_mode = $pa_options['importMode'];
     $vs_match_mode = $pa_options['matchMode'];
     $vn_type_id = $pa_options[$vs_import_target . '_type_id'];
     $vn_rep_type_id = $pa_options['ca_object_representations_type_id'];
     $va_limit_matching_to_type_ids = $pa_options[$vs_import_target . '_limit_matching_to_type_ids'];
     $vn_access = $pa_options[$vs_import_target . '_access'];
     $vn_object_representation_access = $pa_options['ca_object_representations_access'];
     $vn_status = $pa_options[$vs_import_target . '_status'];
     $vn_object_representation_status = $pa_options['ca_object_representations_status'];
     $vn_rel_type_id = isset($pa_options[$vs_import_target . '_representation_relationship_type']) ? $pa_options[$vs_import_target . '_representation_relationship_type'] : null;
     $vn_mapping_id = $pa_options[$vs_import_target . '_mapping_id'];
     $vn_object_representation_mapping_id = $pa_options['ca_object_representations_mapping_id'];
     $vs_idno_mode = $pa_options['idnoMode'];
     $vs_idno = $pa_options['idno'];
     $vs_representation_idno_mode = $pa_options['representationIdnoMode'];
     $vs_representation_idno = $pa_options['representation_idno'];
     $vs_set_mode = $pa_options['setMode'];
     $vs_set_create_name = $pa_options['setCreateName'];
     $vn_set_id = $pa_options['set_id'];
     $vn_locale_id = $pa_options['locale_id'];
     $vs_skip_file_list = $pa_options['skipFileList'];
     $vs_skip_file_list = $pa_options['skipFileList'];
     $vb_allow_duplicate_media = $pa_options['allowDuplicateMedia'];
     $va_relationship_type_id_for = array();
     if (is_array($va_create_relationship_for = $pa_options['create_relationship_for'])) {
         foreach ($va_create_relationship_for as $vs_rel_table) {
             $va_relationship_type_id_for[$vs_rel_table] = $pa_options['relationship_type_id_for_' . $vs_rel_table];
         }
     }
     if (!$vn_locale_id) {
         $vn_locale_id = $g_ui_locale_id;
     }
     $va_files_to_process = caGetDirectoryContentsAsList($pa_options['importFromDirectory'], $vb_include_subdirectories);
     $o_log->logInfo(_t('Found %1 files in directory \'%2\'', sizeof($va_files_to_process), $pa_options['importFromDirectory']));
     if ($vs_set_mode == 'add') {
         $t_set->load($vn_set_id);
     } else {
         if ($vs_set_mode == 'create' && $vs_set_create_name) {
             $va_set_ids = $t_set->getSets(array('user_id' => $po_request->getUserID(), 'table' => $t_instance->tableName(), 'access' => __CA_SET_EDIT_ACCESS__, 'setIDsOnly' => true, 'name' => $vs_set_create_name));
             $vn_set_id = null;
             if (is_array($va_set_ids) && sizeof($va_set_ids) > 0) {
                 $vn_possible_set_id = array_shift($va_set_ids);
                 if ($t_set->load($vn_possible_set_id)) {
                     $vn_set_id = $t_set->getPrimaryKey();
                 }
             } else {
                 $vs_set_code = mb_substr(preg_replace("![^A-Za-z0-9_\\-]+!", "_", $vs_set_create_name), 0, 100);
                 if ($t_set->load(array('set_code' => $vs_set_code))) {
                     $vn_set_id = $t_set->getPrimaryKey();
                 }
             }
             if (!$t_set->getPrimaryKey()) {
                 $t_set->setMode(ACCESS_WRITE);
                 $t_set->set('user_id', $po_request->getUserID());
                 $t_set->set('type_id', $po_request->config->get('ca_sets_default_type'));
                 $t_set->set('table_num', $t_instance->tableNum());
                 $t_set->set('set_code', $vs_set_code);
                 $t_set->insert();
                 if ($t_set->numErrors()) {
                     $va_notices['create_set'] = array('idno' => '', 'label' => _t('Create set %1', $vs_set_create_name), 'message' => $vs_msg = _t('Failed to create set %1: %2', $vs_set_create_name, join("; ", $t_set->getErrors())), 'status' => 'SET ERROR');
                     $o_log->logError($vs_msg);
                 } else {
                     $t_set->addLabel(array('name' => $vs_set_create_name), $vn_locale_id, null, true);
                     if ($t_set->numErrors()) {
                         $va_notices['add_set_label'] = array('idno' => '', 'label' => _t('Add label to set %1', $vs_set_create_name), 'message' => $vs_msg = _t('Failed to add label to set: %1', join("; ", $t_set->getErrors())), 'status' => 'SET ERROR');
                         $o_log->logError($vs_msg);
                     }
                     $vn_set_id = $t_set->getPrimaryKey();
                 }
             }
         } else {
             $vn_set_id = null;
             // no set
         }
     }
     if ($t_set->getPrimaryKey() && !$t_set->haveAccessToSet($po_request->getUserID(), __CA_SET_EDIT_ACCESS__)) {
         $va_notices['set_access'] = array('idno' => '', 'label' => _t('You do not have access to set %1', $vs_set_create_name), 'message' => $vs_msg = _t('Cannot add to set %1 because you do not have edit access', $vs_set_create_name), 'status' => 'SET ERROR');
         $o_log->logError($vs_msg);
         $vn_set_id = null;
         $t_set = new ca_sets();
     }
     $vn_num_items = sizeof($va_files_to_process);
     // Get list of regex packages that user can use to extract object idno's from filenames
     $va_regex_list = caBatchGetMediaFilenameToIdnoRegexList(array('log' => $o_log));
     // Get list of replacements that user can use to transform file names to match object idnos
     $va_replacements_list = caBatchGetMediaFilenameReplacementRegexList(array('log' => $o_log));
     // Get list of files (or file name patterns) to skip
     $va_skip_list = preg_split("![\r\n]+!", $vs_skip_file_list);
     foreach ($va_skip_list as $vn_i => $vs_skip) {
         if (!strlen($va_skip_list[$vn_i] = trim($vs_skip))) {
             unset($va_skip_list[$vn_i]);
         }
     }
     $vn_c = 0;
     $vn_start_time = time();
     $va_report = array();
     foreach ($va_files_to_process as $vs_file) {
         $va_tmp = explode("/", $vs_file);
         $f = array_pop($va_tmp);
         $d = array_pop($va_tmp);
         array_push($va_tmp, $d);
         $vs_directory = join("/", $va_tmp);
         // Skip file names using $vs_skip_file_list
         if (BatchProcessor::_skipFile($f, $va_skip_list)) {
             $o_log->logInfo(_t('Skipped file %1 because it was on the skipped files list', $f));
             continue;
         }
         $vs_relative_directory = preg_replace("!{$vs_batch_media_import_root_directory}[/]*!", "", $vs_directory);
         // does representation already exist?
         if (!$vb_allow_duplicate_media && ($t_dupe = ca_object_representations::mediaExists($vs_file))) {
             $va_notices[$vs_relative_directory . '/' . $f] = array('idno' => '', 'label' => $f, 'message' => $vs_msg = _t('Skipped %1 from %2 because it already exists %3', $f, $vs_relative_directory, caEditorLink($po_request, _t('(view)'), 'button', 'ca_object_representations', $t_dupe->getPrimaryKey())), 'status' => 'SKIPPED');
             $o_log->logInfo($vs_msg);
             continue;
         }
         $t_instance = $po_request->getAppDatamodel()->getInstance($vs_import_target, false);
         $t_instance->setTransaction($o_trans);
         $vs_modified_filename = $f;
         $va_extracted_idnos_from_filename = array();
         if (in_array($vs_import_mode, array('TRY_TO_MATCH', 'ALWAYS_MATCH')) || is_array($va_create_relationship_for) && sizeof($va_create_relationship_for)) {
             foreach ($va_regex_list as $vs_regex_name => $va_regex_info) {
                 $o_log->logDebug(_t("Processing mediaFilenameToObjectIdnoRegexes entry %1", $vs_regex_name));
                 foreach ($va_regex_info['regexes'] as $vs_regex) {
                     switch ($vs_match_mode) {
                         case 'DIRECTORY_NAME':
                             $va_names_to_match = array($d);
                             $o_log->logDebug(_t("Trying to match on directory '%1'", $d));
                             break;
                         case 'FILE_AND_DIRECTORY_NAMES':
                             $va_names_to_match = array($f, $d);
                             $o_log->logDebug(_t("Trying to match on directory '%1' and file name '%2'", $d, $f));
                             break;
                         default:
                         case 'FILE_NAME':
                             $va_names_to_match = array($f);
                             $o_log->logDebug(_t("Trying to match on file name '%1'", $f));
                             break;
                     }
                     // are there any replacements? if so, try to match each element in $va_names_to_match AND all results of the replacements
                     if (is_array($va_replacements_list) && sizeof($va_replacements_list) > 0) {
                         $va_names_to_match_copy = $va_names_to_match;
                         foreach ($va_names_to_match_copy as $vs_name) {
                             foreach ($va_replacements_list as $vs_replacement_code => $va_replacement) {
                                 if (isset($va_replacement['search']) && is_array($va_replacement['search'])) {
                                     $va_replace = caGetOption('replace', $va_replacement);
                                     $va_search = array();
                                     foreach ($va_replacement['search'] as $vs_search) {
                                         $va_search[] = '!' . $vs_search . '!';
                                     }
                                     $vs_replacement_result = @preg_replace($va_search, $va_replace, $vs_name);
                                     if (is_null($vs_replacement_result)) {
                                         $o_log->logError(_t("There was an error in preg_replace while processing replacement %1.", $vs_replacement_code));
                                     }
                                     if ($vs_replacement_result && strlen($vs_replacement_result) > 0) {
                                         $o_log->logDebug(_t("The result for replacement with code %1 applied to value '%2' is '%3' and was added to the list of file names used for matching.", $vs_replacement_code, $vs_name, $vs_replacement_result));
                                         $va_names_to_match[] = $vs_replacement_result;
                                     }
                                 } else {
                                     $o_log->logDebug(_t("Skipped replacement %1 because no search expression was defined.", $vs_replacement_code));
                                 }
                             }
                         }
                     }
                     $o_log->logDebug("Names to match: " . print_r($va_names_to_match, true));
                     foreach ($va_names_to_match as $vs_match_name) {
                         if (preg_match('!' . $vs_regex . '!', $vs_match_name, $va_matches)) {
                             $o_log->logDebug(_t("Matched name %1 on regex %2", $vs_match_name, $vs_regex));
                             if (!$vs_idno || strlen($va_matches[1]) < strlen($vs_idno)) {
                                 $vs_idno = $va_matches[1];
                             }
                             if (!$vs_modified_filename || strlen($vs_modified_filename) > strlen($va_matches[1])) {
                                 $vs_modified_filename = $va_matches[1];
                             }
                             $va_extracted_idnos_from_filename[] = $va_matches[1];
                             if (in_array($vs_import_mode, array('TRY_TO_MATCH', 'ALWAYS_MATCH'))) {
                                 if (!is_array($va_fields_to_match_on = $po_request->config->getList('batch_media_import_match_on')) || !sizeof($va_fields_to_match_on)) {
                                     $batch_media_import_match_on = array('idno');
                                 }
                                 $vs_bool = 'OR';
                                 $va_values = array();
                                 foreach ($va_fields_to_match_on as $vs_fld) {
                                     if (in_array($vs_fld, array('preferred_labels', 'nonpreferred_labels'))) {
                                         $va_values[$vs_fld] = array($vs_fld => array('name' => $va_matches[1]));
                                     } else {
                                         $va_values[$vs_fld] = $va_matches[1];
                                     }
                                 }
                                 if (is_array($va_limit_matching_to_type_ids) && sizeof($va_limit_matching_to_type_ids) > 0) {
                                     $va_values['type_id'] = $va_limit_matching_to_type_ids;
                                     $vs_bool = 'AND';
                                 }
                                 $o_log->logDebug("Trying to find records using boolean {$vs_bool} and values " . print_r($va_values, true));
                                 if (class_exists($vs_import_target) && ($vn_id = $vs_import_target::find($va_values, array('returnAs' => 'firstId', 'boolean' => $vs_bool)))) {
                                     if ($t_instance->load($vn_id)) {
                                         $va_notices[$vs_relative_directory . '/' . $vs_match_name . '_match'] = array('idno' => $t_instance->get($t_instance->getProperty('ID_NUMBERING_ID_FIELD')), 'label' => $t_instance->getLabelForDisplay(), 'message' => $vs_msg = _t('Matched media %1 from %2 to %3 using expression "%4"', $f, $vs_relative_directory, caGetTableDisplayName($vs_import_target, false), $va_regex_info['displayName']), 'status' => 'MATCHED');
                                         $o_log->logInfo($vs_msg);
                                     }
                                     break 3;
                                 }
                             }
                         } else {
                             $o_log->logDebug(_t("Couldn't match name %1 on regex %2", $vs_match_name, $vs_regex));
                         }
                     }
                 }
             }
         }
         if (!$t_instance->getPrimaryKey()) {
             // Use filename as idno if all else fails
             if ($t_instance->load(array('idno' => $f, 'deleted' => 0))) {
                 $va_notices[$vs_relative_directory . '/' . $f . '_match'] = array('idno' => $t_instance->get($t_instance->getProperty('ID_NUMBERING_ID_FIELD')), 'label' => $t_instance->getLabelForDisplay(), 'message' => $vs_msg = _t('Matched media %1 from %2 to %3 using filename', $f, $vs_relative_directory, caGetTableDisplayName($vs_import_target, false)), 'status' => 'MATCHED');
                 $o_log->logInfo($vs_msg);
             }
         }
         switch ($vs_representation_idno_mode) {
             case 'filename':
                 // use the filename as identifier
                 $vs_rep_idno = $f;
                 break;
             case 'filename_no_ext':
                 // use filename without extension as identifier
                 $vs_rep_idno = preg_replace('/\\.[^.\\s]{3,4}$/', '', $f);
                 break;
             case 'directory_and_filename':
                 // use the directory + filename as identifier
                 $vs_rep_idno = $d . '/' . $f;
                 break;
             default:
                 // use idno from form
                 $vs_rep_idno = $vs_representation_idno;
                 break;
         }
         $t_new_rep = null;
         if ($t_instance->getPrimaryKey() && $t_instance instanceof RepresentableBaseModel) {
             // found existing object
             $t_instance->setMode(ACCESS_WRITE);
             $t_new_rep = $t_instance->addRepresentation($vs_directory . '/' . $f, $vn_rep_type_id, $vn_locale_id, $vn_object_representation_status, $vn_object_representation_access, false, array('idno' => $vs_rep_idno), array('original_filename' => $f, 'returnRepresentation' => true, 'type_id' => $vn_rel_type_id));
             if ($t_instance->numErrors()) {
                 $o_eventlog->log(array("CODE" => 'ERR', "SOURCE" => "mediaImport", "MESSAGE" => _t("Error importing {$f} from {$vs_directory}: %1", join('; ', $t_instance->getErrors()))));
                 $va_errors[$vs_relative_directory . '/' . $f] = array('idno' => $t_instance->get($t_instance->getProperty('ID_NUMBERING_ID_FIELD')), 'label' => $t_instance->getLabelForDisplay(), 'errors' => $t_instance->errors(), 'message' => $vs_msg = _t("Error importing %1 from %2: %3", $f, $vs_relative_directory, join('; ', $t_instance->getErrors())), 'status' => 'ERROR');
                 $o_log->logError($vs_msg);
                 $o_trans->rollback();
                 continue;
             } else {
                 if ($vb_delete_media_on_import) {
                     @unlink($vs_directory . '/' . $f);
                 }
             }
         } else {
             // should we create new record?
             if (in_array($vs_import_mode, array('TRY_TO_MATCH', 'DONT_MATCH'))) {
                 $t_instance->setMode(ACCESS_WRITE);
                 $t_instance->set('type_id', $vn_type_id);
                 $t_instance->set('locale_id', $vn_locale_id);
                 $t_instance->set('status', $vn_status);
                 $t_instance->set('access', $vn_access);
                 // for places, take first hierarchy we can find. in most setups there is but one. we might wanna make this configurable via setup screen at some point
                 if ($t_instance->hasField('hierarchy_id')) {
                     $va_hierarchies = $t_instance->getHierarchyList();
                     reset($va_hierarchies);
                     $vn_hierarchy_id = key($va_hierarchies);
                     $t_instance->set('hierarchy_id', $vn_hierarchy_id);
                 }
                 switch ($vs_idno_mode) {
                     case 'filename':
                         // use the filename as identifier
                         $t_instance->set('idno', $f);
                         break;
                     case 'filename_no_ext':
                         // use filename without extension as identifier
                         $f_no_ext = preg_replace('/\\.[^.\\s]{3,4}$/', '', $f);
                         $t_instance->set('idno', $f_no_ext);
                         break;
                     case 'directory_and_filename':
                         // use the directory + filename as identifier
                         $t_instance->set('idno', $d . '/' . $f);
                         break;
                     default:
                         // Calculate identifier using numbering plugin
                         $o_numbering_plugin = $t_instance->getIDNoPlugInInstance();
                         if (!($vs_sep = $o_numbering_plugin->getSeparator())) {
                             $vs_sep = '';
                         }
                         if (!is_array($va_idno_values = $o_numbering_plugin->htmlFormValuesAsArray('idno', null, false, false, true))) {
                             $va_idno_values = array();
                         }
                         $t_instance->set('idno', join($vs_sep, $va_idno_values));
                         // true=always set serial values, even if they already have a value; this let's us use the original pattern while replacing the serial value every time through
                         break;
                 }
                 $t_instance->insert();
                 if ($t_instance->numErrors()) {
                     $o_eventlog->log(array("CODE" => 'ERR', "SOURCE" => "mediaImport", "MESSAGE" => _t("Error creating new record while importing %1 from %2: %3", $f, $vs_relative_directory, join('; ', $t_instance->getErrors()))));
                     $va_errors[$vs_relative_directory . '/' . $f] = array('idno' => $t_instance->get($t_instance->getProperty('ID_NUMBERING_ID_FIELD')), 'label' => $t_instance->getLabelForDisplay(), 'errors' => $t_instance->errors(), 'message' => $vs_msg = _t("Error creating new record while importing %1 from %2: %3", $f, $vs_relative_directory, join('; ', $t_instance->getErrors())), 'status' => 'ERROR');
                     $o_log->logError($vs_msg);
                     $o_trans->rollback();
                     continue;
                 }
                 if ($t_instance->tableName() == 'ca_entities') {
                     // entity labels deserve special treatment
                     $t_instance->addLabel(array('surname' => $f), $vn_locale_id, null, true);
                 } else {
                     $t_instance->addLabel(array($t_instance->getLabelDisplayField() => $f), $vn_locale_id, null, true);
                 }
                 if ($t_instance->numErrors()) {
                     $o_eventlog->log(array("CODE" => 'ERR', "SOURCE" => "mediaImport", "MESSAGE" => _t("Error creating record label while importing %1 from %2: %3", $f, $vs_relative_directory, join('; ', $t_instance->getErrors()))));
                     $va_errors[$vs_relative_directory . '/' . $f] = array('idno' => $t_instance->get($t_instance->getProperty('ID_NUMBERING_ID_FIELD')), 'label' => $t_instance->getLabelForDisplay(), 'errors' => $t_instance->errors(), 'message' => $vs_msg = _t("Error creating record label while importing %1 from %2: %3", $f, $vs_relative_directory, join('; ', $t_instance->getErrors())), 'status' => 'ERROR');
                     $o_log->logError($vs_msg);
                     $o_trans->rollback();
                     continue;
                 }
                 $t_new_rep = $t_instance->addRepresentation($vs_directory . '/' . $f, $vn_rep_type_id, $vn_locale_id, $vn_object_representation_status, $vn_object_representation_access, true, array('idno' => $vs_rep_idno), array('original_filename' => $f, 'returnRepresentation' => true, 'type_id' => $vn_rel_type_id));
                 if ($t_instance->numErrors()) {
                     $o_eventlog->log(array("CODE" => 'ERR', "SOURCE" => "mediaImport", "MESSAGE" => _t("Error importing %1 from %2: ", $f, $vs_relative_directory, join('; ', $t_instance->getErrors()))));
                     $va_errors[$vs_relative_directory . '/' . $f] = array('idno' => $t_instance->get($t_instance->getProperty('ID_NUMBERING_ID_FIELD')), 'label' => $t_instance->getLabelForDisplay(), 'errors' => $t_instance->errors(), 'message' => $vs_msg = _t("Error importing %1 from %2: %3", $f, $vs_relative_directory, join('; ', $t_instance->getErrors())), 'status' => 'ERROR');
                     $o_log->logError($vs_msg);
                     $o_trans->rollback();
                     continue;
                 } else {
                     if ($vb_delete_media_on_import) {
                         @unlink($vs_directory . '/' . $f);
                     }
                 }
             }
         }
         if ($t_instance->getPrimaryKey()) {
             // Perform import of embedded metadata (if required)
             if ($vn_mapping_id) {
                 ca_data_importers::importDataFromSource($vs_directory . '/' . $f, $vn_mapping_id, array('logLevel' => $vs_log_level, 'format' => 'exif', 'forceImportForPrimaryKeys' => array($t_instance->getPrimaryKey(), 'transaction' => $o_trans)));
             }
             if ($vn_object_representation_mapping_id) {
                 ca_data_importers::importDataFromSource($vs_directory . '/' . $f, $vn_object_representation_mapping_id, array('logLevel' => $vs_log_level, 'format' => 'exif', 'forceImportForPrimaryKeys' => array($t_new_rep->getPrimaryKey()), 'transaction' => $o_trans));
             }
             $va_notices[$t_instance->getPrimaryKey()] = array('idno' => $t_instance->get($t_instance->getProperty('ID_NUMBERING_ID_FIELD')), 'label' => $t_instance->getLabelForDisplay(), 'message' => $vs_msg = _t('Imported %1 as %2', $f, $t_instance->get($t_instance->getProperty('ID_NUMBERING_ID_FIELD'))), 'status' => 'SUCCESS');
             $o_log->logInfo($vs_msg);
             if ($vn_set_id) {
                 $t_set->addItem($t_instance->getPrimaryKey(), null, $po_request->getUserID());
             }
             $o_batch_log->addItem($t_instance->getPrimaryKey(), $t_instance->errors());
             // Create relationships?
             if (is_array($va_create_relationship_for) && sizeof($va_create_relationship_for) && is_array($va_extracted_idnos_from_filename) && sizeof($va_extracted_idnos_from_filename)) {
                 foreach ($va_extracted_idnos_from_filename as $vs_idno) {
                     foreach ($va_create_relationship_for as $vs_rel_table) {
                         if (!isset($va_relationship_type_id_for[$vs_rel_table]) || !$va_relationship_type_id_for[$vs_rel_table]) {
                             continue;
                         }
                         $t_rel = $t_instance->getAppDatamodel()->getInstanceByTableName($vs_rel_table);
                         if ($t_rel->load(array($t_rel->getProperty('ID_NUMBERING_ID_FIELD') => $vs_idno))) {
                             $t_instance->addRelationship($vs_rel_table, $t_rel->getPrimaryKey(), $va_relationship_type_id_for[$vs_rel_table]);
                             if (!$t_instance->numErrors()) {
                                 $va_notices[$t_instance->getPrimaryKey() . '_rel'] = array('idno' => $t_instance->get($t_instance->getProperty('ID_NUMBERING_ID_FIELD')), 'label' => $vs_label = $t_instance->getLabelForDisplay(), 'message' => $vs_msg = _t('Added relationship between <em>%1</em> and %2 <em>%3</em>', $vs_label, $t_rel->getProperty('NAME_SINGULAR'), $t_rel->getLabelForDisplay()), 'status' => 'RELATED');
                                 $o_log->logInfo($vs_msg);
                             } else {
                                 $va_notices[$t_instance->getPrimaryKey()] = array('idno' => $t_instance->get($t_instance->getProperty('ID_NUMBERING_ID_FIELD')), 'label' => $vs_label = $t_instance->getLabelForDisplay(), 'message' => $vs_msg = _t('Could not add relationship between <em>%1</em> and %2 <em>%3</em>: %4', $vs_label, $t_rel->getProperty('NAME_SINGULAR'), $t_rel->getLabelForDisplay(), join("; ", $t_instance->getErrors())), 'status' => 'ERROR');
                                 $o_log->logError($vs_msg);
                             }
                         }
                     }
                 }
             }
         } else {
             $va_notices[$vs_relative_directory . '/' . $f] = array('idno' => '', 'label' => $f, 'message' => $vs_msg = $vs_import_mode == 'ALWAYS_MATCH' ? _t('Skipped %1 from %2 because it could not be matched', $f, $vs_relative_directory) : _t('Skipped %1 from %2', $f, $vs_relative_directory), 'status' => 'SKIPPED');
             $o_log->logInfo($vs_msg);
         }
         if (isset($pa_options['progressCallback']) && ($ps_callback = $pa_options['progressCallback'])) {
             $ps_callback($po_request, $vn_c, $vn_num_items, _t("[%3/%4] Processing %1 (%3)", caTruncateStringWithEllipsis($vs_relative_directory, 20) . '/' . caTruncateStringWithEllipsis($f, 30), $t_instance->get($t_instance->getProperty('ID_NUMBERING_ID_FIELD')), $vn_c, $vn_num_items), $t_new_rep, time() - $vn_start_time, memory_get_usage(true), $vn_c, sizeof($va_errors));
         }
         $vn_c++;
     }
     if (isset($pa_options['progressCallback']) && ($ps_callback = $pa_options['progressCallback'])) {
         $ps_callback($po_request, $vn_num_items, $vn_num_items, _t("Processing completed"), null, time() - $vn_start_time, memory_get_usage(true), $vn_c, sizeof($va_errors));
     }
     $vn_elapsed_time = time() - $vn_start_time;
     if (isset($pa_options['reportCallback']) && ($ps_callback = $pa_options['reportCallback'])) {
         $va_general = array('elapsedTime' => $vn_elapsed_time, 'numErrors' => sizeof($va_errors), 'numProcessed' => $vn_c, 'batchSize' => $vn_num_items, 'table' => $t_instance->tableName(), 'set_id' => $t_set->getPrimaryKey(), 'setName' => $t_set->getLabelForDisplay());
         $ps_callback($po_request, $va_general, $va_notices, $va_errors);
     }
     $o_batch_log->close();
     if ($vb_we_set_transaction) {
         if (sizeof($va_errors) > 0) {
             $o_trans->rollback();
         } else {
             $o_trans->commit();
         }
     }
     $vs_set_name = $t_set->getLabelForDisplay();
     $vs_started_on = caGetLocalizedDate($vn_start_time);
     if (isset($pa_options['sendMail']) && $pa_options['sendMail']) {
         if ($vs_email = trim($po_request->user->get('email'))) {
             caSendMessageUsingView($po_request, array($vs_email => $po_request->user->get('fname') . ' ' . $po_request->user->get('lname')), __CA_ADMIN_EMAIL__, _t('[%1] Batch media import completed', $po_request->config->get('app_display_name')), 'batch_media_import_completed.tpl', array('notices' => $va_notices, 'errors' => $va_errors, 'directory' => $vs_relative_directory, 'numErrors' => sizeof($va_errors), 'numProcessed' => $vn_c, 'subjectNameSingular' => _t('file'), 'subjectNamePlural' => _t('files'), 'startedOn' => $vs_started_on, 'completedOn' => caGetLocalizedDate(time()), 'setName' => $vn_set_id ? $vs_set_name : null, 'elapsedTime' => caFormatInterval($vn_elapsed_time)));
         }
     }
     if (isset($pa_options['sendSMS']) && $pa_options['sendSMS']) {
         SMS::send($po_request->getUserID(), _t("[%1] Media import processing for directory %2 with %3 %4 begun at %5 is complete", $po_request->config->get('app_display_name'), $vs_relative_directory, $vn_num_items, $vn_num_items == 1 ? _t('file') : _t('files'), $vs_started_on));
     }
     $o_log->logInfo(_t("Media import processing for directory %1 with %2 %3 begun at %4 is complete", $vs_relative_directory, $vn_num_items, $vn_num_items == 1 ? _t('file') : _t('files')));
     return array('errors' => $va_errors, 'notices' => $va_notices, 'processing_time' => caFormatInterval($vn_elapsed_time));
 }
Exemplo n.º 15
0
 public function forward($ps_path)
 {
     $this->opo_request->setPath($ps_path);
     $this->opo_request->setIsDispatched(false);
 }
Exemplo n.º 16
0
 /**
  *	Return navigation configuration fragment suitable for insertion into the navigation.conf structure.
  *	Can be used by lib/core/AppNavigation to dynamically insert navigation for screens into navigation tree
  *
  * @param RequestHTTP $po_request
  * @param int $pn_type_id
  * @param string $ps_module_path
  * @param string $ps_controller
  * @param string $ps_action
  * @param array $pa_parameters
  * @param array $pa_requirements
  * @param bool $pb_disable_options
  * @param array $pa_options	Values to include in returned array for each screen. Values are returned as-is. Specific options also have the following effects:
  *		returnTypeRestrictions = return list of type restrictions for screen. Default is false. 
  *		restrictToTypes = 
  *		user_id = User_id to apply access control for
  * @return array
  */
 public function getScreensAsNavConfigFragment($po_request, $pn_type_id, $ps_module_path, $ps_controller, $ps_action, $pa_parameters, $pa_requirements, $pb_disable_options = false, $pa_options = null)
 {
     if (!caGetOption('user_id', $pa_options, null) && $po_request) {
         $pa_options['user_id'] = $po_request->getUserID();
     }
     if (!($va_screens = $this->getScreens($pn_type_id, $pa_options))) {
         return false;
     }
     $va_nav = array();
     $vn_default_screen_id = null;
     foreach ($va_screens as $va_screen) {
         if (isset($pa_options['restrictToTypes']) && is_array($pa_options['restrictToTypes']) && is_array($va_screen['typeRestrictions']) && sizeof($va_screen['typeRestrictions']) > 0) {
             $vb_skip = true;
             foreach ($pa_options['restrictToTypes'] as $vn_res_type_id => $vs_res_type) {
                 if (isset($va_screen['typeRestrictions'][$vn_res_type_id]) && $va_screen['typeRestrictions'][$vn_res_type_id]) {
                     $vb_skip = false;
                     break;
                 }
             }
             if ($vb_skip) {
                 continue;
             }
         }
         if (!$vn_default_screen_id) {
             $vn_default_screen_id = $va_screen['screen_id'];
         }
         $va_nav['screen_' . $va_screen['screen_id']] = array('displayName' => $va_screen['name'], "default" => array('module' => $ps_module_path, 'controller' => $ps_controller, 'action' => $ps_action . '/Screen' . $va_screen['screen_id']), "useActionInPath" => 0, "useActionExtraInPath" => 1, "disabled" => $pb_disable_options, "requires" => $pa_requirements, "parameters" => $pa_parameters);
         if (isset($pa_options['returnTypeRestrictions']) && $pa_options['returnTypeRestrictions']) {
             $va_nav['screen_' . $va_screen['screen_id']]['typeRestrictions'] = $va_screen['typeRestrictions'];
         }
         if (is_array($pa_options)) {
             $va_nav['screen_' . $va_screen['screen_id']] = array_merge($va_nav['screen_' . $va_screen['screen_id']], $pa_options);
         }
         if ($va_screen['is_default']) {
             $vn_default_screen_id = $va_screen['screen_id'];
         }
     }
     return array('fragment' => $va_nav, 'defaultScreen' => 'Screen' . $vn_default_screen_id);
 }