コード例 #1
0
 /**
  * Return an RDF object based an a $row
  */
 public function rdf($row, $prefix = '')
 {
     $row->type = isset($row->type) ? $row->type : 'version';
     if (isset($row->url)) {
         if (!is_array($row->url)) {
             $row->url = array($row->url);
         }
         foreach ($row->url as $key => $value) {
             if (!isURL($value)) {
                 $row->url[$key] = abs_url($value, $prefix);
             }
         }
     }
     $rdf = parent::rdf($row, $prefix);
     // Blend with RDF from the semantic store
     if (!empty($row->rdf)) {
         foreach ($row->rdf as $p => $values) {
             if (array_key_exists($p, $rdf)) {
                 // TODO: Not sure we should allow a collision between the semantic and relational tables? For now, don't.
             } else {
                 $rdf[$p] = $values;
             }
         }
     }
     return $rdf;
 }
コード例 #2
0
 private function rdf_value($value = array())
 {
     $return = array();
     foreach ($value as $val) {
         if (empty($val)) {
             continue;
         }
         $return[] = array('value' => $val, 'type' => isURL($val) ? 'uri' : 'literal');
     }
     return $return;
 }
コード例 #3
0
ファイル: wrapper.php プロジェクト: austinvernsonger/scalar
function print_rdf($rdf, $tabs = 0, $ns = array(), $hide = array(), $aria = false)
{
    $hide = array_merge($hide, array('rdf:type', 'dcterms:title', 'sioc:content'));
    foreach ($rdf as $p => $values) {
        if (in_array($p, $hide)) {
            continue;
        }
        foreach ($values as $value) {
            if (isURL($value['value'])) {
                $str = '<a class="metadata" aria-hidden="' . ($aria ? 'false' : 'true') . '" rel="' . toNS($p, $ns) . '" href="' . $value['value'] . '"></a>' . "\n";
            } else {
                $str = '<span class="metadata" aria-hidden="' . ($aria ? 'false' : 'true') . '" property="' . toNS($p, $ns) . '">' . $value['value'] . '</span>' . "\n";
            }
            for ($j = 0; $j < $tabs; $j++) {
                $str = "\t" . $str;
            }
            echo $str;
        }
    }
}
コード例 #4
0
 /** 
  * Perform lookup on Wikipedia-based data service
  *
  * @param array $pa_settings Plugin settings values
  * @param string $ps_search The expression with which to query the remote data service
  * @param array $pa_options Lookup options (none defined yet)
  * @return array
  */
 public function lookup($pa_settings, $ps_search, $pa_options = null)
 {
     // support passing full wikipedia URLs
     if (isURL($ps_search)) {
         $ps_search = self::getPageTitleFromURI($ps_search);
     }
     $vs_lang = caGetOption('lang', $pa_settings, 'en');
     // readable version of get parameters
     $va_get_params = array('action' => 'query', 'generator' => 'search', 'gsrsearch' => urlencode($ps_search), 'gsrlimit' => 50, 'gsrwhat' => 'nearmatch', 'prop' => 'info', 'inprop' => 'url', 'format' => 'json');
     $vs_content = caQueryExternalWebservice($vs_url = 'https://' . $vs_lang . '.wikipedia.org/w/api.php?' . caConcatGetParams($va_get_params));
     $va_content = @json_decode($vs_content, true);
     if (!is_array($va_content) || !isset($va_content['query']['pages']) || !is_array($va_content['query']['pages']) || !sizeof($va_content['query']['pages'])) {
         return array();
     }
     // the top two levels are 'query' and 'pages'
     $va_results = $va_content['query']['pages'];
     $va_return = array();
     foreach ($va_results as $va_result) {
         $va_return['results'][] = array('label' => $va_result['title'] . ' [' . $va_result['fullurl'] . ']', 'url' => $va_result['fullurl'], 'idno' => $va_result['pageid']);
     }
     return $va_return;
 }
コード例 #5
0
/**
 * Query external web service and return whatever body it returns as string
 * @param string $ps_url URL of the web service to query
 * @return string
 * @throws \Exception
 */
function caQueryExternalWebservice($ps_url)
{
    if (!isURL($ps_url)) {
        return false;
    }
    $o_conf = Configuration::load();
    $vo_curl = curl_init();
    curl_setopt($vo_curl, CURLOPT_URL, $ps_url);
    if ($vs_proxy = $o_conf->get('web_services_proxy_url')) {
        /* proxy server is configured */
        curl_setopt($vo_curl, CURLOPT_PROXY, $vs_proxy);
    }
    curl_setopt($vo_curl, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($vo_curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($vo_curl, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($vo_curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($vo_curl, CURLOPT_AUTOREFERER, true);
    curl_setopt($vo_curl, CURLOPT_CONNECTTIMEOUT, 120);
    curl_setopt($vo_curl, CURLOPT_TIMEOUT, 120);
    curl_setopt($vo_curl, CURLOPT_MAXREDIRS, 10);
    curl_setopt($vo_curl, CURLOPT_USERAGENT, 'CollectiveAccess web service lookup');
    $vs_content = curl_exec($vo_curl);
    if (curl_getinfo($vo_curl, CURLINFO_HTTP_CODE) !== 200) {
        throw new \Exception(_t('An error occurred while querying an external webservice'));
    }
    curl_close($vo_curl);
    return $vs_content;
}
コード例 #6
0
ファイル: utilityHelpers.php プロジェクト: kai-iak/pawtucket2
/**
 * Query external web service and return whatever body it returns as string
 * @param string $ps_url URL of the web service to query
 * @return string
 */
function caQueryExternalWebservice($ps_url)
{
    if (!isURL($ps_url)) {
        return false;
    }
    $o_conf = Configuration::load();
    if ($vs_proxy = $o_conf->get('web_services_proxy_url')) {
        /* proxy server is configured */
        $vs_proxy_auth = null;
        if (($vs_proxy_user = $o_conf->get('web_services_proxy_auth_user')) && ($vs_proxy_pass = $o_conf->get('web_services_proxy_auth_pw'))) {
            $vs_proxy_auth = base64_encode("{$vs_proxy_user}:{$vs_proxy_pass}");
        }
        // non-authed proxy requests go through curl to properly support https queries
        // everything else is still handled via file_get_contents and stream contexts
        if (is_null($vs_proxy_auth) && function_exists('curl_exec')) {
            $vo_curl = curl_init();
            curl_setopt($vo_curl, CURLOPT_URL, $ps_url);
            curl_setopt($vo_curl, CURLOPT_PROXY, $vs_proxy);
            curl_setopt($vo_curl, CURLOPT_SSL_VERIFYHOST, 0);
            curl_setopt($vo_curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($vo_curl, CURLOPT_FOLLOWLOCATION, true);
            curl_setopt($vo_curl, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($vo_curl, CURLOPT_AUTOREFERER, true);
            curl_setopt($vo_curl, CURLOPT_CONNECTTIMEOUT, 120);
            curl_setopt($vo_curl, CURLOPT_TIMEOUT, 120);
            curl_setopt($vo_curl, CURLOPT_MAXREDIRS, 10);
            curl_setopt($vo_curl, CURLOPT_USERAGENT, 'CollectiveAccess web service lookup');
            $vs_content = curl_exec($vo_curl);
            curl_close($vo_curl);
            return $vs_content;
        } else {
            $va_context_options = array('http' => array('proxy' => $vs_proxy, 'request_fulluri' => true, 'header' => 'User-agent: CollectiveAccess web service lookup'));
            if ($vs_proxy_auth) {
                $va_context_options['http']['header'] = "Proxy-Authorization: Basic {$vs_proxy_auth}";
            }
            $vo_context = stream_context_create($va_context_options);
            return @file_get_contents($ps_url, false, $vo_context);
        }
    } else {
        return @file_get_contents($ps_url);
    }
}
コード例 #7
0
ファイル: tiki-editpage.php プロジェクト: hurcane/tiki-azure
 if ($requestedWatch !== $currentlyWatching) {
     if ($requestedWatch) {
         $tikilib->add_user_watch($user, 'wiki_page_changed', $page, 'wiki page', $page, $wikilib->sefurl($page));
     } else {
         $tikilib->remove_user_watch($user, 'wiki_page_changed', $page, 'wiki page');
     }
 }
 if (!empty($prefs['geo_locate_wiki']) && $prefs['geo_locate_wiki'] == 'y' && !empty($_REQUEST['geolocation'])) {
     TikiLib::lib('geo')->set_coordinates('wiki page', $page, $_REQUEST['geolocation']);
 }
 if ($prefs['namespace_enabled'] == 'y' && isset($_REQUEST['explicit_namespace'])) {
     $wikilib->set_explicit_namespace($page, $_REQUEST['explicit_namespace']);
 }
 if (!empty($_REQUEST['returnto'])) {
     // came from wikiplugin_include.php edit button
     if (isURL($_REQUEST['returnto'])) {
         $url = $_REQUEST['returnto'];
     } else {
         $url = $wikilib->sefurl($_REQUEST['returnto']);
     }
 } else {
     if ($page_ref_id) {
         $url = "tiki-index.php?page_ref_id={$page_ref_id}";
     } else {
         $url = $wikilib->sefurl($page);
     }
 }
 if ($prefs['feature_multilingual'] === 'y' && $prefs['feature_best_language'] === 'y' && isset($info['lang']) && $info['lang'] !== $prefs['language']) {
     $url .= (strpos($url, '?') === false ? '?' : '&') . 'no_bl=y';
 }
 if ($prefs['flaggedrev_approval'] == 'y' && $tiki_p_wiki_approve == 'y') {
コード例 #8
0
 /**
  * Returns representation_id for the object representation with the specified name (and type) or idno (regardless of specified type.) If the object does
  * not already exist then it will be created with the specified name, type and locale, as well as with any specified values in the $pa_values array.
  * $pa_values keys should be either valid object fields or attributes.
  *
  * @param string $ps_representation_name Object label name
  * @param int $pn_type_id The type_id of the object type to use if the representation needs to be created
  * @param int $pn_locale_id The locale_id to use if the representation needs to be created (will be used for both the object locale as well as the label locale)
  * @param array $pa_values An optional array of additional values to populate newly created representation records with. These values are *only* used for newly created representation; they will not be applied if the representation named already exists. The array keys should be names of ca_object_representations fields or valid representation attributes. Values should be either a scalar (for single-value attributes) or an array of values for (multi-valued attributes)
  * @param array $pa_options An optional array of options, which include:
  *                outputErrors - if true, errors will be printed to console [default=false]
  *                matchOn = optional list indicating sequence of checks for an existing record; values of array can be "label" and "idno". Ex. array("idno", "label") will first try to match on idno and then label if the first match fails.
  *                dontCreate - if true then new representations will not be created [default=false]
  *                transaction - if Transaction object is passed, use it for all Db-related tasks [default=null]
  *                returnInstance = return ca_object_representations instance rather than representation_id. Default is false.
  *                generateIdnoWithTemplate = A template to use when setting the idno. The template is a value with automatically-set SERIAL values replaced with % characters. Eg. 2012.% will set the created row's idno value to 2012.121 (assuming that 121 is the next number in the serial sequence.) The template is NOT used if idno is passed explicitly as a value in $pa_values.
  *                importEvent = if ca_data_import_events instance is passed then the insert/update of the representation will be logged as part of the import
  *                importEventSource = if importEvent is passed, then the value set for importEventSource is used in the import event log as the data source. If omitted a default value of "?" is used
  *                nonPreferredLabels = an optional array of nonpreferred labels to add to any newly created representations. Each label in the array is an array with required representation label values.
  *                log = if KLogger instance is passed then actions will be logged
  *				  matchMediaFilesWithoutExtension = if media path is invalid, attempt to find media in referenced directory and sub-directories that has a matching name, regardless of file extension. [default=false] 
  * @return bool|ca_object_representations|mixed|null
  */
 static function getObjectRepresentationID($ps_representation_name, $pn_type_id, $pn_locale_id, $pa_values = null, $pa_options = null)
 {
     if (!is_array($pa_options)) {
         $pa_options = array();
     }
     if (!isset($pa_options['outputErrors'])) {
         $pa_options['outputErrors'] = false;
     }
     $vb_match_media_without_extension = caGetOption('matchMediaFilesWithoutExtension', $pa_options, false);
     $pa_match_on = caGetOption('matchOn', $pa_options, array('label', 'idno'), array('castTo' => "array"));
     /** @var ca_data_import_events $o_event */
     $o_event = isset($pa_options['importEvent']) && $pa_options['importEvent'] instanceof ca_data_import_events ? $pa_options['importEvent'] : null;
     $t_rep = new ca_object_representations();
     if (isset($pa_options['transaction']) && $pa_options['transaction'] instanceof Transaction) {
         $t_rep->setTransaction($pa_options['transaction']);
         if ($o_event) {
             $o_event->setTransaction($pa_options['transaction']);
         }
     }
     $vs_event_source = isset($pa_options['importEventSource']) && $pa_options['importEventSource'] ? $pa_options['importEventSource'] : "?";
     /** @var KLogger $o_log */
     $o_log = isset($pa_options['log']) && $pa_options['log'] instanceof KLogger ? $pa_options['log'] : null;
     $vs_idno = isset($pa_values['idno']) ? (string) $pa_values['idno'] : null;
     if (preg_match('!\\%!', $vs_idno)) {
         $pa_options['generateIdnoWithTemplate'] = $vs_idno;
         $vs_idno = null;
     }
     if (!$vs_idno) {
         if (isset($pa_options['generateIdnoWithTemplate']) && $pa_options['generateIdnoWithTemplate']) {
             $vs_idno = $t_rep->setIdnoWithTemplate($pa_options['generateIdnoWithTemplate'], array('dontSetValue' => true));
         }
     }
     $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));
     $vn_id = null;
     foreach ($pa_match_on as $vs_match_on) {
         switch (strtolower($vs_match_on)) {
             case 'label':
             case 'labels':
                 if (trim($ps_representation_name)) {
                     if ($vn_id = ca_object_representations::find(array('preferred_labels' => array('name' => $ps_representation_name), 'type_id' => $pn_type_id), array('returnAs' => 'firstId', 'transaction' => $pa_options['transaction']))) {
                         break 2;
                     }
                 }
                 break;
             case 'idno':
                 if (!$vs_idno) {
                     break;
                 }
                 if ($vs_idno == '%') {
                     break;
                 }
                 // don't try to match on an unreplaced idno placeholder
                 $va_idnos_to_match = array($vs_idno);
                 if (is_array($va_replacements_list)) {
                     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 . '!';
                             }
                             if ($vs_idno_proc = @preg_replace($va_search, $va_replace, $vs_idno)) {
                                 $va_idnos_to_match[] = $vs_idno_proc;
                             }
                         }
                     }
                 }
                 if (is_array($va_regex_list) && sizeof($va_regex_list)) {
                     foreach ($va_regex_list as $vs_regex_name => $va_regex_info) {
                         foreach ($va_regex_info['regexes'] as $vs_regex) {
                             foreach ($va_idnos_to_match as $vs_idno_match) {
                                 if (!$vs_idno_match) {
                                     continue;
                                 }
                                 if (preg_match('!' . $vs_regex . '!', $vs_idno_match, $va_matches)) {
                                     if ($vn_id = ca_object_representations::find(array('idno' => $va_matches[1]), array('returnAs' => 'firstId', 'transaction' => $pa_options['transaction']))) {
                                         break 5;
                                     }
                                 }
                             }
                         }
                     }
                 } else {
                     foreach ($va_idnos_to_match as $vs_idno_match) {
                         if (!$vs_idno_match) {
                             continue;
                         }
                         if ($vn_id = ca_object_representations::find(array('idno' => $vs_idno_match), array('returnAs' => 'firstId', 'transaction' => $pa_options['transaction']))) {
                             break 3;
                         }
                     }
                 }
                 break;
         }
     }
     if (!$vn_id) {
         if (isset($pa_options['dontCreate']) && $pa_options['dontCreate']) {
             return false;
         }
         if ($o_event) {
             $o_event->beginItem($vs_event_source, 'ca_object_representations', 'I');
         }
         $t_rep->setMode(ACCESS_WRITE);
         $t_rep->set('locale_id', $pn_locale_id);
         $t_rep->set('type_id', $pn_type_id);
         $t_rep->set('source_id', isset($pa_values['source_id']) ? $pa_values['source_id'] : null);
         $t_rep->set('access', isset($pa_values['access']) ? $pa_values['access'] : 0);
         $t_rep->set('status', isset($pa_values['status']) ? $pa_values['status'] : 0);
         if (isset($pa_values['media']) && $pa_values['media']) {
             if ($vb_match_media_without_extension && !isURL($pa_values['media']) && !file_exists($pa_values['media'])) {
                 $vs_dirname = pathinfo($pa_values['media'], PATHINFO_DIRNAME);
                 $vs_filename = preg_replace('!\\.[A-Za-z0-9]{1,4}$!', '', pathinfo($pa_values['media'], PATHINFO_BASENAME));
                 $vs_original_path = $pa_values['media'];
                 $pa_values['media'] = null;
                 $va_files_in_dir = caGetDirectoryContentsAsList($vs_dirname, true, false, false, false);
                 foreach ($va_files_in_dir as $vs_filepath) {
                     if ($o_log) {
                         $o_log->logDebug(_t("Trying media %1 in place of %2/%3", $vs_filepath, $vs_original_path, $vs_filename));
                     }
                     if (pathinfo($vs_filepath, PATHINFO_FILENAME) == $vs_filename) {
                         if ($o_log) {
                             $o_log->logNotice(_t("Found media %1 for %2/%3", $vs_filepath, $vs_original_path, $vs_filename));
                         }
                         $pa_values['media'] = $vs_filepath;
                         break;
                     }
                 }
             }
             $t_rep->set('media', $pa_values['media']);
         }
         $t_rep->set('idno', $vs_idno);
         $t_rep->insert();
         if ($t_rep->numErrors()) {
             if (isset($pa_options['outputErrors']) && $pa_options['outputErrors']) {
                 print "[Error] " . _t("Could not insert object %1: %2", $ps_representation_name, join('; ', $t_rep->getErrors())) . "\n";
             }
             if ($o_log) {
                 $o_log->logError(_t("Could not insert object %1: %2", $ps_representation_name, join('; ', $t_rep->getErrors())));
             }
             return null;
         }
         $vb_label_errors = false;
         $t_rep->addLabel(array('name' => $ps_representation_name), $pn_locale_id, null, true);
         if ($t_rep->numErrors()) {
             if (isset($pa_options['outputErrors']) && $pa_options['outputErrors']) {
                 print "[Error] " . _t("Could not set preferred label for object %1: %2", $ps_representation_name, join('; ', $t_rep->getErrors())) . "\n";
             }
             if ($o_log) {
                 $o_log->logError(_t("Could not set preferred label for object %1: %2", $ps_representation_name, join('; ', $t_rep->getErrors())));
             }
             $vb_label_errors = true;
         }
         /** @var IIDNumbering $o_idno */
         if ($o_idno = $t_rep->getIDNoPlugInInstance()) {
             $va_values = $o_idno->htmlFormValuesAsArray('idno', $vs_idno);
             if (!is_array($va_values)) {
                 $va_values = array($va_values);
             }
             if (!($vs_sep = $o_idno->getSeparator())) {
                 $vs_sep = '';
             }
             if (($vs_proc_idno = join($vs_sep, $va_values)) && $vs_proc_idno != $vs_idno) {
                 $t_rep->set('idno', $vs_proc_idno);
                 $t_rep->update();
                 if ($t_rep->numErrors()) {
                     if (isset($pa_options['outputErrors']) && $pa_options['outputErrors']) {
                         print "[Error] " . _t("Could not update idno for %1: %2", $ps_representation_name, join('; ', $t_rep->getErrors())) . "\n";
                     }
                     if ($o_log) {
                         $o_log->logError(_t("Could not object idno for %1: %2", $ps_representation_name, join('; ', $t_rep->getErrors())));
                     }
                     return null;
                 }
             }
         }
         unset($pa_values['access']);
         unset($pa_values['status']);
         unset($pa_values['idno']);
         unset($pa_values['source_id']);
         $vb_attr_errors = false;
         if (is_array($pa_values)) {
             foreach ($pa_values as $vs_element => $va_values) {
                 if (!caIsIndexedArray($va_values)) {
                     $va_values = array($va_values);
                 }
                 foreach ($va_values as $va_value) {
                     if (is_array($va_value)) {
                         // array of values (complex multi-valued attribute)
                         $t_rep->addAttribute(array_merge($va_value, array('locale_id' => $pn_locale_id)), $vs_element);
                     } else {
                         // scalar value (simple single value attribute)
                         if ($va_value) {
                             $t_rep->addAttribute(array('locale_id' => $pn_locale_id, $vs_element => $va_value), $vs_element);
                         }
                     }
                 }
             }
             $t_rep->update();
             if ($t_rep->numErrors()) {
                 if (isset($pa_options['outputErrors']) && $pa_options['outputErrors']) {
                     print "[Error] " . _t("Could not set values for representation %1: %2", $ps_representation_name, join('; ', $t_rep->getErrors())) . "\n";
                 }
                 if ($o_log) {
                     $o_log->logError(_t("Could not set values for representation %1: %2", $ps_representation_name, join('; ', $t_rep->getErrors())));
                 }
                 $vb_attr_errors = true;
             }
         }
         if (is_array($va_nonpreferred_labels = caGetOption("nonPreferredLabels", $pa_options, null))) {
             if (caIsAssociativeArray($va_nonpreferred_labels)) {
                 // single non-preferred label
                 $va_labels = array($va_nonpreferred_labels);
             } else {
                 // list of non-preferred labels
                 $va_labels = $va_nonpreferred_labels;
             }
             foreach ($va_labels as $va_label) {
                 $t_rep->addLabel($va_label, $pn_locale_id, null, false);
                 if ($t_rep->numErrors()) {
                     if (isset($pa_options['outputErrors']) && $pa_options['outputErrors']) {
                         print "[Error] " . _t("Could not set non-preferred label for representation %1: %2", $ps_representation_name, join('; ', $t_rep->getErrors())) . "\n";
                     }
                     if ($o_log) {
                         $o_log->logError(_t("Could not set non-preferred label for representation %1: %2", $ps_representation_name, join('; ', $t_rep->getErrors())));
                     }
                 }
             }
         }
         $vn_representation_id = $t_rep->getPrimaryKey();
         if ($o_event) {
             if ($vb_attr_errors || $vb_label_errors) {
                 $o_event->endItem($vn_representation_id, __CA_DATA_IMPORT_ITEM_PARTIAL_SUCCESS__, _t("Errors setting field values: %1", join('; ', $t_rep->getErrors())));
             } else {
                 $o_event->endItem($vn_representation_id, __CA_DATA_IMPORT_ITEM_SUCCESS__, '');
             }
         }
         if ($o_log) {
             $o_log->logInfo(_t("Created new representation %1", $ps_representation_name));
         }
         if (isset($pa_options['returnInstance']) && $pa_options['returnInstance']) {
             return $t_rep;
         }
     } else {
         if ($o_event) {
             $o_event->beginItem($vs_event_source, 'ca_object_representations', 'U');
         }
         $vn_representation_id = $vn_id;
         if ($o_event) {
             $o_event->endItem($vn_representation_id, __CA_DATA_IMPORT_ITEM_SUCCESS__, '');
         }
         if ($o_log) {
             $o_log->logDebug(_t("Found existing representation %1 in DataMigrationUtils::getObjectRepresentationID()", $ps_representation_name));
         }
         if (isset($pa_options['returnInstance']) && $pa_options['returnInstance']) {
             $t_rep = new ca_object_representations($vn_representation_id);
             if (isset($pa_options['transaction']) && $pa_options['transaction'] instanceof Transaction) {
                 $t_rep->setTransaction($pa_options['transaction']);
             }
             return $t_rep;
         }
     }
     return $vn_representation_id;
 }
コード例 #9
0
 /**
  *
  *
  */
 public function parseValue($ps_value, $pa_element_info, $pa_options = null)
 {
     $ps_value = trim(preg_replace("![\t\n\r]+!", ' ', $ps_value));
     $vs_service = caGetOption('service', $this->getSettingValuesFromElementArray($pa_element_info, array('service')));
     //if (!trim($ps_value)) {
     //$this->postError(1970, _t('Entry was blank.'), 'InformationServiceAttributeValue->parseValue()');
     //	return false;
     //}
     if (trim($ps_value)) {
         $va_tmp = explode('|', $ps_value);
         $va_info = array();
         if (sizeof($va_tmp) == 3) {
             /// value is already in desired format (from autocomplete lookup)
             // get extra indexing info for this uri from plugin implementation
             $this->opo_plugin = InformationServiceManager::getInformationServiceInstance($vs_service);
             $vs_display_text = $this->opo_plugin->getDisplayValueFromLookupText($va_tmp[0]);
             $va_info['indexing_info'] = $this->opo_plugin->getDataForSearchIndexing($pa_element_info['settings'], $va_tmp[2]);
             $va_info['extra_info'] = $this->opo_plugin->getExtraInfo($pa_element_info['settings'], $va_tmp[2]);
             return array('value_longtext1' => $vs_display_text, 'value_longtext2' => $va_tmp[2], 'value_decimal1' => $va_tmp[1], 'value_blob' => caSerializeForDatabase($va_info));
         } elseif (sizeof($va_tmp) == 1 && (isURL($va_tmp[0], array('strict' => true)) || is_numeric($va_tmp[0]))) {
             // URI or ID -> try to look it up. we match hit when exactly 1 hit comes back
             // try lookup cache
             if (CompositeCache::contains($va_tmp[0], "InformationServiceLookup{$vs_service}")) {
                 return CompositeCache::fetch($va_tmp[0], "InformationServiceLookup{$vs_service}");
             }
             // try lookup
             $this->opo_plugin = InformationServiceManager::getInformationServiceInstance($vs_service);
             $va_ret = $this->opo_plugin->lookup($pa_element_info['settings'], $va_tmp[0]);
             // only match exact results. at some point we might want to try to get fancy
             // and pick one (or rather, have the plugin pick one) if there's more than one
             if (is_array($va_ret['results']) && sizeof($va_ret['results']) == 1) {
                 $va_hit = array_shift($va_ret['results']);
                 $va_info['indexing_info'] = $this->opo_plugin->getDataForSearchIndexing($pa_element_info['settings'], $va_hit['url']);
                 $va_info['extra_info'] = $this->opo_plugin->getExtraInfo($pa_element_info['settings'], $va_hit['url']);
                 $vs_display_text = $this->opo_plugin->getDisplayValueFromLookupText($va_hit['label']);
                 $va_return = array('value_longtext1' => $vs_display_text, 'value_longtext2' => $va_hit['url'], 'value_decimal1' => $va_hit['id'], 'value_blob' => caSerializeForDatabase($va_info));
             } else {
                 $this->postError(1970, _t('Value for InformationService lookup has to be an ID or URL that returns exactly 1 hit. We got more or no hits. Value was %1', $ps_value), 'ListAttributeValue->parseValue()');
                 return false;
             }
             CompositeCache::save($va_tmp[0], $va_return, "InformationServiceLookup{$vs_service}");
             return $va_return;
         } else {
             // don't save if value hasn't changed
             return array('_dont_save' => true);
         }
     }
     return array('value_longtext1' => '', 'value_longtext2' => '', 'value_decimal1' => null, 'value_blob' => null);
 }
コード例 #10
0
ファイル: system.php プロジェクト: austinvernsonger/scalar
 public function dashboard()
 {
     $this->load->model('book_model', 'books');
     $book_id = isset($_REQUEST['book_id']) && !empty($_REQUEST['book_id']) ? $_REQUEST['book_id'] : 0;
     $user_id = isset($_REQUEST['user_id']) && !empty($_REQUEST['user_id']) ? $_REQUEST['user_id'] : 0;
     $action = isset($_REQUEST['action']) && !empty($_REQUEST['action']) ? $_REQUEST['action'] : null;
     // There is more specific validation in each call below, but here run a general check on calls on books and users
     if (!$this->data['login']->is_logged_in) {
         $this->require_login(4);
     }
     if (!empty($book_id)) {
         $this->data['book'] = $this->books->get($book_id);
         $this->set_user_book_perms();
         $this->protect_book();
     }
     if (!$this->data['login_is_super'] && !empty($user_id)) {
         if ($this->data['login']->user_id != $user_id) {
             $this->kickout();
         }
     }
     $this->load->model('page_model', 'pages');
     $this->load->model('version_model', 'versions');
     $this->load->model('path_model', 'paths');
     $this->load->model('tag_model', 'tags');
     $this->load->model('annotation_model', 'annotations');
     $this->load->model('reply_model', 'replies');
     $this->data['zone'] = isset($_REQUEST['zone']) && !empty($_REQUEST['zone']) ? $_REQUEST['zone'] : 'user';
     $this->data['type'] = isset($_GET['type']) && !empty($_GET['type']) ? $_GET['type'] : null;
     $this->data['sq'] = isset($_GET['sq']) && !empty($_GET['sq']) ? trim($_GET['sq']) : null;
     $this->data['book_id'] = isset($_GET['book_id']) && !empty($_GET['book_id']) ? trim($_GET['book_id']) : 0;
     $this->data['delete'] = isset($_GET['delete']) && !empty($_GET['delete']) ? trim($_GET['delete']) : null;
     $this->data['saved'] = isset($_GET['action']) && 'saved' == $_GET['action'] ? true : false;
     $this->data['deleted'] = isset($_GET['action']) && 'deleted' == $_GET['action'] ? true : false;
     $this->data['duplicated'] = isset($_GET['action']) && 'duplicated' == $_GET['action'] ? true : false;
     // Actions
     try {
         switch ($action) {
             case 'do_save_style':
                 // Book Properties (method requires book_id)
                 $array = $_POST;
                 unset($array['action']);
                 unset($array['zone']);
                 $this->books->save($array);
                 $this->books->save_versions($array);
                 header('Location: ' . $this->base_url . '?book_id=' . $book_id . '&zone=' . $this->data['zone'] . '&action=book_style_saved');
                 exit;
             case 'do_save_user':
                 // My Account (method requires user_id & book_id)
                 $array = $_POST;
                 if ($this->users->email_exists_for_different_user($array['email'], $this->data['login']->user_id)) {
                     header('Location: ' . $this->base_url . '?book_id=' . $book_id . '&zone=' . $this->data['zone'] . '&error=email_exists');
                     exit;
                 }
                 if (empty($array['fullname'])) {
                     header('Location: ' . $this->base_url . '?book_id=' . $book_id . '&zone=' . $this->data['zone'] . '&error=fullname_required');
                     exit;
                 }
                 if (!empty($array['url'])) {
                     if (!isURL($array['url'])) {
                         $array['url'] = 'http://' . $array['url'];
                     }
                 }
                 if (!empty($array['password'])) {
                     if (!$this->users->get_by_email_and_password($array['email'], $array['old_password'])) {
                         header('Location: ' . $this->base_url . '?book_id=' . $book_id . '&zone=' . $this->data['zone'] . '&error=incorrect_password');
                         exit;
                     }
                     if ($array['password'] != $array['password_2']) {
                         header('Location: ' . $this->base_url . '?book_id=' . $book_id . '&zone=' . $this->data['zone'] . '&error=password_match');
                         exit;
                     }
                     $this->users->set_password($this->data['login']->user_id, $array['password']);
                 }
                 // Save profile
                 unset($array['password']);
                 unset($array['old_password']);
                 unset($array['password_2']);
                 $this->users->save($array);
                 $this->set_login_params();
                 header('Location: ' . $this->base_url . '?book_id=' . $book_id . '&zone=' . $this->data['zone'] . '&action=user_saved');
                 exit;
             case 'do_save_sharing':
                 $this->books->save(array('title' => $_POST['title'], 'book_id' => (int) $_POST['book_id']));
                 $array = $_POST;
                 unset($array['action']);
                 unset($array['zone']);
                 $this->books->save($array);
                 header('Location: ' . $this->base_url . '?book_id=' . $book_id . '&zone=' . $this->data['zone'] . '&action=book_sharing_saved#tabs-' . $this->data['zone']);
                 exit;
             case 'do_duplicate_book':
                 // My Account  TODO
                 $user_id = @(int) $_POST['user_id'];
                 $array = $_POST;
                 if (empty($user_id) && !$this->data['login_is_super']) {
                     $this->kickout();
                 }
                 $book_id = (int) $this->books->duplicate($array);
                 // Option to redirect to page of choice
                 if (isset($array['redirect']) && filter_var($array['redirect'], FILTER_VALIDATE_URL)) {
                     $url_has_query = parse_url($array['redirect'], PHP_URL_QUERY);
                     $redirect_url = $array['redirect'];
                     if (!isset($url_has_query)) {
                         if (substr($redirect_url, -1) != '?') {
                             $redirect_url .= '?';
                         }
                     } else {
                         $redirect_url .= '&';
                     }
                     $redirect_url .= 'duplicated=1';
                     // TODO: Change to action=duplicated
                     header('Location: ' . $redirect_url);
                     // Redirect to Dashboard > My Account
                 } else {
                     header('Location: ' . $this->base_url . '?book_id=' . $book_id . '&zone=' . $this->data['zone'] . '&action=duplicated');
                 }
                 exit;
             case 'do_add_book':
                 // Admin: All Books (requires title) & My Account (user_id & title)
                 $user_id = @(int) $_POST['user_id'];
                 $array = $_POST;
                 if (empty($user_id) && !$this->data['login_is_super']) {
                     $this->kickout();
                 }
                 $book_id = (int) $this->books->add($array);
                 // Option to redirect to page of choice
                 if (isset($array['redirect']) && filter_var($array['redirect'], FILTER_VALIDATE_URL)) {
                     $url_has_query = parse_url($array['redirect'], PHP_URL_QUERY);
                     $redirect_url = $array['redirect'];
                     if (!isset($url_has_query)) {
                         if (substr($redirect_url, -1) != '?') {
                             $redirect_url .= '?';
                         }
                     } else {
                         $redirect_url .= '&';
                     }
                     $redirect_url .= 'created=1';
                     header('Location: ' . $redirect_url);
                     // Redirect to Dashboard > My Account
                 } else {
                     header('Location: ' . $this->base_url . '?book_id=' . $book_id . '&zone=' . $this->data['zone'] . '&action=added');
                 }
                 exit;
             case 'do_add_user':
                 // Admin: All Users
                 if (!$this->data['login_is_super']) {
                     $this->kickout();
                 }
                 $array = $_POST;
                 $book_title = isset($array['book_title']) && !empty($array['book_title']) && 'title of first book (optional)' != $array['book_title'] ? trim($array['book_title']) : null;
                 $user_id = (int) $this->users->add($array);
                 if (!empty($user_id) && !empty($book_title)) {
                     $book_id = $this->books->add(array('title' => $book_title));
                     if (!empty($book_id)) {
                         $this->books->save_users($book_id, array($user_id), 'author');
                     }
                 }
                 header('Location: ' . $this->base_url . '?book_id=' . $book_id . '&zone=' . $this->data['zone'] . '&action=added');
                 exit;
             case 'do_delete':
                 // Admin: All Users & All Books
                 if (!$this->data['login_is_super']) {
                     $this->kickout();
                 }
                 $zone = $this->data['zone'];
                 $delete = (int) $_REQUEST['delete'];
                 $type = $_REQUEST['type'];
                 if (!is_object($this->{$type})) {
                     show_error('Invalid section');
                 }
                 if (!$this->{$type}->delete($delete)) {
                     show_error('There was a problem deleting. Please try again');
                 }
                 header('Location: ' . $this->base_url . '?action=deleted&zone=' . $zone . '#tabs-' . $zone);
                 exit;
             case "get_email_list":
                 // Admin: Tools
                 if (!$this->data['login_is_super']) {
                     $this->kickout();
                 }
                 $users = $this->users->get_all();
                 $this->data['email_list'] = array();
                 foreach ($users as $user) {
                     if (empty($user->email)) {
                         continue;
                     }
                     $this->data['email_list'][] = trim($user->email);
                 }
                 unset($user);
                 break;
             case "recreate_book_folders":
                 // Admin: Tools
                 if (!$this->data['login_is_super']) {
                     $this->kickout();
                 }
                 $books = $this->books->get_all();
                 $this->data['book_list'] = array();
                 foreach ($books as $book) {
                     $slug = $book->slug;
                     $msg = $slug . ' ... ';
                     if ($this->books->slug_exists($slug)) {
                         $msg .= 'already exists';
                     } else {
                         try {
                             $this->books->create_directory_from_slug($slug);
                             $msg .= 'RECREATED';
                         } catch (Exception $e) {
                             $msg .= 'ERROR attempting to recreate: ' . $e->getMessage();
                         }
                     }
                     $this->data['book_list'][] = $msg;
                 }
                 unset($books);
                 break;
             case 'acls_join_book':
                 // @Lucas - added function to add a user as a "reader" to a book, as well as email the author
                 if (!$this->data['login']->is_logged_in) {
                     $this->kickout();
                 }
                 $this->load->model('book_model', 'books');
                 $this->load->library('SendMail', 'sendmail');
                 $book_id = @(int) $_REQUEST['book_to_join'];
                 $this->data['book'] = $this->books->get($book_id);
                 $list_in_index = 0;
                 $this->data['content'] = $this->users->save_books($this->data['login']->user_id, array($this->data['book']->book_id), 'reader', $list_in_index);
                 //Send email to current authors. If the current user opted to request to become an author, send that email instead.
                 $this->sendmail->acls_join_book($this->data['login'], $this->data['book'], (int) $_REQUEST['request_author'], @$_REQUEST['author_reason']);
                 if (isset($_POST['redirect']) && filter_var($_POST['redirect'], FILTER_VALIDATE_URL)) {
                     $url_has_query = parse_url($_POST['redirect'], PHP_URL_QUERY);
                     $redirect_url = $_POST['redirect'];
                     if (!isset($url_has_query)) {
                         if (substr($redirect_url, -1) != '?') {
                             $redirect_url .= '?';
                         }
                     } else {
                         $redirect_url .= '&';
                     }
                     $redirect_url .= 'joined=1';
                     header('Location: ' . $redirect_url);
                 } else {
                     header('Location: ' . base_url() . '?joined=1');
                 }
                 break;
             case 'acls_elevate_user':
                 if (!$this->data['login']->is_logged_in) {
                     $this->kickout();
                 }
                 $this->load->model('book_model', 'books');
                 $this->load->library('SendMail', 'sendmail');
                 $this->data['book'] = $this->books->get($book_id);
                 $user_is_reader = false;
                 $selected_user = null;
                 foreach ($this->data['book']->users as $user) {
                     if ($user->user_id == $user_id) {
                         $selected_user = $user;
                         $user_is_reader = true;
                         break;
                     }
                 }
                 if ($user_is_reader) {
                     $this->data['content'] = $this->users->save(array('id' => $user_id, 'book_id' => $book_id, 'relationship' => 'author', 'list_in_index' => 1));
                     $this->sendmail->acls_elevate_user($selected_user, $this->data['book']);
                     header('Location: ' . base_url() . '?action=elevate&user_id=' . $user_id . '&book_id=' . $book_id . '&elevated=true');
                 } else {
                     header('Location: ' . base_url() . '?action=elevate&user_id=' . $user_id . '&book_id=' . $book_id . '&elevated=error&error=invalid_user');
                 }
                 break;
         }
     } catch (Exception $e) {
         show_error($e->getMessage());
     }
     // Books and current book
     $this->data['my_books'] = $this->books->get_all($this->data['login']->user_id, false);
     $this->data['book'] = $book_id ? $this->books->get($book_id) : array();
     $this->data['title'] = !empty($this->data['book']) ? $this->data['book']->title . ' Dashboard' : $this->config->item('install_name') . ': Dashboard';
     $this->data['cover_title'] = 'Dashboard';
     // Get general data for each zone; this is useful for displaying red dots for "not live" content in each tab, even though it's a performance hit
     $this->data['current_book_users'] = $this->data['current_book_images'] = $this->data['current_book_versions'] = array();
     $this->data['current_book_content'] = $book_id ? $this->pages->get_all($book_id, 'composite', null, false) : array();
     $this->data['current_book_files'] = $book_id ? $this->pages->get_all($book_id, 'media', null, false) : array();
     $this->data['current_book_replies'] = $book_id ? $this->replies->get_all($book_id, null, null, false) : array();
     // Get hidden comments to make this clear in the UI
     $this->data['pages_not_live'] = $this->count_not_live($this->data['current_book_content']);
     $this->data['media_not_live'] = $this->count_not_live($this->data['current_book_files']);
     $this->data['replies_not_live'] = $this->count_not_live($this->data['current_book_replies']);
     // Get specific data for each zone (no case for pages or media, since these are handled via the API)
     switch ($this->data['zone']) {
         case '':
         case 'user':
             $this->data['duplicatable_books'] = $this->books->get_duplicatable();
             break;
         case 'style':
             $this->data['current_book_images'] = $book_id ? $this->books->get_images($book_id) : array();
             $this->data['current_book_versions'] = $this->books->get_book_versions($book_id);
             $this->data['predefined_css'] = false;
             $this->data['interfaces'] = array();
             $melons = $this->melon_paths();
             foreach ($melons as $melon_path) {
                 if (!file_exists($melon_path . 'config.php')) {
                     continue;
                 }
                 $this->load_melon_config(basename($melon_path));
                 if (!empty($this->data['book']) && basename($melon_path) == $this->data['book']->template) {
                     $this->data['predefined_css'] = $this->config->item('predefined_css');
                 }
                 $this->data['interfaces'][] = array('meta' => $this->config->item('melon_meta'), 'stylesheets' => $this->config->item('stylesheets'));
             }
             usort($this->data['interfaces'], "sort_interfaces");
             break;
         case 'users':
             $this->data['current_book_users'] = $book_id ? $this->users->get_book_users($book_id) : array();
             break;
         case 'publish':
             // Do Nothing.  Nothing needs to be done.
             break;
             // Page-types follow, purposely at the bottom of the switch so that they fall into 'default'
         // Page-types follow, purposely at the bottom of the switch so that they fall into 'default'
         default:
             if (!empty($this->data['book'])) {
                 $this->data['book']->has_paywall = $this->books->has_paywall($this->data['book']);
             }
     }
     if ($this->data['login_is_super']) {
         $this->data['total'] = isset($_REQUEST['total']) && is_numeric($_REQUEST['total']) && $_REQUEST['total'] > 0 ? $_REQUEST['total'] : 20;
         $this->data['start'] = isset($_REQUEST['start']) && is_numeric($_REQUEST['start']) && $_REQUEST['start'] > 0 ? $_REQUEST['start'] : 0;
         $query = isset($_REQUEST['sq']) ? $_REQUEST['sq'] : null;
         switch ($this->data['zone']) {
             case 'all-users':
                 if ($this->data['login_is_super']) {
                     if (isset($query)) {
                         $this->data['users'] = $this->users->search($query);
                     } else {
                         $this->data['users'] = $this->users->get_all(0, false, 'fullname', 'asc', $this->data['total'], $this->data['start']);
                     }
                 } else {
                     $this->data['users'] = array();
                 }
                 for ($j = 0; $j < count($this->data['users']); $j++) {
                     $this->data['users'][$j]->books = $this->books->get_all($this->data['users'][$j]->user_id);
                 }
                 break;
             case 'all-books':
                 if ($this->data['login_is_super']) {
                     if (isset($query)) {
                         $this->data['books'] = $this->books->search($query);
                     } else {
                         $this->data['books'] = $this->books->get_all(0, false, 'title', 'asc', $this->data['total'], $this->data['start']);
                     }
                 } else {
                     $this->data['books'] = array();
                 }
                 $this->data['users'] = $this->data['login_is_super'] ? $this->users->get_all() : array();
                 break;
         }
     }
     // Load Dashboard plugins
     $this->config->load('plugins');
     $plugins = $this->config->item('plugins');
     $this->data['plugins'] = array();
     if (isset($plugins['dashboard'])) {
         foreach ($plugins['dashboard'] as $value) {
             $this->load->plugin($value);
             $cvalue = ucwords($value);
             $this->data['plugins'][$value] = new $cvalue($this->data);
         }
     }
     // Load dashboard
     $this->template->set_template('admin');
     $this->template->write_view('cover', 'modules/cover/dashboard_cover', $this->data);
     $this->template->write_view('content', 'modules/dashboard/tabs', $this->data);
     $this->template->render();
 }
コード例 #11
0
ファイル: BaseModel.php プロジェクト: samrahman/providence
 /**
  * Perform media processing for the given field if something has been uploaded
  *
  * @access private
  * @param string $ps_field field name
  * @param array options
  * 
  * Supported options:
  * 		delete_old_media = set to zero to prevent that old media files are deleted; defaults to 1
  *		these_versions_only = if set to an array of valid version names, then only the specified versions are updated with the currently updated file; ignored if no media already exists
  *		dont_allow_duplicate_media = if set to true, and the model as a field named "md5" then media will be rejected if a row already exists with the same MD5 signature
  */
 public function _processMedia($ps_field, $pa_options = null)
 {
     global $AUTH_CURRENT_USER_ID;
     if (!is_array($pa_options)) {
         $pa_options = array();
     }
     if (!isset($pa_options['delete_old_media'])) {
         $pa_options['delete_old_media'] = true;
     }
     if (!isset($pa_options['these_versions_only'])) {
         $pa_options['these_versions_only'] = null;
     }
     $vs_sql = "";
     $vn_max_execution_time = ini_get('max_execution_time');
     set_time_limit(7200);
     $o_tq = new TaskQueue();
     $o_media_proc_settings = new MediaProcessingSettings($this, $ps_field);
     # only set file if something was uploaded
     # (ie. don't nuke an existing file because none
     #      was uploaded)
     $va_field_info = $this->getFieldInfo($ps_field);
     if (isset($this->_FILES_CLEAR[$ps_field]) && $this->_FILES_CLEAR[$ps_field]) {
         //
         // Clear files
         //
         $va_versions = $this->getMediaVersions($ps_field);
         #--- delete files
         foreach ($va_versions as $v) {
             $this->_removeMedia($ps_field, $v);
         }
         $this->_removeMedia($ps_field, '_undo_');
         $this->_FILES[$ps_field] = null;
         $this->_FIELD_VALUES[$ps_field] = null;
         $vs_sql = "{$ps_field} = " . $this->quote(caSerializeForDatabase($this->_FILES[$ps_field], true)) . ",";
     } else {
         // Don't try to process files when no file is actually set
         if (isset($this->_SET_FILES[$ps_field]['tmp_name'])) {
             $o_tq = new TaskQueue();
             $o_media_proc_settings = new MediaProcessingSettings($this, $ps_field);
             //
             // Process incoming files
             //
             $m = new Media();
             $va_media_objects = array();
             // is it a URL?
             $vs_url_fetched_from = null;
             $vn_url_fetched_on = null;
             $vb_allow_fetching_of_urls = (bool) $this->_CONFIG->get('allow_fetching_of_media_from_remote_urls');
             $vb_is_fetched_file = false;
             if ($vb_allow_fetching_of_urls && (bool) ini_get('allow_url_fopen') && isURL($vs_url = html_entity_decode($this->_SET_FILES[$ps_field]['tmp_name']))) {
                 $vs_tmp_file = tempnam(__CA_APP_DIR__ . '/tmp', 'caUrlCopy');
                 $r_incoming_fp = fopen($vs_url, 'r');
                 if (!$r_incoming_fp) {
                     $this->postError(1600, _t('Cannot open remote URL [%1] to fetch media', $vs_url), "BaseModel->_processMedia()", $this->tableName() . '.' . $ps_field);
                     set_time_limit($vn_max_execution_time);
                     return false;
                 }
                 $r_outgoing_fp = fopen($vs_tmp_file, 'w');
                 if (!$r_outgoing_fp) {
                     $this->postError(1600, _t('Cannot open file for media fetched from URL [%1]', $vs_url), "BaseModel->_processMedia()", $this->tableName() . '.' . $ps_field);
                     set_time_limit($vn_max_execution_time);
                     return false;
                 }
                 while (($vs_content = fgets($r_incoming_fp, 4096)) !== false) {
                     fwrite($r_outgoing_fp, $vs_content);
                 }
                 fclose($r_incoming_fp);
                 fclose($r_outgoing_fp);
                 $vs_url_fetched_from = $vs_url;
                 $vn_url_fetched_on = time();
                 $this->_SET_FILES[$ps_field]['tmp_name'] = $vs_tmp_file;
                 $vb_is_fetched_file = true;
             }
             // is it server-side stored user media?
             if (preg_match("!^userMedia[\\d]+/!", $this->_SET_FILES[$ps_field]['tmp_name'])) {
                 // use configured directory to dump media with fallback to standard tmp directory
                 if (!is_writeable($vs_tmp_directory = $this->getAppConfig()->get('ajax_media_upload_tmp_directory'))) {
                     $vs_tmp_directory = caGetTempDirPath();
                 }
                 $this->_SET_FILES[$ps_field]['tmp_name'] = "{$vs_tmp_directory}/" . $this->_SET_FILES[$ps_field]['tmp_name'];
                 // read metadata
                 if (file_exists("{$vs_tmp_directory}/" . $this->_SET_FILES[$ps_field]['tmp_name'] . "_metadata")) {
                     if (is_array($va_tmp_metadata = json_decode(file_get_contents("{$vs_tmp_directory}/" . $this->_SET_FILES[$ps_field]['tmp_name'] . "_metadata")))) {
                         $this->_SET_FILES[$ps_field]['original_filename'] = $va_tmp_metadata['original_filename'];
                     }
                 }
             }
             if (isset($this->_SET_FILES[$ps_field]['tmp_name']) && file_exists($this->_SET_FILES[$ps_field]['tmp_name'])) {
                 if (!isset($pa_options['dont_allow_duplicate_media'])) {
                     $pa_options['dont_allow_duplicate_media'] = (bool) $this->getAppConfig()->get('dont_allow_duplicate_media');
                 }
                 if (isset($pa_options['dont_allow_duplicate_media']) && $pa_options['dont_allow_duplicate_media']) {
                     if ($this->hasField('md5')) {
                         $qr_dupe_chk = $this->getDb()->query("\n\t\t\t\t\t\t\t\tSELECT " . $this->primaryKey() . " FROM " . $this->tableName() . " WHERE md5 = ? " . ($this->hasField('deleted') ? ' AND deleted = 0' : '') . "\n\t\t\t\t\t\t\t", (string) md5_file($this->_SET_FILES[$ps_field]['tmp_name']));
                         if ($qr_dupe_chk->nextRow()) {
                             $this->postError(1600, _t("Media already exists in database"), "BaseModel->_processMedia()", $this->tableName() . '.' . $ps_field);
                             return false;
                         }
                     }
                 }
                 // allow adding zip and (gzipped) tape archives
                 $vb_is_archive = false;
                 $vs_original_filename = $this->_SET_FILES[$ps_field]['original_filename'];
                 $vs_original_tmpname = $this->_SET_FILES[$ps_field]['tmp_name'];
                 $va_matches = array();
                 if (preg_match("/(\\.zip|\\.tar\\.gz|\\.tgz)\$/", $vs_original_filename, $va_matches)) {
                     $vs_archive_extension = $va_matches[1];
                     // add file extension to temporary file if necessary; otherwise phar barfs when handling the archive
                     $va_tmp = array();
                     preg_match("/[.]*\\.([a-zA-Z0-9]+)\$/", $vs_original_tmpname, $va_tmp);
                     if (!isset($va_tmp[1])) {
                         @rename($this->_SET_FILES[$ps_field]['tmp_name'], $this->_SET_FILES[$ps_field]['tmp_name'] . $vs_archive_extension);
                         $this->_SET_FILES[$ps_field]['tmp_name'] = $this->_SET_FILES[$ps_field]['tmp_name'] . $vs_archive_extension;
                     }
                     if (caIsArchive($this->_SET_FILES[$ps_field]['tmp_name'])) {
                         $va_archive_files = caGetDirectoryContentsAsList('phar://' . $this->_SET_FILES[$ps_field]['tmp_name']);
                         if (sizeof($va_archive_files) > 0) {
                             // get first file we encounter in the archive and use it to generate them previews
                             $vb_is_archive = true;
                             $vs_archive = $this->_SET_FILES[$ps_field]['tmp_name'];
                             $va_tmp = array();
                             // copy primary file from the archive to temporary file (with extension so that *Magick can identify properly)
                             // this is basically a fallback. if the code below fails, we still have a 'fake' original
                             preg_match("/[.]*\\.([a-zA-Z0-9]+)\$/", $va_archive_files[0], $va_tmp);
                             $vs_primary_file_tmp = tempnam(caGetTempDirPath(), "caArchivePrimary");
                             @unlink($vs_primary_file_tmp);
                             $vs_primary_file_tmp = $vs_primary_file_tmp . "." . $va_tmp[1];
                             if (!@copy($va_archive_files[0], $vs_primary_file_tmp)) {
                                 $this->postError(1600, _t("Couldn't extract first file from archive. There is probably a invalid character in a directory or file name inside the archive"), "BaseModel->_processMedia()", $this->tableName() . '.' . $ps_field);
                                 set_time_limit($vn_max_execution_time);
                                 if ($vb_is_fetched_file) {
                                     @unlink($vs_tmp_file);
                                 }
                                 if ($vb_is_archive) {
                                     @unlink($vs_archive);
                                     @unlink($vs_primary_file_tmp);
                                 }
                                 return false;
                             }
                             $this->_SET_FILES[$ps_field]['tmp_name'] = $vs_primary_file_tmp;
                             // prepare to join archive contents to form a better downloadable "original" than the zip/tgz archive (e.g. a multi-page tiff)
                             // to do that, we have to 'extract' the archive so that command-line utilities like *Magick can operate
                             @caRemoveDirectory(caGetTempDirPath() . '/caArchiveExtract');
                             // remove left-overs, just to be sure we don't include other files in the tiff
                             $va_archive_tmp_files = array();
                             @mkdir(caGetTempDirPath() . '/caArchiveExtract');
                             foreach ($va_archive_files as $vs_archive_file) {
                                 $vs_basename = basename($vs_archive_file);
                                 $vs_tmp_file_name = caGetTempDirPath() . '/caArchiveExtract/' . str_replace(" ", "_", $vs_basename);
                                 $va_archive_tmp_files[] = $vs_tmp_file_name;
                                 @copy($vs_archive_file, $vs_tmp_file_name);
                             }
                         }
                     }
                     if (!$vb_is_archive) {
                         // something went wrong (i.e. no valid or empty archive) -> restore previous state
                         @rename($this->_SET_FILES[$ps_field]['tmp_name'] . $vs_archive_extension, $vs_original_tmpname);
                         $this->_SET_FILES[$ps_field]['tmp_name'] = $vs_original_tmpname;
                     }
                 }
                 // ImageMagick partly relies on file extensions to properly identify images (RAW images in particular)
                 // therefore we rename the temporary file here (using the extension of the original filename, if any)
                 $va_matches = array();
                 $vb_renamed_tmpfile = false;
                 preg_match("/[.]*\\.([a-zA-Z0-9]+)\$/", $this->_SET_FILES[$ps_field]['tmp_name'], $va_matches);
                 if (!isset($va_matches[1])) {
                     // file has no extension, i.e. is probably PHP upload tmp file
                     $va_matches = array();
                     preg_match("/[.]*\\.([a-zA-Z0-9]+)\$/", $this->_SET_FILES[$ps_field]['original_filename'], $va_matches);
                     if (strlen($va_matches[1]) > 0) {
                         $va_parts = explode("/", $this->_SET_FILES[$ps_field]['tmp_name']);
                         $vs_new_filename = sys_get_temp_dir() . "/" . $va_parts[sizeof($va_parts) - 1] . "." . $va_matches[1];
                         if (!move_uploaded_file($this->_SET_FILES[$ps_field]['tmp_name'], $vs_new_filename)) {
                             rename($this->_SET_FILES[$ps_field]['tmp_name'], $vs_new_filename);
                         }
                         $this->_SET_FILES[$ps_field]['tmp_name'] = $vs_new_filename;
                         $vb_renamed_tmpfile = true;
                     }
                 }
                 $input_mimetype = $m->divineFileFormat($this->_SET_FILES[$ps_field]['tmp_name']);
                 if (!($input_type = $o_media_proc_settings->canAccept($input_mimetype))) {
                     # error - filetype not accepted by this field
                     $this->postError(1600, $input_mimetype ? _t("File type %1 not accepted by %2", $input_mimetype, $ps_field) : _t("Unknown file type not accepted by %1", $ps_field), "BaseModel->_processMedia()", $this->tableName() . '.' . $ps_field);
                     set_time_limit($vn_max_execution_time);
                     if ($vb_is_fetched_file) {
                         @unlink($vs_tmp_file);
                     }
                     if ($vb_is_archive) {
                         @unlink($vs_archive);
                         @unlink($vs_primary_file_tmp);
                     }
                     return false;
                 }
                 # ok process file...
                 if (!$m->read($this->_SET_FILES[$ps_field]['tmp_name'])) {
                     $this->errors = array_merge($this->errors, $m->errors());
                     // copy into model plugin errors
                     set_time_limit($vn_max_execution_time);
                     if ($vb_is_fetched_file) {
                         @unlink($vs_tmp_file);
                     }
                     if ($vb_is_archive) {
                         @unlink($vs_archive);
                         @unlink($vs_primary_file_tmp);
                     }
                     return false;
                 }
                 // if necessary, join archive contents to form a better downloadable "original" than the zip/tgz archive (e.g. a multi-page tiff)
                 // by this point, a backend plugin was picked using the first file of the archive. this backend is also used to prepare the new original.
                 if ($vb_is_archive && sizeof($va_archive_tmp_files) > 0) {
                     if ($vs_archive_original = $m->joinArchiveContents($va_archive_tmp_files)) {
                         // mangle filename, so that the uploaded archive.zip becomes archive.tif or archive.gif or whatever extension the Media plugin prefers
                         $va_new_original_pathinfo = pathinfo($vs_archive_original);
                         $va_archive_pathinfo = pathinfo($this->_SET_FILES[$ps_field]['original_filename']);
                         $this->_SET_FILES[$ps_field]['original_filename'] = $va_archive_pathinfo['filename'] . "." . $va_new_original_pathinfo['extension'];
                         // this is now our original, disregard the uploaded archive
                         $this->_SET_FILES[$ps_field]['tmp_name'] = $vs_archive_original;
                         // re-run mimetype detection and read on the new original
                         $m->reset();
                         $input_mimetype = $m->divineFileFormat($vs_archive_original);
                         $input_type = $o_media_proc_settings->canAccept($input_mimetype);
                         $m->read($vs_archive_original);
                     }
                     @caRemoveDirectory(caGetTempDirPath() . '/caArchiveExtract');
                 }
                 $va_media_objects['_original'] = $m;
                 // preserve center setting from any existing media
                 $va_center = null;
                 if (is_array($va_tmp = $this->getMediaInfo($ps_field))) {
                     $va_center = caGetOption('_CENTER', $va_tmp, array());
                 }
                 $media_desc = array("ORIGINAL_FILENAME" => $this->_SET_FILES[$ps_field]['original_filename'], "_CENTER" => $va_center, "_SCALE" => caGetOption('_SCALE', $va_tmp, array()), "_SCALE_UNITS" => caGetOption('_SCALE_UNITS', $va_tmp, array()), "INPUT" => array("MIMETYPE" => $m->get("mimetype"), "WIDTH" => $m->get("width"), "HEIGHT" => $m->get("height"), "MD5" => md5_file($this->_SET_FILES[$ps_field]['tmp_name']), "FILESIZE" => filesize($this->_SET_FILES[$ps_field]['tmp_name']), "FETCHED_FROM" => $vs_url_fetched_from, "FETCHED_ON" => $vn_url_fetched_on));
                 if (isset($this->_SET_FILES[$ps_field]['options']['TRANSFORMATION_HISTORY']) && is_array($this->_SET_FILES[$ps_field]['options']['TRANSFORMATION_HISTORY'])) {
                     $media_desc['TRANSFORMATION_HISTORY'] = $this->_SET_FILES[$ps_field]['options']['TRANSFORMATION_HISTORY'];
                 }
                 #
                 # Extract metadata from file
                 #
                 $media_metadata = $m->getExtractedMetadata();
                 # get versions to create
                 $va_versions = $this->getMediaVersions($ps_field, $input_mimetype);
                 $error = 0;
                 # don't process files that are not going to be processed or converted
                 # we don't want to waste time opening file we're not going to do anything with
                 # also, we don't want to recompress JPEGs...
                 $media_type = $o_media_proc_settings->canAccept($input_mimetype);
                 $version_info = $o_media_proc_settings->getMediaTypeVersions($media_type);
                 $va_default_queue_settings = $o_media_proc_settings->getMediaTypeQueueSettings($media_type);
                 if (!($va_media_write_options = $this->_FILES[$ps_field]['options'])) {
                     $va_media_write_options = $this->_SET_FILES[$ps_field]['options'];
                 }
                 # Is an "undo" version set in options?
                 if (isset($this->_SET_FILES[$ps_field]['options']['undo']) && file_exists($this->_SET_FILES[$ps_field]['options']['undo'])) {
                     if ($volume = $version_info['original']['VOLUME']) {
                         $vi = $this->_MEDIA_VOLUMES->getVolumeInformation($volume);
                         if ($vi["absolutePath"] && strlen($dirhash = $this->_getDirectoryHash($vi["absolutePath"], $this->getPrimaryKey()))) {
                             $magic = rand(0, 99999);
                             $vs_filename = $this->_genMediaName($ps_field) . "_undo_";
                             $filepath = $vi["absolutePath"] . "/" . $dirhash . "/" . $magic . "_" . $vs_filename;
                             if (copy($this->_SET_FILES[$ps_field]['options']['undo'], $filepath)) {
                                 $media_desc['_undo_'] = array("VOLUME" => $volume, "FILENAME" => $vs_filename, "HASH" => $dirhash, "MAGIC" => $magic, "MD5" => md5_file($filepath));
                             }
                         }
                     }
                 }
                 $va_process_these_versions_only = array();
                 if (isset($pa_options['these_versions_only']) && is_array($pa_options['these_versions_only']) && sizeof($pa_options['these_versions_only'])) {
                     $va_tmp = $this->_FIELD_VALUES[$ps_field];
                     foreach ($pa_options['these_versions_only'] as $vs_this_version_only) {
                         if (in_array($vs_this_version_only, $va_versions)) {
                             if (is_array($this->_FIELD_VALUES[$ps_field])) {
                                 $va_process_these_versions_only[] = $vs_this_version_only;
                             }
                         }
                     }
                     // Copy metadata for version we're not processing
                     if (sizeof($va_process_these_versions_only)) {
                         foreach (array_keys($va_tmp) as $v) {
                             if (!in_array($v, $va_process_these_versions_only)) {
                                 $media_desc[$v] = $va_tmp[$v];
                             }
                         }
                     }
                 }
                 $va_files_to_delete = array();
                 $va_queued_versions = array();
                 $queue_enabled = !sizeof($va_process_these_versions_only) && $this->getAppConfig()->get('queue_enabled') ? true : false;
                 $vs_path_to_queue_media = null;
                 foreach ($va_versions as $v) {
                     $vs_use_icon = null;
                     if (sizeof($va_process_these_versions_only) && !in_array($v, $va_process_these_versions_only)) {
                         // only processing certain versions... and this one isn't it so skip
                         continue;
                     }
                     $queue = $va_default_queue_settings['QUEUE'];
                     $queue_threshold = isset($version_info[$v]['QUEUE_WHEN_FILE_LARGER_THAN']) ? intval($version_info[$v]['QUEUE_WHEN_FILE_LARGER_THAN']) : (int) $va_default_queue_settings['QUEUE_WHEN_FILE_LARGER_THAN'];
                     $rule = isset($version_info[$v]['RULE']) ? $version_info[$v]['RULE'] : '';
                     $volume = isset($version_info[$v]['VOLUME']) ? $version_info[$v]['VOLUME'] : '';
                     $basis = isset($version_info[$v]['BASIS']) ? $version_info[$v]['BASIS'] : '';
                     if (isset($media_desc[$basis]) && isset($media_desc[$basis]['FILENAME'])) {
                         if (!isset($va_media_objects[$basis])) {
                             $o_media = new Media();
                             $basis_vi = $this->_MEDIA_VOLUMES->getVolumeInformation($media_desc[$basis]['VOLUME']);
                             if ($o_media->read($p = $basis_vi['absolutePath'] . "/" . $media_desc[$basis]['HASH'] . "/" . $media_desc[$basis]['MAGIC'] . "_" . $media_desc[$basis]['FILENAME'])) {
                                 $va_media_objects[$basis] = $o_media;
                             } else {
                                 $m = $va_media_objects['_original'];
                             }
                         } else {
                             $m = $va_media_objects[$basis];
                         }
                     } else {
                         $m = $va_media_objects['_original'];
                     }
                     $m->reset();
                     # get volume
                     $vi = $this->_MEDIA_VOLUMES->getVolumeInformation($volume);
                     if (!is_array($vi)) {
                         print "Invalid volume '{$volume}'<br>";
                         exit;
                     }
                     // Send to queue if it's too big to process here
                     if ($queue_enabled && $queue && $queue_threshold > 0 && $queue_threshold < (int) $media_desc["INPUT"]["FILESIZE"] && $va_default_queue_settings['QUEUE_USING_VERSION'] != $v) {
                         $va_queued_versions[$v] = array('VOLUME' => $volume);
                         $media_desc[$v]["QUEUED"] = $queue;
                         if ($version_info[$v]["QUEUED_MESSAGE"]) {
                             $media_desc[$v]["QUEUED_MESSAGE"] = $version_info[$v]["QUEUED_MESSAGE"];
                         } else {
                             $media_desc[$v]["QUEUED_MESSAGE"] = $va_default_queue_settings['QUEUED_MESSAGE'] ? $va_default_queue_settings['QUEUED_MESSAGE'] : _t("Media is being processed and will be available shortly.");
                         }
                         if ($pa_options['delete_old_media']) {
                             $va_files_to_delete[] = array('field' => $ps_field, 'version' => $v);
                         }
                         continue;
                     }
                     # get transformation rules
                     $rules = $o_media_proc_settings->getMediaTransformationRule($rule);
                     if (sizeof($rules) == 0) {
                         $output_mimetype = $input_mimetype;
                         $m->set("version", $v);
                         #
                         # don't process this media, just copy the file
                         #
                         $ext = $m->mimetype2extension($output_mimetype);
                         if (!$ext) {
                             $this->postError(1600, _t("File could not be copied for %1; can't convert mimetype '%2' to extension", $ps_field, $output_mimetype), "BaseModel->_processMedia()", $this->tableName() . '.' . $ps_field);
                             $m->cleanup();
                             set_time_limit($vn_max_execution_time);
                             if ($vb_is_fetched_file) {
                                 @unlink($vs_tmp_file);
                             }
                             if ($vb_is_archive) {
                                 @unlink($vs_archive);
                                 @unlink($vs_primary_file_tmp);
                                 @unlink($vs_archive_original);
                             }
                             return false;
                         }
                         if (($dirhash = $this->_getDirectoryHash($vi["absolutePath"], $this->getPrimaryKey())) === false) {
                             $this->postError(1600, _t("Could not create subdirectory for uploaded file in %1. Please ask your administrator to check the permissions of your media directory.", $vi["absolutePath"]), "BaseModel->_processMedia()", $this->tableName() . '.' . $ps_field);
                             set_time_limit($vn_max_execution_time);
                             if ($vb_is_fetched_file) {
                                 @unlink($vs_tmp_file);
                             }
                             if ($vb_is_archive) {
                                 @unlink($vs_archive);
                                 @unlink($vs_primary_file_tmp);
                                 @unlink($vs_archive_original);
                             }
                             return false;
                         }
                         if ((bool) $version_info[$v]["USE_EXTERNAL_URL_WHEN_AVAILABLE"]) {
                             $filepath = $this->_SET_FILES[$ps_field]['tmp_name'];
                             if ($pa_options['delete_old_media']) {
                                 $va_files_to_delete[] = array('field' => $ps_field, 'version' => $v);
                             }
                             $media_desc[$v] = array("VOLUME" => $volume, "MIMETYPE" => $output_mimetype, "WIDTH" => $m->get("width"), "HEIGHT" => $m->get("height"), "PROPERTIES" => $m->getProperties(), "EXTERNAL_URL" => $media_desc['INPUT']['FETCHED_FROM'], "FILENAME" => null, "HASH" => null, "MAGIC" => null, "EXTENSION" => $ext, "MD5" => md5_file($filepath));
                         } else {
                             $magic = rand(0, 99999);
                             $filepath = $vi["absolutePath"] . "/" . $dirhash . "/" . $magic . "_" . $this->_genMediaName($ps_field) . "_" . $v . "." . $ext;
                             if (!copy($this->_SET_FILES[$ps_field]['tmp_name'], $filepath)) {
                                 $this->postError(1600, _t("File could not be copied. Ask your administrator to check permissions and file space for %1", $vi["absolutePath"]), "BaseModel->_processMedia()", $this->tableName() . '.' . $ps_field);
                                 $m->cleanup();
                                 set_time_limit($vn_max_execution_time);
                                 if ($vb_is_fetched_file) {
                                     @unlink($vs_tmp_file);
                                 }
                                 if ($vb_is_archive) {
                                     @unlink($vs_archive);
                                     @unlink($vs_primary_file_tmp);
                                     @unlink($vs_archive_original);
                                 }
                                 return false;
                             }
                             if ($v === $va_default_queue_settings['QUEUE_USING_VERSION']) {
                                 $vs_path_to_queue_media = $filepath;
                             }
                             if ($pa_options['delete_old_media']) {
                                 $va_files_to_delete[] = array('field' => $ps_field, 'version' => $v, 'dont_delete_path' => $vi["absolutePath"] . "/" . $dirhash . "/" . $magic . "_" . $this->_genMediaName($ps_field) . "_" . $v, 'dont_delete_extension' => $ext);
                             }
                             if (is_array($vi["mirrors"]) && sizeof($vi["mirrors"]) > 0) {
                                 $vs_entity_key = join("/", array($this->tableName(), $ps_field, $this->getPrimaryKey(), $v));
                                 $vs_row_key = join("/", array($this->tableName(), $this->getPrimaryKey()));
                                 foreach ($vi["mirrors"] as $vs_mirror_code => $va_mirror_info) {
                                     $vs_mirror_method = $va_mirror_info["method"];
                                     $vs_queue = $vs_mirror_method . "mirror";
                                     if (!$o_tq->cancelPendingTasksForEntity($vs_entity_key)) {
                                         //$this->postError(560, _t("Could not cancel pending tasks: %1", $this->error),"BaseModel->_processMedia()");
                                         //$m->cleanup();
                                         //return false;
                                     }
                                     if ($o_tq->addTask($vs_queue, array("MIRROR" => $vs_mirror_code, "VOLUME" => $volume, "FIELD" => $ps_field, "TABLE" => $this->tableName(), "VERSION" => $v, "FILES" => array(array("FILE_PATH" => $filepath, "ABS_PATH" => $vi["absolutePath"], "HASH" => $dirhash, "FILENAME" => $magic . "_" . $this->_genMediaName($ps_field) . "_" . $v . "." . $ext)), "MIRROR_INFO" => $va_mirror_info, "PK" => $this->primaryKey(), "PK_VAL" => $this->getPrimaryKey()), array("priority" => 100, "entity_key" => $vs_entity_key, "row_key" => $vs_row_key, 'user_id' => $AUTH_CURRENT_USER_ID))) {
                                         continue;
                                     } else {
                                         $this->postError(100, _t("Couldn't queue mirror using '%1' for version '%2' (handler '%3')", $vs_mirror_method, $v, $queue), "BaseModel->_processMedia()");
                                     }
                                 }
                             }
                             $media_desc[$v] = array("VOLUME" => $volume, "MIMETYPE" => $output_mimetype, "WIDTH" => $m->get("width"), "HEIGHT" => $m->get("height"), "PROPERTIES" => $m->getProperties(), "FILENAME" => $this->_genMediaName($ps_field) . "_" . $v . "." . $ext, "HASH" => $dirhash, "MAGIC" => $magic, "EXTENSION" => $ext, "MD5" => md5_file($filepath));
                         }
                     } else {
                         $m->set("version", $v);
                         while (list($operation, $parameters) = each($rules)) {
                             if ($operation === 'SET') {
                                 foreach ($parameters as $pp => $pv) {
                                     if ($pp == 'format') {
                                         $output_mimetype = $pv;
                                     } else {
                                         $m->set($pp, $pv);
                                     }
                                 }
                             } else {
                                 if (is_array($this->_FIELD_VALUES[$ps_field]) && is_array($va_media_center = $this->getMediaCenter($ps_field))) {
                                     $parameters['_centerX'] = caGetOption('x', $va_media_center, 0.5);
                                     $parameters['_centerY'] = caGetOption('y', $va_media_center, 0.5);
                                     if ($parameters['_centerX'] < 0 || $parameters['_centerX'] > 1) {
                                         $parameters['_centerX'] = 0.5;
                                     }
                                     if ($parameters['_centerY'] < 0 || $parameters['_centerY'] > 1) {
                                         $parameters['_centerY'] = 0.5;
                                     }
                                 }
                                 if (!$m->transform($operation, $parameters)) {
                                     $error = 1;
                                     $error_msg = "Couldn't do transformation '{$operation}'";
                                     break 2;
                                 }
                             }
                         }
                         if (!$output_mimetype) {
                             $output_mimetype = $input_mimetype;
                         }
                         if (!($ext = $m->mimetype2extension($output_mimetype))) {
                             $this->postError(1600, _t("File could not be processed for %1; can't convert mimetype '%2' to extension", $ps_field, $output_mimetype), "BaseModel->_processMedia()", $this->tableName() . '.' . $ps_field);
                             $m->cleanup();
                             set_time_limit($vn_max_execution_time);
                             if ($vb_is_fetched_file) {
                                 @unlink($vs_tmp_file);
                             }
                             if ($vb_is_archive) {
                                 @unlink($vs_archive);
                                 @unlink($vs_primary_file_tmp);
                                 @unlink($vs_archive_original);
                             }
                             return false;
                         }
                         if (($dirhash = $this->_getDirectoryHash($vi["absolutePath"], $this->getPrimaryKey())) === false) {
                             $this->postError(1600, _t("Could not create subdirectory for uploaded file in %1. Please ask your administrator to check the permissions of your media directory.", $vi["absolutePath"]), "BaseModel->_processMedia()", $this->tableName() . '.' . $ps_field);
                             set_time_limit($vn_max_execution_time);
                             if ($vb_is_fetched_file) {
                                 @unlink($vs_tmp_file);
                             }
                             if ($vb_is_archive) {
                                 @unlink($vs_archive);
                                 @unlink($vs_primary_file_tmp);
                                 @unlink($vs_archive_original);
                             }
                             return false;
                         }
                         $magic = rand(0, 99999);
                         $filepath = $vi["absolutePath"] . "/" . $dirhash . "/" . $magic . "_" . $this->_genMediaName($ps_field) . "_" . $v;
                         if (!($vs_output_file = $m->write($filepath, $output_mimetype, $va_media_write_options))) {
                             $this->postError(1600, _t("Couldn't write file: %1", join("; ", $m->getErrors())), "BaseModel->_processMedia()", $this->tableName() . '.' . $ps_field);
                             $m->cleanup();
                             set_time_limit($vn_max_execution_time);
                             if ($vb_is_fetched_file) {
                                 @unlink($vs_tmp_file);
                             }
                             if ($vb_is_archive) {
                                 @unlink($vs_archive);
                                 @unlink($vs_primary_file_tmp);
                                 @unlink($vs_archive_original);
                             }
                             return false;
                             break;
                         } 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_output_file === __CA_MEDIA_3D_DEFAULT_ICON__) {
                                 $vs_use_icon = $vs_output_file;
                             }
                         }
                         if ($v === $va_default_queue_settings['QUEUE_USING_VERSION']) {
                             $vs_path_to_queue_media = $vs_output_file;
                             $vs_use_icon = __CA_MEDIA_QUEUED_ICON__;
                         }
                         if ($pa_options['delete_old_media'] && !$error) {
                             if ($vs_old_media_path = $this->getMediaPath($ps_field, $v)) {
                                 $va_files_to_delete[] = array('field' => $ps_field, 'version' => $v, 'dont_delete_path' => $filepath, 'dont_delete_extension' => $ext);
                             }
                         }
                         if (is_array($vi["mirrors"]) && sizeof($vi["mirrors"]) > 0) {
                             $vs_entity_key = join("/", array($this->tableName(), $ps_field, $this->getPrimaryKey(), $v));
                             $vs_row_key = join("/", array($this->tableName(), $this->getPrimaryKey()));
                             foreach ($vi["mirrors"] as $vs_mirror_code => $va_mirror_info) {
                                 $vs_mirror_method = $va_mirror_info["method"];
                                 $vs_queue = $vs_mirror_method . "mirror";
                                 if (!$o_tq->cancelPendingTasksForEntity($vs_entity_key)) {
                                     //$this->postError(560, _t("Could not cancel pending tasks: %1", $this->error),"BaseModel->_processMedia()");
                                     //$m->cleanup();
                                     //return false;
                                 }
                                 if ($o_tq->addTask($vs_queue, array("MIRROR" => $vs_mirror_code, "VOLUME" => $volume, "FIELD" => $ps_field, "TABLE" => $this->tableName(), "VERSION" => $v, "FILES" => array(array("FILE_PATH" => $filepath . "." . $ext, "ABS_PATH" => $vi["absolutePath"], "HASH" => $dirhash, "FILENAME" => $magic . "_" . $this->_genMediaName($ps_field) . "_" . $v . "." . $ext)), "MIRROR_INFO" => $va_mirror_info, "PK" => $this->primaryKey(), "PK_VAL" => $this->getPrimaryKey()), array("priority" => 100, "entity_key" => $vs_entity_key, "row_key" => $vs_row_key, 'user_id' => $AUTH_CURRENT_USER_ID))) {
                                     continue;
                                 } else {
                                     $this->postError(100, _t("Couldn't queue mirror using '%1' for version '%2' (handler '%3')", $vs_mirror_method, $v, $queue), "BaseModel->_processMedia()");
                                 }
                             }
                         }
                         if ($vs_use_icon) {
                             $media_desc[$v] = array("MIMETYPE" => $output_mimetype, "USE_ICON" => $vs_use_icon, "WIDTH" => $m->get("width"), "HEIGHT" => $m->get("height"));
                         } else {
                             $media_desc[$v] = array("VOLUME" => $volume, "MIMETYPE" => $output_mimetype, "WIDTH" => $m->get("width"), "HEIGHT" => $m->get("height"), "PROPERTIES" => $m->getProperties(), "FILENAME" => $this->_genMediaName($ps_field) . "_" . $v . "." . $ext, "HASH" => $dirhash, "MAGIC" => $magic, "EXTENSION" => $ext, "MD5" => md5_file($vi["absolutePath"] . "/" . $dirhash . "/" . $magic . "_" . $this->_genMediaName($ps_field) . "_" . $v . "." . $ext));
                         }
                         $m->reset();
                     }
                 }
                 if (sizeof($va_queued_versions)) {
                     $vs_entity_key = md5(join("/", array_merge(array($this->tableName(), $ps_field, $this->getPrimaryKey()), array_keys($va_queued_versions))));
                     $vs_row_key = join("/", array($this->tableName(), $this->getPrimaryKey()));
                     if (!$o_tq->cancelPendingTasksForEntity($vs_entity_key, $queue)) {
                         // TODO: log this
                     }
                     if (!($filename = $vs_path_to_queue_media)) {
                         // if we're not using a designated not-queued representation to generate the queued ones
                         // then copy the uploaded file to the tmp dir and use that
                         $filename = $o_tq->copyFileToQueueTmp($va_default_queue_settings['QUEUE'], $this->_SET_FILES[$ps_field]['tmp_name']);
                     }
                     if ($filename) {
                         if ($o_tq->addTask($va_default_queue_settings['QUEUE'], array("TABLE" => $this->tableName(), "FIELD" => $ps_field, "PK" => $this->primaryKey(), "PK_VAL" => $this->getPrimaryKey(), "INPUT_MIMETYPE" => $input_mimetype, "FILENAME" => $filename, "VERSIONS" => $va_queued_versions, "OPTIONS" => $va_media_write_options, "DONT_DELETE_OLD_MEDIA" => $filename == $vs_path_to_queue_media ? true : false), array("priority" => 100, "entity_key" => $vs_entity_key, "row_key" => $vs_row_key, 'user_id' => $AUTH_CURRENT_USER_ID))) {
                             if ($pa_options['delete_old_media']) {
                                 foreach ($va_queued_versions as $vs_version => $va_version_info) {
                                     $va_files_to_delete[] = array('field' => $ps_field, 'version' => $vs_version);
                                 }
                             }
                         } else {
                             $this->postError(100, _t("Couldn't queue processing for version '%1' using handler '%2'", !$v, $queue), "BaseModel->_processMedia()");
                         }
                     } else {
                         $this->errors = $o_tq->errors;
                     }
                 } else {
                     // 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)
                     if (!sizeof($va_process_these_versions_only) && ((bool) $this->_CONFIG->get('video_preview_generate_frames') || (bool) $this->_CONFIG->get('document_preview_generate_pages')) && method_exists($this, 'addFile')) {
                         if (method_exists($this, 'removeAllFiles')) {
                             $this->removeAllFiles();
                             // get rid of any previously existing frames (they might be hanging ar
                         }
                         $va_preview_frame_list = $m->writePreviews(array('width' => $m->get("width"), 'height' => $m->get("height"), 'minNumberOfFrames' => $this->_CONFIG->get('video_preview_min_number_of_frames'), 'maxNumberOfFrames' => $this->_CONFIG->get('video_preview_max_number_of_frames'), 'numberOfPages' => $this->_CONFIG->get('document_preview_max_number_of_pages'), 'frameInterval' => $this->_CONFIG->get('video_preview_interval_between_frames'), 'pageInterval' => $this->_CONFIG->get('document_preview_interval_between_pages'), 'startAtTime' => $this->_CONFIG->get('video_preview_start_at'), 'endAtTime' => $this->_CONFIG->get('video_preview_end_at'), 'startAtPage' => $this->_CONFIG->get('document_preview_start_page'), 'outputDirectory' => __CA_APP_DIR__ . '/tmp'));
                         if (is_array($va_preview_frame_list)) {
                             foreach ($va_preview_frame_list as $vn_time => $vs_frame) {
                                 $this->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 (!$error) {
                     #
                     # --- Clean up old media from versions that are not supported in the new media
                     #
                     if ($pa_options['delete_old_media']) {
                         foreach ($this->getMediaVersions($ps_field) as $old_version) {
                             if (!is_array($media_desc[$old_version])) {
                                 $this->_removeMedia($ps_field, $old_version);
                             }
                         }
                     }
                     foreach ($va_files_to_delete as $va_file_to_delete) {
                         $this->_removeMedia($va_file_to_delete['field'], $va_file_to_delete['version'], $va_file_to_delete['dont_delete_path'], $va_file_to_delete['dont_delete_extension']);
                     }
                     # Remove old _undo_ file if defined
                     if ($vs_undo_path = $this->getMediaPath($ps_field, '_undo_')) {
                         @unlink($vs_undo_path);
                     }
                     $this->_FILES[$ps_field] = $media_desc;
                     $this->_FIELD_VALUES[$ps_field] = $media_desc;
                     $vs_serialized_data = caSerializeForDatabase($this->_FILES[$ps_field], true);
                     $vs_sql = "{$ps_field} = " . $this->quote($vs_serialized_data) . ",";
                     if (($vs_metadata_field_name = $o_media_proc_settings->getMetadataFieldName()) && $this->hasField($vs_metadata_field_name)) {
                         $this->set($vs_metadata_field_name, $media_metadata);
                         $vs_sql .= " " . $vs_metadata_field_name . " = " . $this->quote(caSerializeForDatabase($media_metadata, true)) . ",";
                     }
                     if (($vs_content_field_name = $o_media_proc_settings->getMetadataContentName()) && $this->hasField($vs_content_field_name)) {
                         $this->_FIELD_VALUES[$vs_content_field_name] = $this->quote($m->getExtractedText());
                         $vs_sql .= " " . $vs_content_field_name . " = " . $this->_FIELD_VALUES[$vs_content_field_name] . ",";
                     }
                     if (is_array($va_locs = $m->getExtractedTextLocations())) {
                         MediaContentLocationIndexer::clear($this->tableNum(), $this->getPrimaryKey());
                         foreach ($va_locs as $vs_content => $va_loc_list) {
                             foreach ($va_loc_list as $va_loc) {
                                 MediaContentLocationIndexer::index($this->tableNum(), $this->getPrimaryKey(), $vs_content, $va_loc['p'], $va_loc['x1'], $va_loc['y1'], $va_loc['x2'], $va_loc['y2']);
                             }
                         }
                         MediaContentLocationIndexer::write();
                     }
                 } else {
                     # error - invalid media
                     $this->postError(1600, _t("File could not be processed for %1: %2", $ps_field, $error_msg), "BaseModel->_processMedia()");
                     #	    return false;
                 }
                 $m->cleanup();
                 if ($vb_renamed_tmpfile) {
                     @unlink($this->_SET_FILES[$ps_field]['tmp_name']);
                 }
             } elseif (is_array($this->_FIELD_VALUES[$ps_field])) {
                 // Just set field values in SQL (assume in-place update of media metadata) because no tmp_name is set
                 // [This generally should not happen]
                 $this->_FILES[$ps_field] = $this->_FIELD_VALUES[$ps_field];
                 $vs_sql = "{$ps_field} = " . $this->quote(caSerializeForDatabase($this->_FILES[$ps_field], true)) . ",";
             }
             $this->_SET_FILES[$ps_field] = null;
         } elseif (is_array($this->_FIELD_VALUES[$ps_field])) {
             // Just set field values in SQL (usually in-place update of media metadata)
             $this->_FILES[$ps_field] = $this->_FIELD_VALUES[$ps_field];
             $vs_sql = "{$ps_field} = " . $this->quote(caSerializeForDatabase($this->_FILES[$ps_field], true)) . ",";
         }
     }
     set_time_limit($vn_max_execution_time);
     if ($vb_is_fetched_file) {
         @unlink($vs_tmp_file);
     }
     if ($vb_is_archive) {
         @unlink($vs_archive);
         @unlink($vs_primary_file_tmp);
         @unlink($vs_archive_original);
     }
     return $vs_sql;
 }
コード例 #12
0
 /**
  * Returns true if the media field is set to a non-empty file
  **/
 public function mediaIsEmpty()
 {
     if (!($vs_media_path = $this->getMediaPath('media', 'original'))) {
         $vs_media_path = $this->get('media');
     }
     if ($vs_media_path) {
         if (file_exists($vs_media_path) && abs(filesize($vs_media_path)) > 0) {
             return false;
         }
     }
     // is it a URL?
     if ($this->_CONFIG->get('allow_fetching_of_media_from_remote_urls')) {
         if (isURL($vs_media_path)) {
             return false;
         }
     }
     return true;
 }
コード例 #13
0
ファイル: MY_url_helper.php プロジェクト: paulshannon/scalar
function confirm_base($uri)
{
    if (empty($uri)) {
        return $uri;
    }
    if (isURL($uri)) {
        return $uri;
    }
    return base_url() . $uri;
}
コード例 #14
0
ファイル: MY_Model.php プロジェクト: paulshannon/scalar
 public function foaf_homepage($value, $base_uri)
 {
     if (isURL($value)) {
         return $value;
     }
     return confirm_slash($base_uri) . 'users/' . $value;
 }
コード例 #15
0
ファイル: message_fields.php プロジェクト: Blu2z/implsk
     if ($fldNotNull[$i] && $fldValue[$i] == "" && !($action == 'change' && $fld[$i] == $AUTHORIZE_BY)) {
         $errCode = 1;
     }
     if ($fldNotNull[$i] && $fldFmt[$i] == "url" && ($fldValue[$i] == 'http://' || $fldValue[$i] == 'ftp://')) {
         $errCode = 1;
     }
     if ($fldFmt[$i] == "email" && $fldValue[$i] && !nc_preg_match("/^[a-z0-9\\._-]+@[a-z0-9\\._-]+\\.[a-z]{2,6}\$/i", $fldValue[$i])) {
         $errCode = 2;
     }
     if ($fldFmt[$i] == "phone" && $fldValue[$i] && !nc_preg_match("/^ (\\+?\\d-?)?  (((\\(\\d{3}\\))|(\\d{3})?)-?)?  \\d{3}-?\\d{2}-?\\d{2} \$/x", str_replace(array(" ", " \t"), '', $fldValue[$i]))) {
         $errCode = 2;
     }
     if ($fldType[$i] == 1 && $fldFmt[$i] == "url" && ($fldValue[$i] == 'http://' || $fldValue[$i] == 'ftp://')) {
         $fldValue[$i] = "";
     }
     if ($fldFmt[$i] == "url" && $fldValue[$i] && !isURL($fldValue[$i])) {
         $errCode = 2;
     }
     break;
     # int
 # int
 case NC_FIELDTYPE_INT:
     if ($fldNotNull[$i] && $fldValue[$i] == "") {
         $errCode = 1;
     }
     if ($fldValue[$i] != "" && $fldValue[$i] != strval(intval($fldValue[$i]))) {
         $errCode = 2;
     }
     break;
     # text
 # text
コード例 #16
0
ファイル: RDF_Store.php プロジェクト: paulshannon/scalar
 /** 
  * Save an array of fields and values for a single node by URN
  */
 public function save_by_urn($urn, $array = array(), $g = 'urn:scalar')
 {
     $conf = array('ns' => $this->ns);
     $resource = ARC2::getResource($conf);
     $resource->setURI($urn);
     foreach ($array as $field => $valueArray) {
         if (!isNS($field) && !isURL($field)) {
             continue;
         }
         $field = toURL($field, $this->ns);
         if (!is_array($valueArray)) {
             $valueArray = array($valueArray);
         }
         $insert_values = array();
         foreach ($valueArray as $value) {
             if (empty($value)) {
                 continue;
             }
             if (is_string($value)) {
                 if (substr($value, -1, 1) == '"') {
                     $value .= ' ';
                 }
                 // ARC bug fix
                 //$value = closeOpenTags($value);
             }
             if (is_array($value)) {
                 if (empty($value['value'])) {
                     continue;
                 }
                 $insert_values[] = $value;
             } else {
                 $insert_values[] = array('value' => $value, 'type' => isURL($value) || isNS($value, $this->ns) ? 'uri' : 'literal');
             }
         }
         if (!empty($insert_values)) {
             $resource->setProp($field, $insert_values);
         }
     }
     $this->store->insert($resource->index, $g);
     if ($errs = $this->store->getErrors()) {
         print_r($errs);
     }
     return true;
 }
コード例 #17
0
 /**
  * Fetches a literal property string value from given node
  * @param string $ps_base_node
  * @param string $ps_literal_propery EasyRdf property definition
  * @param string|null $ps_node_uri Optional related node URI to pull from
  * @param array $pa_options Available options are
  * 			limit -> limit number of processed related notes, defaults to 10
  * 			stripAfterLastComma -> strip everything after (and including) the last comma in the individual literal string
  * 				this is useful for gvp:parentString where the top-most category is usually not very useful
  * @return string|bool
  */
 static function getLiteralFromRDFNode($ps_base_node, $ps_literal_propery, $ps_node_uri = null, $pa_options = array())
 {
     if (!isURL($ps_base_node)) {
         return false;
     }
     if (!is_array($pa_options)) {
         $pa_options = array();
     }
     $vs_cache_key = md5($ps_base_node . $ps_literal_propery . $ps_node_uri . print_r($pa_options, true));
     if (CompositeCache::contains($vs_cache_key, 'GettyRDFLiterals')) {
         return CompositeCache::fetch($vs_cache_key, 'GettyRDFLiterals');
     }
     $pn_limit = (int) caGetOption('limit', $pa_options, 10);
     $pb_strip_after_last_comma = (bool) caGetOption('stripAfterLastComma', $pa_options, false);
     $pb_invert = (bool) caGetOption('invert', $pa_options, false);
     if (!($o_graph = self::getURIAsRDFGraph($ps_base_node))) {
         return false;
     }
     $va_pull_graphs = array();
     if (strlen($ps_node_uri) > 0) {
         $o_related_nodes = $o_graph->all($ps_base_node, $ps_node_uri);
         if (is_array($o_related_nodes)) {
             $vn_i = 0;
             foreach ($o_related_nodes as $o_related_node) {
                 $vs_pull_uri = (string) $o_related_node;
                 if (!($o_pull_graph = self::getURIAsRDFGraph($vs_pull_uri))) {
                     return false;
                 }
                 $va_pull_graphs[$vs_pull_uri] = $o_pull_graph;
                 if (++$vn_i >= $pn_limit) {
                     break;
                 }
             }
         }
     } else {
         $va_pull_graphs[$ps_base_node] = $o_graph;
     }
     $va_return = array();
     $vn_j = 0;
     foreach ($va_pull_graphs as $vs_uri => $o_g) {
         $va_literals = $o_g->all($vs_uri, $ps_literal_propery);
         foreach ($va_literals as $o_literal) {
             if ($o_literal instanceof EasyRdf_Literal) {
                 $vs_string_to_add = htmlentities(preg_replace('/[\\<\\>]/', '', $o_literal->getValue()));
             } else {
                 $vs_string_to_add = preg_replace('/[\\<\\>]/', '', (string) $o_literal);
             }
             if ($pb_strip_after_last_comma) {
                 $vn_last_comma_pos = strrpos($vs_string_to_add, ',');
                 $vs_string_to_add = substr($vs_string_to_add, 0, $vn_last_comma_pos - strlen($vs_string_to_add));
             }
             $va_tmp = explode(', ', $vs_string_to_add);
             if ($pb_invert && sizeof($va_tmp)) {
                 $vs_string_to_add = join(' &gt; ', array_reverse($va_tmp));
             }
             // make links click-able
             if (isURL($vs_string_to_add)) {
                 $vs_string_to_add = "<a href='{$vs_string_to_add}' target='_blank'>{$vs_string_to_add}</a>";
             }
             $va_return[] = $vs_string_to_add;
             if (++$vn_j >= $pn_limit) {
                 break;
             }
         }
     }
     $vs_return = join('; ', $va_return);
     CompositeCache::save($vs_cache_key, $vs_return, 'GettyRDFLiterals');
     return $vs_return;
 }
コード例 #18
0
ファイル: CLIUtils.php プロジェクト: idiscussforum/providence
 /**
  * @param Zend_Console_Getopt|null $po_opts
  * @return bool
  */
 public static function reload_ulan_records($po_opts = null)
 {
     require_once __CA_MODELS_DIR__ . '/ca_data_importers.php';
     if (!($vs_mapping = $po_opts->getOption('mapping'))) {
         CLIUtils::addError("\t\tNo mapping found. Please use the -m parameter to specify a ULAN mapping.");
         return false;
     }
     if (!ca_data_importers::mappingExists($vs_mapping)) {
         CLIUtils::addError("\t\tMapping {$vs_mapping} does not exist");
         return false;
     }
     $vs_log_dir = $po_opts->getOption('log');
     $vn_log_level = CLIUtils::getLogLevel($po_opts);
     $o_db = new Db();
     $qr_items = $o_db->query("\n\t\t\t\tSELECT DISTINCT source FROM ca_data_import_events WHERE type_code = 'ULAN'\n\t\t\t");
     $va_sources = array();
     while ($qr_items->nextRow()) {
         $vs_source = $qr_items->get('source');
         if (!isURL($vs_source)) {
             continue;
         }
         if (!preg_match("/http\\:\\/\\/vocab\\.getty\\.edu\\/ulan\\//", $vs_source)) {
             continue;
         }
         $va_sources[] = $vs_source;
     }
     ca_data_importers::importDataFromSource(join(',', $va_sources), $vs_mapping, array('format' => 'ULAN', 'showCLIProgressBar' => true, 'logDirectory' => $vs_log_dir, 'logLevel' => $vn_log_level));
     return true;
 }
コード例 #19
0
{
    return filter_var($array, FILTER_VALIDATE_FLOAT, FILTER_REQUIRE_ARRAY);
}
$array = array(1.2, "1.7", "", "-12345.678", "1,234.2222", "abcd4.2efgh", array());
echo '<br/>';
var_dump(isFloatInArray($array));
echo '<br />';
function isEmailByRegexp($email)
{
    $pattern = '/^\\S+@[\\w\\d.-]{2,}\\.[\\w]{2,6}$/iU';
    return filter_var($email, FILTER_VALIDATE_REGEXP, array("options" => array("regexp" => $pattern))) ? true : false;
}
$mail = '*****@*****.**';
var_dump(isEmailByRegexp($mail));
echo '<br />';
function isURL($url)
{
    return filter_var($url, FILTER_VALIDATE_URL) ? true : false;
}
var_dump(isURL('http://www.my.com/aaaa/asdfasd/asdfasdf/afsd'));
echo '<br />';
function isEmail($email)
{
    return filter_var($email, FILTER_VALIDATE_EMAIL) ? true : false;
}
var_dump(isEmail('*****@*****.**'));
?>


</body>
</html>
 /**
  * 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;
 }
コード例 #21
0
ファイル: index.php プロジェクト: VoDongMy/VoDongMy
}
?>
 
        <?php 
echo $this->session->get_flashdata('message');
?>
        </div>
    </div>
    <div id="forgot-pass" style="display: none;">
        <div id="loginhead_e"></div>
        <div class="label">
            <input class="email" id="email" type="text" onblur="if(this.value=='')this.value='Địa chỉ Email'" onfocus="if(this.value=='Địa chỉ Email')this.value=''" value="Địa chỉ Email" name="email">
        </div>
        <div class="label">
            <input type="button" onclick="send_pass()" value="" class="bt_sendpass">
        </div>
        <div class="list">
            <a href="javascript:;" onclick="form_login()">Đăng nhập hệ thống</a>
        </div>
        <?php 
function isURL($url)
{
    $pattern = '@(https?://([-\\w\\.]+)+(:\\d+)?(/([\\w/_\\.]*(\\?\\S+)?)?)?)@';
    return preg_match($pattern, $url);
}
echo isURL('360vnit.com');
?>
    </div>
</div>
<?php 
echo form_close();
コード例 #22
0
ファイル: s_common.inc.php プロジェクト: Blu2z/implsk
/**
 * Вывод поля типа "Строка" в альтернативных формах шаблона
 * @param string имя поля
 * @param string дополнительные свойства для <input ...>
 * @param int идентификатор компонента, его стоит указывать при вызове функции т.к. в функции s_list_class() его глобальное значение будет иное
 * @param bool выводить описание поля или нет
 * @return string
 */
function nc_string_field($field_name, $style = "", $classID = "", $caption = false, $value = '', $valid = false, $caption_style = null, $protect = false)
{
    // для получения значения поля
    global $fldValue, $fldID, $systemTableID;
    $nc_core = nc_Core::get_object();
    // текущее значение компонента
    if (!$classID) {
        $classID = $nc_core->sub_class->get_current('Class_ID');
    }
    $sysTable = $systemTableID ? $systemTableID : $nc_core->component->get_by_id($classID, 'System_Table_ID');
    $show_field_errors = $classID == $nc_core->sub_class->get_current('Class_ID');
    $component = new nc_Component($classID, $sysTable);
    $fields = $component->get_fields(NC_FIELDTYPE_STRING);
    // поиск поля
    $field = 0;
    $strAdd = "";
    foreach ($fields as $v) {
        $format_string = nc_field_parse_format($v['format'], NC_FIELDTYPE_STRING);
        if (isset($format_string['transliteration_field']) && $format_string['transliteration_field'] == $field_name) {
            $strAdd .= "data-type='transliterate' data-from='f_" . $v['name'] . "' " . (!empty($format_string['use_url_rules']) ? "data-is-url='yes'" : "");
        }
        if ($v['name'] == $field_name) {
            $field = $v;
        }
    }
    // поля не существует
    if (!$field) {
        if ($show_field_errors) {
            trigger_error("<b>nc_string_field()</b>: Incorrect field name (" . $field_name . ")", E_USER_WARNING);
        }
        return false;
    }
    // поле не доступно для редактирования
    if ($field['edit_type'] == 3 || $field['edit_type'] == 2 && !nc_field_check_admin_perm()) {
        return false;
    }
    // значение поля
    if (!$value && is_array($fldID)) {
        $t = array_flip($fldID);
        $value = $fldValue[$t[$field['id']]];
    }
    // вывод функции
    $result = '';
    # вывод Caption, если нужно
    if ($caption) {
        $result .= nc_field_caption($field, $caption_style);
    }
    if ($valid) {
        $result = "<span id='nc_field_{$fldID}'>{$result}</span>";
    }
    if ($value == NULL) {
        if ($field['format'] == 'url') {
            $value = isURL($field['default']) ? $field['default'] : "http://";
        } elseif ($field['default']) {
            $value = $field['default'];
        }
    }
    # формат поля
    $inputType = $field['format'] == 'password' ? 'password' : 'text';
    //echo $field['format'];
    # проверим, есть ли в параметре "style", атрибуты
    $style_attr = nc_reg_search_html_attr($style);
    # прописываем параметры из $style
    $style_opt = "";
    if (!in_array("maxlength", $style_attr)) {
        $style_opt .= "maxlength='255'";
    }
    if (!in_array("size", $style_attr)) {
        $style_opt .= ($style_opt ? " " : "") . "size='50'";
    }
    if (!in_array("type", $style_attr)) {
        $style_opt .= ($style_opt ? " " : "") . "type='" . $inputType . "'";
    }
    if ($style_opt) {
        $style_opt = " " . $style_opt;
    }
    $result .= "<input name='f_" . $field_name . "'" . $style_opt . ($style ? " " . $style : "") . " value='" . htmlspecialchars($value, ENT_QUOTES) . "' " . $strAdd . " />";
    //$result .= nc_field_validation('input', 'f_'.$field_name, $field['id'], 'string', $field['not_null'], $field['format']);
    if ($protect) {
        $result = json_encode($result);
        $html = "<div id='protect_{$field_name}'></div>";
        $html .= "<script type='text/javascript'>\n            var new_div = document.createElement('div');\n            new_div.innerHTML = {$result};\n            var protected_element = document.getElementById('protect_{$field_name}');\n            if (protected_element) {\n                protected_element.parentNode.replaceChild(new_div, protected_element);\n            }\n        </script>";
        $result = $html;
    }
    return $result;
}
コード例 #23
0
ファイル: reply_list.php プロジェクト: paulshannon/scalar
}
?>
 
<?php 
if (!empty($page->versions[$page->version_index]->rdf)) {
    ?>
	<div class="inline_icon_link meta meta_link pulldown pulldown_click"><a href="javascript:;">Additional metadata</a>
	  	<ul class="pulldown-content pulldown-content-nudge-center pulldown-content-no-mouseover nodots">
<?php 
    foreach ($page->versions[$page->version_index]->rdf as $p => $values) {
        $p = toNS($p, $ns);
        echo '<li>';
        echo '<b>' . $p . '</b><br />';
        foreach ($values as $value) {
            $value = $value['value'];
            $value = isURL($value) ? '<a href="' . $value . '">' . $value . '</a>' : $value;
            echo $value . '<br />';
        }
        echo "</li>\n";
    }
    ?>
		</ul>	
	</div>
<?php 
}
?>
  
	<div class="maximize" id="comments" style="opacity: 1;">
		<div class="maximize_fade"></div>
		<div class="maximize_content maximize_content_static_width">	
			<div class="mediaElementHeader mediaElementHeaderWithNavBar">
コード例 #24
0
ファイル: action.php プロジェクト: smc0210/michang
             $file_name_3 = "delete";
         }                
     }
     else
     {
         $file_name_3['new_name'] = date("YmdHis").makeRandomString(4);    
     } 
 }
 
 $title_explain = $title_explain."#!!#".$title_explain2;        
 if($oldPassword == $password)
 {
     $password = "";
 }
 
 if(!isURL($link))
 {
     //$link = "";
 }
 
 $isSuccess = $board_control->modifyData2($title_en, $number, $title, $tx_contents, $main_image_name
                                                         , $thumb_image_name, $etcArray, $password, $category_type
                                                         , $display_order
                                                         , $dataArray
                                                         , $fileArray
                                                         , $thumb_image2_name
                                                         , $main_thumb_image_name
                                                         , $file_name_1
                                                         , $file_name_2
                                                         , $file_name_3
                                                         , $title_explain
コード例 #25
0
 public function parseValue($ps_value, $pa_element_info, $pa_options = null)
 {
     if (is_array($ps_value) && $ps_value['_uploaded_file'] && file_exists($ps_value['tmp_name']) && filesize($ps_value['tmp_name']) > 0 || ($vb_is_file_path = file_exists($ps_value)) || ($vb_is_file_path = isURL($ps_value))) {
         // got file
         if ($vb_is_file_path) {
             return array('value_blob' => $ps_value, 'value_longtext2' => $ps_value, 'value_decimal1' => null, 'value_decimal2' => null, '_media' => true);
         } else {
             return array('value_blob' => $ps_value['tmp_name'], 'value_longtext2' => $ps_value['name'], 'value_decimal1' => null, 'value_decimal2' => null, '_media' => true);
         }
     } else {
         //$this->postError(1970, _t('No media uploaded'), 'MediaAttributeValue->parseValue()');
         //return false;
     }
     return array('value_blob' => $this->ops_media_data, 'value_longtext2' => $this->ops_file_original_name, 'value_decimal1' => null, 'value_decimal2' => null, '_dont_save' => true);
 }
コード例 #26
0
 public function delete($content = 0)
 {
     if (is_numeric($content)) {
         $content_id = (int) $content;
     }
     if (isset($content->content_id)) {
         $content_id = (int) $content->content_id;
     }
     if (empty($content_id)) {
         return false;
     }
     unset($content);
     // Get book slug (for deleting files)
     $this->db->select($this->books_table . ".slug");
     $this->db->select($this->books_table . ".book_id");
     $this->db->from($this->pages_table);
     $this->db->join($this->books_table, $this->books_table . '.book_id=' . $this->pages_table . '.book_id');
     $this->db->where($this->pages_table . '.content_id', $content_id);
     $query = $this->db->get();
     $result = $query->result();
     $book_id = (int) $result[0]->book_id;
     $book_slug = $result[0]->slug;
     // Delete from content table
     $this->db->where('content_id', $content_id);
     $this->db->delete($this->pages_table);
     // Get versions and delete from relationship tables and meta
     $ci =& get_instance();
     $ci->load->model("version_model", "versions");
     $this->db->where('content_id', $content_id);
     $query = $this->db->get($this->versions_table);
     $result = $query->result();
     $url_cache = array();
     foreach ($result as $row) {
         $version_id = (int) $row->version_id;
         $ci->versions->delete($version_id);
         $url_cache[] = $row->url;
         // Physical file
     }
     // Delete physical file (if not used by another page)
     foreach ($url_cache as $url) {
         if (!empty($url) && !isURL($url) && !empty($book_slug)) {
             // is local
             // Make sure this resource isn't being used by another page in the same book
             $version = $ci->versions->get_by_url($url);
             if (!empty($version)) {
                 $content = $this->get($version->content_id);
                 if (!empty($content) && (int) $content->book_id == $book_id) {
                     continue;
                     // Don't delete
                 }
             }
             // Go ahead and delete
             $url = confirm_slash(FCPATH) . confirm_slash($book_slug) . $url;
             if (file_exists($url) && !unlink($url)) {
                 echo 'Warning: could not delete file.';
             }
         }
     }
     // Delete versions
     $this->db->where('content_id', $content_id);
     $this->db->delete($this->versions_table);
     return true;
 }
コード例 #27
0
 /**
  * Returns id for the row with the specified name (and type) or idno (regardless of specified type.) If the row does not already
  * exist then it will be created with the specified name, type and locale, as well as with any specified values in the $pa_values array.
  * $pa_values keys should be either valid entity fields or attributes.
  *
  * @param string $ps_table The table to match and/or create rows in
  * @param array $pa_label Array with values for row label
  * @param int $pn_parent_id
  * @param int $pn_type_id The type_id or code of the type to use if the row needs to be created
  * @param int $pn_locale_id The locale_id to use if the row needs to be created (will be used for both the row locale as well as the label locale)
  * @param array $pa_values An optional array of additional values to populate newly created rows with. These values are *only* used for newly created rows; they will not be applied if the row named already exists unless the forceUpdate option is set, in which case attributes (but not intrinsics) will be updated. The array keys should be names of fields or valid attributes. Values should be either a scalar (for single-value attributes) or an array of values for (multi-valued attributes)
  * @param array $pa_options An optional array of options, which include:
  *                outputErrors - if true, errors will be printed to console [default=false]
  *                dontCreate - if true then new entities will not be created [default=false]
  *                matchOn = optional list indicating sequence of checks for an existing record; values of array can be "label" and "idno". Ex. array("idno", "label") will first try to match on idno and then label if the first match fails. For entities only you may also specifiy "displayname", "surname" and "forename" to match on the text of the those label fields exclusively.
  *                matchOnDisplayName  if true then entities are looked up exclusively using displayname, otherwise forename and surname fields are used [default=false]
  *                transaction - if Transaction instance is passed, use it for all Db-related tasks [default=null]
  *                returnInstance = return ca_entities instance rather than entity_id. Default is false.
  *                generateIdnoWithTemplate = A template to use when setting the idno. The template is a value with automatically-set SERIAL values replaced with % characters. Eg. 2012.% will set the created row's idno value to 2012.121 (assuming that 121 is the next number in the serial sequence.) The template is NOT used if idno is passed explicitly as a value in $pa_values.
  *                importEvent = if ca_data_import_events instance is passed then the insert/update of the entity will be logged as part of the import
  *                importEventSource = if importEvent is passed, then the value set for importEventSource is used in the import event log as the data source. If omitted a default value of "?" is used
  *                nonPreferredLabels = an optional array of nonpreferred labels to add to any newly created entities. Each label in the array is an array with required entity label values.
  *				  forceUpdate = update attributes set in $pa_values even if row already exists. [Default=false; no values are updated in existing rows]
  *				  matchMediaFilesWithoutExtension = For ca_object_representations, if media path is invalid, attempt to find media in referenced directory and sub-directories that has a matching name, regardless of file extension. [default=false] 
  *                log = if KLogger instance is passed then actions will be logged
  *				  ignoreParent = Don't take into account parent_id value when looking for matching rows [Default is false]
  * @return bool|BaseModel|mixed|null
  */
 private static function _getID($ps_table, $pa_label, $pn_parent_id, $pn_type_id, $pn_locale_id, $pa_values = null, $pa_options = null)
 {
     if (!is_array($pa_options)) {
         $pa_options = array();
     }
     $o_dm = Datamodel::load();
     /** @var KLogger $o_log */
     $o_log = isset($pa_options['log']) && $pa_options['log'] instanceof KLogger ? $pa_options['log'] : null;
     if (!($t_instance = $o_dm->getInstanceByTableName($ps_table, true))) {
         return null;
     }
     $vs_table_display_name = $t_instance->getProperty('NAME_SINGULAR');
     $vs_table_class = $t_instance->tableName();
     $vs_label_display_fld = $t_instance->getLabelDisplayField();
     $vs_label = $pa_label[$vs_label_display_fld];
     $pb_output_errors = caGetOption('outputErrors', $pa_options, false);
     $pb_match_on_displayname = caGetOption('matchOnDisplayName', $pa_options, false);
     $pa_match_on = caGetOption('matchOn', $pa_options, array('label', 'idno', 'displayname'), array('castTo' => "array"));
     $ps_event_source = caGetOption('importEventSource', $pa_options, '?');
     $pb_match_media_without_ext = caGetOption('matchMediaFilesWithoutExtension', $pa_options, false);
     $pb_ignore_parent = caGetOption('ignoreParent', $pa_options, false);
     $vn_parent_id = $pn_parent_id ? $pn_parent_id : caGetOption('parent_id', $pa_values, null);
     if (!$vn_parent_id) {
         $vn_parent_id = null;
     }
     $vs_idno_fld = $t_instance->getProperty('ID_NUMBERING_ID_FIELD');
     $vs_idno = caGetOption($vs_idno_fld, $pa_values, null);
     /** @var ca_data_import_events $o_event */
     $o_event = isset($pa_options['importEvent']) && $pa_options['importEvent'] instanceof ca_data_import_events ? $pa_options['importEvent'] : null;
     if (isset($pa_options['transaction']) && $pa_options['transaction'] instanceof Transaction) {
         $t_instance->setTransaction($pa_options['transaction']);
         if ($o_event) {
             $o_event->setTransaction($pa_options['transaction']);
         }
     }
     if (preg_match('!\\%!', $vs_idno)) {
         $pa_options['generateIdnoWithTemplate'] = $vs_idno;
         $vs_idno = null;
     }
     if (!$vs_idno) {
         if (isset($pa_options['generateIdnoWithTemplate']) && $pa_options['generateIdnoWithTemplate']) {
             $pa_values[$vs_idno_fld] = $vs_idno = $t_instance->setIdnoWithTemplate($pa_options['generateIdnoWithTemplate'], array('dontSetValue' => true));
         }
     }
     $va_regex_list = $va_replacements_list = null;
     if ($vs_table_class == 'ca_object_representations') {
         // Get list of regular expressions that user can use to transform file names to match object idnos
         $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));
     }
     $vn_id = null;
     foreach ($pa_match_on as $vs_match_on) {
         switch (strtolower($vs_match_on)) {
             case 'idno':
                 if ($vs_idno == '%') {
                     break;
                 }
                 // don't try to match on an unreplaced idno placeholder
                 switch ($vs_table_class) {
                     case 'ca_object_representations':
                         //
                         // idno lookups for representations use media batch importer rules
                         //
                         $va_idnos_to_match = array($vs_idno);
                         if (is_array($va_replacements_list)) {
                             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 . '!';
                                     }
                                     if ($vs_idno_proc = @preg_replace($va_search, $va_replace, $vs_idno)) {
                                         $va_idnos_to_match[] = $vs_idno_proc;
                                     }
                                 }
                             }
                         }
                         if (is_array($va_regex_list) && sizeof($va_regex_list)) {
                             foreach ($va_regex_list as $vs_regex_name => $va_regex_info) {
                                 foreach ($va_regex_info['regexes'] as $vs_regex) {
                                     foreach ($va_idnos_to_match as $vs_idno_match) {
                                         if (!$vs_idno_match) {
                                             continue;
                                         }
                                         if (preg_match('!' . $vs_regex . '!', $vs_idno_match, $va_matches)) {
                                             if ($vn_id = ca_object_representations::find(array('idno' => $va_matches[1]), array('returnAs' => 'firstId', 'purifyWithFallback' => true, 'transaction' => $pa_options['transaction']))) {
                                                 break 5;
                                             }
                                         }
                                     }
                                 }
                             }
                         } else {
                             foreach ($va_idnos_to_match as $vs_idno_match) {
                                 if (!$vs_idno_match) {
                                     continue;
                                 }
                                 if ($vn_id = ca_object_representations::find(array('idno' => $vs_idno_match), array('returnAs' => 'firstId', 'purifyWithFallback' => true, 'transaction' => $pa_options['transaction']))) {
                                     break 3;
                                 }
                             }
                         }
                         break;
                     default:
                         //
                         // Standard idno lookup for most tables
                         //
                         $va_find_vals = array($vs_idno_fld => $vs_idno ? $vs_idno : ($pa_label['_originalText'] ? $pa_label['_originalText'] : $vs_label), 'type_id' => $pn_type_id);
                         if (!$pb_ignore_parent && isset($pa_values['parent_id'])) {
                             $va_find_vals['parent_id'] = $pa_values['parent_id'];
                         }
                         if (($vs_idno || trim($pa_label['_originalText'] || $vs_label)) && ($vn_id = $vs_table_class::find($va_find_vals, array('returnAs' => 'firstId', 'purifyWithFallback' => true, 'transaction' => $pa_options['transaction'])))) {
                             break 2;
                         }
                         break;
                 }
                 break;
             case 'label':
             case 'labels':
                 if ($pb_match_on_displayname && strlen(trim($pa_label['displayname'])) > 0) {
                     // entities only
                     $va_params = array('preferred_labels' => array('displayname' => $pa_label['displayname']), 'type_id' => $pn_type_id);
                     if (!$pb_ignore_parent && isset($pa_values['parent_id'])) {
                         $va_params['parent_id'] = $vn_parent_id;
                     }
                     $vn_id = $vs_table_class::find($va_params, array('returnAs' => 'firstId', 'purifyWithFallback' => true, 'transaction' => $pa_options['transaction']));
                 } elseif ($vs_table_class == 'ca_entities') {
                     // entities only
                     $va_params = array('preferred_labels' => array('forename' => $pa_label['forename'], 'middlename' => $pa_label['middlename'], 'surname' => $pa_label['surname']), 'type_id' => $pn_type_id);
                     if (!$pb_ignore_parent) {
                         $va_params['parent_id'] = $vn_parent_id;
                     }
                     $vn_id = $vs_table_class::find($va_params, array('returnAs' => 'firstId', 'purifyWithFallback' => true, 'transaction' => $pa_options['transaction']));
                 } else {
                     $va_params = array('preferred_labels' => array($vs_label_display_fld => $pa_label[$vs_label_display_fld]), 'type_id' => $pn_type_id);
                     if (!$pb_ignore_parent && isset($pa_values['parent_id'])) {
                         $va_params['parent_id'] = $vn_parent_id;
                     }
                     $vn_id = $vs_table_class::find($va_params, array('returnAs' => 'firstId', 'purifyWithFallback' => true, 'transaction' => $pa_options['transaction']));
                 }
                 if ($vn_id) {
                     break 2;
                 }
                 break;
                 //
                 // For entities only
                 //
             //
             // For entities only
             //
             case 'surname':
                 $va_params = array('preferred_labels' => array('surname' => $pa_label['surname']), 'type_id' => $pn_type_id);
                 if (!$pb_ignore_parent && isset($pa_values['parent_id'])) {
                     $va_params['parent_id'] = $vn_parent_id;
                 }
                 $vn_id = $vs_table_class::find($va_params, array('returnAs' => 'firstId', 'purifyWithFallback' => true, 'transaction' => $pa_options['transaction']));
                 if ($vn_id) {
                     break 2;
                 }
                 break;
             case 'forename':
                 $va_params = array('preferred_labels' => array('forename' => $pa_label['forename']), 'type_id' => $pn_type_id);
                 if (!$pb_ignore_parent && isset($pa_values['parent_id'])) {
                     $va_params['parent_id'] = $vn_parent_id;
                 }
                 $vn_id = $vs_table_class::find($va_params, array('returnAs' => 'firstId', 'purifyWithFallback' => true, 'transaction' => $pa_options['transaction']));
                 if ($vn_id) {
                     break 2;
                 }
                 break;
             case 'displayname':
                 $va_params = array('preferred_labels' => array('displayname' => $pa_label['displayname']), 'type_id' => $pn_type_id);
                 if (!$pb_ignore_parent && isset($pa_values['parent_id'])) {
                     $va_params['parent_id'] = $vn_parent_id;
                 }
                 $vn_id = $vs_table_class::find($va_params, array('returnAs' => 'firstId', 'purifyWithFallback' => true, 'transaction' => $pa_options['transaction']));
                 if ($vn_id) {
                     break 2;
                 }
                 break;
         }
     }
     if (!$vn_id) {
         //
         // Create new row
         //
         if (caGetOption('dontCreate', $pa_options, false)) {
             return false;
         }
         if ($o_event) {
             $o_event->beginItem($ps_event_source, $vs_table_class, 'I');
         }
         // If we're creating a new item, it's probably a good idea to *NOT* use a
         // BaseModel instance from cache, because those cannot change their type_id
         if (!($t_instance = $o_dm->getInstanceByTableName($ps_table, false))) {
             return null;
         }
         if (isset($pa_options['transaction']) && $pa_options['transaction'] instanceof Transaction) {
             $t_instance->setTransaction($pa_options['transaction']);
         }
         $t_instance->setMode(ACCESS_WRITE);
         $t_instance->set('locale_id', $pn_locale_id);
         $t_instance->set('type_id', $pn_type_id);
         $va_intrinsics = array('source_id' => null, 'access' => 0, 'status' => 0, 'lifespan' => null, 'parent_id' => $vn_parent_id, 'lot_status_id' => null, '_interstitial' => null);
         if ($vs_hier_id_fld = $t_instance->getProperty('HIERARCHY_ID_FLD')) {
             $va_intrinsics[$vs_hier_id_fld] = null;
         }
         if ($vs_idno_fld) {
             $va_intrinsics[$vs_idno_fld] = $vs_idno ? $vs_idno : null;
         }
         foreach ($va_intrinsics as $vs_fld => $vm_fld_default) {
             if ($t_instance->hasField($vs_fld)) {
                 $t_instance->set($vs_fld, caGetOption($vs_fld, $pa_values, $vm_fld_default));
             }
             unset($pa_values[$vs_fld]);
         }
         if ($t_instance->hasField('media') && $t_instance->getFieldInfo('media', 'FIELD_TYPE') == FT_MEDIA && isset($pa_values['media']) && $pa_values['media']) {
             if (is_array($pa_values['media'])) {
                 $pa_values['media'] = array_shift($pa_values['media']);
             }
             if ($pb_match_media_without_ext && !isURL($pa_values['media']) && !file_exists($pa_values['media'])) {
                 $vs_dirname = pathinfo($pa_values['media'], PATHINFO_DIRNAME);
                 $vs_filename = preg_replace('!\\.[A-Za-z0-9]{1,4}$!', '', pathinfo($pa_values['media'], PATHINFO_BASENAME));
                 $vs_original_path = $pa_values['media'];
                 $pa_values['media'] = null;
                 $va_files_in_dir = caGetDirectoryContentsAsList($vs_dirname, true, false, false, false);
                 foreach ($va_files_in_dir as $vs_filepath) {
                     if ($o_log) {
                         $o_log->logDebug(_t("Trying media %1 in place of %2/%3", $vs_filepath, $vs_original_path, $vs_filename));
                     }
                     if (pathinfo($vs_filepath, PATHINFO_FILENAME) == $vs_filename) {
                         if ($o_log) {
                             $o_log->logNotice(_t("Found media %1 for %2/%3", $vs_filepath, $vs_original_path, $vs_filename));
                         }
                         $pa_values['media'] = $vs_filepath;
                         break;
                     }
                 }
             }
             $t_instance->set('media', $pa_values['media']);
         }
         $t_instance->insert();
         if ($t_instance->numErrors()) {
             if ($pb_output_errors) {
                 print "[Error] " . _t("Could not insert %1 %2: %3", $vs_table_display_name, $pa_label[$vs_label_display_fld], join('; ', $t_instance->getErrors())) . "\n";
             }
             if ($o_log) {
                 $o_log->logError(_t("Could not insert %1 %2: %3", $vs_table_display_name, $pa_label[$vs_label_display_fld], join('; ', $t_instance->getErrors())));
             }
             return null;
         }
         $vb_label_errors = false;
         $t_instance->addLabel($pa_label, $pn_locale_id, null, true);
         if ($t_instance->numErrors()) {
             if ($pb_output_errors) {
                 print "[Error] " . _t("Could not set preferred label for %1 %2: %3", $vs_table_display_name, $pa_label[$vs_label_display_fld], join('; ', $t_instance->getErrors())) . "\n";
             }
             if ($o_log) {
                 $o_log->logError(_t("Could not set preferred label for %1 %2: %3", $vs_table_display_name, $pa_label[$vs_label_display_fld], join('; ', $t_instance->getErrors())));
             }
             $vb_label_errors = true;
         }
         DataMigrationUtils::_setIdno($t_instance, $vs_idno, $pa_options);
         $vb_attr_errors = !DataMigrationUtils::_setAttributes($t_instance, $pn_locale_id, $pa_values, $pa_options);
         DataMigrationUtils::_setNonPreferredLabels($t_instance, $pn_locale_id, $pa_options);
         $vn_id = $t_instance->getPrimaryKey();
         if ($o_event) {
             if ($vb_attr_errors || $vb_label_errors) {
                 $o_event->endItem($vn_id, __CA_DATA_IMPORT_ITEM_PARTIAL_SUCCESS__, _t("Errors setting field values: %1", join('; ', $t_instance->getErrors())));
             } else {
                 $o_event->endItem($vn_id, __CA_DATA_IMPORT_ITEM_SUCCESS__, '');
             }
         }
         if ($o_log) {
             $o_log->logInfo(_t("Created new %1 %2", $vs_table_display_name, $pa_label[$vs_label_display_fld]));
         }
         if (isset($pa_options['returnInstance']) && $pa_options['returnInstance']) {
             return $t_instance;
         }
     } else {
         if ($o_event) {
             $o_event->beginItem($ps_event_source, $vs_table_class, 'U');
         }
         if ($o_log) {
             $o_log->logDebug(_t("Found existing %1 %2 in DataMigrationUtils::_getID()", $vs_table_display_name, $pa_label[$vs_label_display_fld]));
         }
         $vb_attr_errors = false;
         if (($vb_force_update = caGetOption('forceUpdate', $pa_options, false)) || ($vb_return_instance = caGetOption('returnInstance', $pa_options, false))) {
             if (!($t_instance = $o_dm->getInstanceByTableName($vs_table_class, false))) {
                 return null;
             }
             if (isset($pa_options['transaction']) && $pa_options['transaction'] instanceof Transaction) {
                 $t_instance->setTransaction($pa_options['transaction']);
             }
             $vb_has_attr = false;
             if ($vb_force_update) {
                 foreach ($pa_values as $vs_element => $va_values) {
                     if ($t_instance->hasElement($vs_element)) {
                         $vb_has_attr = true;
                         break;
                     }
                 }
             }
             if ($vb_return_instance || $vb_force_update && $vb_has_attr) {
                 $vn_rc = $t_instance->load($vn_id);
             } else {
                 $vn_rc = true;
             }
             if (!$vn_rc) {
                 if ($o_log) {
                     $o_log->logError(_t("Could not load existing %1 with id %2 (%3) in DataMigrationUtils::_getID() [THIS SHOULD NOT HAPPEN]", $vs_table_display_name, $vn_id, $pa_label[$vs_label_display_fld]));
                 }
                 return null;
             } else {
                 if ($vb_force_update && $vb_has_attr) {
                     if ($vb_attr_errors = !DataMigrationUtils::_setAttributes($t_instance, $pn_locale_id, $pa_values, $pa_options)) {
                         if ($o_log) {
                             $o_log->logError(_t("Could not set attributes for %1 with id %2 (%3) in DataMigrationUtils::_getID(): %4", $vs_table_display_name, $vn_id, $pa_label[$vs_label_display_fld], join("; ", $t_instance->getErrors())));
                         }
                     }
                 }
                 if ($o_event) {
                     if ($vb_attr_errors) {
                         $o_event->endItem($vn_id, __CA_DATA_IMPORT_ITEM_PARTIAL_SUCCESS__, _t("Errors setting field values: %1", join('; ', $t_instance->getErrors())));
                     } else {
                         $o_event->endItem($vn_id, __CA_DATA_IMPORT_ITEM_SUCCESS__, '');
                     }
                 }
                 if ($vb_return_instance) {
                     return $t_instance;
                 }
             }
         }
         if ($o_event) {
             $o_event->endItem($vn_id, __CA_DATA_IMPORT_ITEM_SUCCESS__, '');
         }
     }
     return $vn_id;
 }
コード例 #28
0
ファイル: ItemService.php プロジェクト: ymani2435/providence
 /**
  * Add item as specified in request body array. Can also be used to
  * add item directly. If both parameters are set, the request data
  * is ignored.
  * @param null|string $ps_table optional table name. if not set, table name is taken from request
  * @param null|array $pa_data optional array with item data. if not set, data is taken from request body
  * @return array|bool
  */
 public function addItem($ps_table = null, $pa_data = null)
 {
     if (!$ps_table) {
         $ps_table = $this->ops_table;
     }
     if (!($t_instance = $this->_getTableInstance($ps_table))) {
         return false;
     }
     $t_locales = new ca_locales();
     if (!$pa_data || !is_array($pa_data)) {
         $pa_data = $this->getRequestBodyArray();
     }
     // intrinsic fields
     if (is_array($pa_data["intrinsic_fields"]) && sizeof($pa_data["intrinsic_fields"])) {
         foreach ($pa_data["intrinsic_fields"] as $vs_field_name => $vs_value) {
             $t_instance->set($vs_field_name, $vs_value);
         }
     } else {
         $this->addError(_t("No intrinsic fields specified"));
         return false;
     }
     // attributes
     if (is_array($pa_data["attributes"]) && sizeof($pa_data["attributes"])) {
         foreach ($pa_data["attributes"] as $vs_attribute_name => $va_values) {
             foreach ($va_values as $va_value) {
                 if ($va_value["locale"]) {
                     $va_value["locale_id"] = $t_locales->localeCodeToID($va_value["locale"]);
                     unset($va_value["locale"]);
                 }
                 $t_instance->addAttribute($va_value, $vs_attribute_name);
             }
         }
     }
     $t_instance->setMode(ACCESS_WRITE);
     $t_instance->insert();
     if (!$t_instance->getPrimaryKey()) {
         $this->opa_errors = array_merge($t_instance->getErrors(), $this->opa_errors);
         return false;
     }
     // AFTER INSERT STUFF
     // preferred labels
     if (is_array($pa_data["preferred_labels"]) && sizeof($pa_data["preferred_labels"])) {
         foreach ($pa_data["preferred_labels"] as $va_label) {
             if ($va_label["locale"]) {
                 $vn_locale_id = $t_locales->localeCodeToID($va_label["locale"]);
                 unset($va_label["locale"]);
             }
             $t_instance->addLabel($va_label, $vn_locale_id, null, true);
         }
     }
     // nonpreferred labels
     if (is_array($pa_data["nonpreferred_labels"]) && sizeof($pa_data["nonpreferred_labels"])) {
         foreach ($pa_data["nonpreferred_labels"] as $va_label) {
             if ($va_label["locale"]) {
                 $vn_locale_id = $t_locales->localeCodeToID($va_label["locale"]);
                 unset($va_label["locale"]);
             }
             if ($va_label["type_id"]) {
                 $vn_type_id = $va_label["type_id"];
                 unset($va_label["type_id"]);
             } else {
                 $vn_type_id = null;
             }
             $t_instance->addLabel($va_label, $vn_locale_id, $vn_type_id, false);
         }
     }
     // relationships
     if (is_array($pa_data["related"]) && sizeof($pa_data["related"]) > 0) {
         foreach ($pa_data["related"] as $vs_table => $va_relationships) {
             if ($vs_table == 'ca_sets') {
                 foreach ($va_relationships as $va_relationship) {
                     $t_set = new ca_sets();
                     if ($t_set->load($va_relationship)) {
                         $t_set->addItem($t_instance->getPrimaryKey());
                     }
                 }
             } else {
                 foreach ($va_relationships as $va_relationship) {
                     $vs_source_info = isset($va_relationship["source_info"]) ? $va_relationship["source_info"] : null;
                     $vs_effective_date = isset($va_relationship["effective_date"]) ? $va_relationship["effective_date"] : null;
                     $vs_direction = isset($va_relationship["direction"]) ? $va_relationship["direction"] : null;
                     $t_rel_instance = $this->_getTableInstance($vs_table);
                     $vs_pk = isset($va_relationship[$t_rel_instance->primaryKey()]) ? $va_relationship[$t_rel_instance->primaryKey()] : null;
                     $vs_type_id = isset($va_relationship["type_id"]) ? $va_relationship["type_id"] : null;
                     $t_rel = $t_instance->addRelationship($vs_table, $vs_pk, $vs_type_id, $vs_effective_date, $vs_source_info, $vs_direction);
                     // deal with interstitial attributes
                     if ($t_rel instanceof BaseRelationshipModel) {
                         $vb_have_to_update = false;
                         if (is_array($va_relationship["attributes"]) && sizeof($va_relationship["attributes"])) {
                             foreach ($va_relationship["attributes"] as $vs_attribute_name => $va_values) {
                                 foreach ($va_values as $va_value) {
                                     if ($va_value["locale"]) {
                                         $va_value["locale_id"] = $t_locales->localeCodeToID($va_value["locale"]);
                                         unset($va_value["locale"]);
                                     }
                                     $t_rel->addAttribute($va_value, $vs_attribute_name);
                                     $vb_have_to_update = true;
                                 }
                             }
                         }
                         if ($vb_have_to_update) {
                             $t_rel->setMode(ACCESS_WRITE);
                             $t_rel->update();
                         }
                     }
                 }
             }
         }
         if ($t_instance instanceof RepresentableBaseModel && isset($pa_data['representations']) && is_array($pa_data['representations'])) {
             foreach ($pa_data['representations'] as $va_rep) {
                 if (!isset($va_rep['media']) || !file_exists($va_rep['media']) && !isURL($va_rep['media'])) {
                     continue;
                 }
                 if (!($vn_rep_locale_id = $t_locales->localeCodeToID($va_rep['locale']))) {
                     $vn_rep_locale_id = $t_locales->localeCodeToID('en_US');
                 }
                 $t_instance->addRepresentation($va_rep['media'], caGetOption('type', $va_rep, 'front'), $vn_rep_locale_id, caGetOption('status', $va_rep, 0), caGetOption('access', $va_rep, 0), (bool) $va_rep['primary'], is_array($va_rep['values']) ? $va_rep['values'] : null);
             }
         }
     }
     if ($t_instance->numErrors() > 0) {
         foreach ($t_instance->getErrors() as $vs_error) {
             $this->addError($vs_error);
         }
         // don't leave orphaned record in case something
         // went wrong with labels or relationships
         if ($t_instance->getPrimaryKey()) {
             $t_instance->delete();
         }
         return false;
     } else {
         return array($t_instance->primaryKey() => $t_instance->getPrimaryKey());
     }
 }
コード例 #29
0
ファイル: TGN.php プロジェクト: ymani2435/providence
    /** 
     * Perform lookup on TGN-based data service
     *
     * @param array $pa_settings Plugin settings values
     * @param string $ps_search The expression with which to query the remote data service
     * @param array $pa_options Lookup options
     * 			phrase => send a lucene phrase search instead of keywords
     * 			raw => return raw, unprocessed results from getty service
     * @return array
     */
    public function lookup($pa_settings, $ps_search, $pa_options = null)
    {
        if (!is_array($pa_options)) {
            $pa_options = array();
        }
        $va_service_conf = $this->opo_linked_data_conf->get('tgn');
        $vs_search_field = isset($va_service_conf['search_text']) && $va_service_conf['search_text'] ? 'luc:text' : 'luc:term';
        $pb_phrase = (bool) caGetOption('phrase', $pa_options, false);
        $pb_raw = (bool) caGetOption('raw', $pa_options, false);
        $pn_limit = (int) caGetOption('limit', $pa_options, $va_service_conf['result_limit'] ? $va_service_conf['result_limit'] : 50);
        /**
         * Contrary to what the Getty documentation says the terms seem to get combined by OR, not AND, so if you pass
         * "Coney Island" you get all kinds of Islands, just not the one you're looking for. It's in there somewhere but
         * the order field might prevent it from showing up within the limit. So we do our own little piece of "query rewriting" here.
         */
        if (is_numeric($ps_search)) {
            $vs_search = $ps_search;
        } elseif (isURL($ps_search)) {
            $vs_search = str_replace('http://vocab.getty.edu/tgn/', '', $ps_search);
        } elseif ($pb_phrase) {
            $vs_search = '\\"' . $ps_search . '\\"';
        } else {
            $va_search = preg_split('/[\\s]+/', $ps_search);
            $vs_search = join(' AND ', $va_search);
        }
        $vs_query = urlencode('SELECT ?ID ?TermPrefLabel ?Parents ?Type ?ParentsFull{
			?ID a skos:Concept; ' . $vs_search_field . ' "' . $vs_search . '"; skos:inScheme tgn: ;
			gvp:prefLabelGVP [xl:literalForm ?TermPrefLabel].
  			{?ID gvp:parentStringAbbrev ?Parents}
  			{?ID gvp:parentStringAbbrev ?ParentsFull}
  			{?ID gvp:displayOrder ?Order}
  			{?ID gvp:placeTypePreferred [gvp:prefLabelGVP [xl:literalForm ?Type]]}
		} ORDER BY ASC(?Order)
		LIMIT ' . $pn_limit);
        $va_results = parent::queryGetty($vs_query);
        if (!is_array($va_results)) {
            return false;
        }
        if ($pb_raw) {
            return $va_results;
        }
        $va_return = array();
        foreach ($va_results as $va_values) {
            $vs_id = '';
            if (preg_match("/[a-z]{3,4}\\/[0-9]+\$/", $va_values['ID']['value'], $va_matches)) {
                $vs_id = str_replace('/', ':', $va_matches[0]);
            }
            $vs_label = '[' . str_replace('tgn:', '', $vs_id) . '] ' . $va_values['TermPrefLabel']['value'] . "; " . $va_values['Parents']['value'] . " (" . $va_values['Type']['value'] . ")";
            $va_return['results'][] = array('label' => htmlentities(str_replace(', ... World', '', $vs_label)), 'url' => $va_values['ID']['value'], 'idno' => $vs_id);
        }
        return $va_return;
    }
コード例 #30
0
 /**
  * Fetches a literal property string value from given node
  * @param string $ps_base_node
  * @param string $ps_literal_propery EasyRdf property definition
  * @param string|null $ps_node_uri Optional related node URI to pull from
  * @param array $pa_options Available options are
  * 			limit -> limit number of processed related notes, defaults to 10
  * 			stripAfterLastComma -> strip everything after (and including) the last comma in the individual literal string
  * 				this is useful for gvp:parentString where the top-most category is usually not very useful
  * @return string|bool
  */
 static function getLiteralFromRDFNode($ps_base_node, $ps_literal_propery, $ps_node_uri = null, $pa_options = array())
 {
     if (!isURL($ps_base_node)) {
         return false;
     }
     if (!is_array($pa_options)) {
         $pa_options = array();
     }
     $vs_cache_key = md5(serialize(func_get_args()));
     if (CompositeCache::contains($vs_cache_key, 'GettyRDFLiterals')) {
         return CompositeCache::fetch($vs_cache_key, 'GettyRDFLiterals');
     }
     $pn_limit = (int) caGetOption('limit', $pa_options, 10);
     $pb_strip_after_last_comma = (bool) caGetOption('stripAfterLastComma', $pa_options, false);
     $pb_invert = (bool) caGetOption('invert', $pa_options, false);
     $pb_recursive = (bool) caGetOption('recursive', $pa_options, false);
     if (!($o_graph = self::getURIAsRDFGraph($ps_base_node))) {
         return false;
     }
     // if we're pulling from a related node, add those graphs (technically nodes) to the list (we pull from all of them)
     if (strlen($ps_node_uri) > 0) {
         $va_pull_graphs = self::getListOfRelatedGraphs($o_graph, $ps_base_node, $ps_node_uri, $pn_limit, $pb_recursive);
     } else {
         // the only graph/node we pull from is the base node
         $va_pull_graphs = array($ps_base_node => $o_graph);
     }
     if (!is_array($va_pull_graphs)) {
         return false;
     }
     $va_return = array();
     $vn_j = 0;
     foreach ($va_pull_graphs as $vs_uri => $o_g) {
         $va_literals = $o_g->all($vs_uri, $ps_literal_propery);
         foreach ($va_literals as $o_literal) {
             if ($o_literal instanceof EasyRdf_Literal) {
                 $vs_string_to_add = htmlentities(preg_replace('/[\\<\\>]/', '', $o_literal->getValue()));
             } else {
                 $vs_string_to_add = preg_replace('/[\\<\\>]/', '', (string) $o_literal);
             }
             if ($pb_strip_after_last_comma) {
                 $vn_last_comma_pos = strrpos($vs_string_to_add, ',');
                 $vs_string_to_add = substr($vs_string_to_add, 0, $vn_last_comma_pos - strlen($vs_string_to_add));
             }
             $va_tmp = explode(', ', $vs_string_to_add);
             if ($pb_invert && sizeof($va_tmp)) {
                 $vs_string_to_add = join(' &gt; ', array_reverse($va_tmp));
             }
             // make links click-able
             if (isURL($vs_string_to_add)) {
                 $vs_string_to_add = "<a href='{$vs_string_to_add}' target='_blank'>{$vs_string_to_add}</a>";
             }
             $va_return[] = $vs_string_to_add;
             if (++$vn_j >= $pn_limit) {
                 break;
             }
         }
     }
     $vs_return = join('; ', $va_return);
     CompositeCache::save($vs_cache_key, $vs_return, 'GettyRDFLiterals', 60 * 60 * 24 * 7);
     return $vs_return;
 }