escapeJsString() публичный статический Метод

.. ]]> this requires only to escape ' with \' and end of script block We also remove NUL byte as some browsers (namely MSIE) ignore it and inserting it anywhere inside
public static escapeJsString ( string $string ) : string
$string string the string to be escaped
Результат string the escaped string
Пример #1
0
    /**
     * Displays a link, or a button if the link's URL is too large, to
     * accommodate some browsers' limitations
     *
     * @param string  $url          the URL
     * @param string  $message      the link message
     * @param mixed   $tag_params   string: js confirmation
     *                              array: additional tag params (f.e. style="")
     * @param boolean $new_form     we set this to false when we are already in
     *                              a  form, to avoid generating nested forms
     * @param boolean $strip_img    whether to strip the image
     * @param string  $target       target
     * @param boolean $force_button use a button even when the URL is not too long
     *
     * @return string  the results to be echoed or saved in an array
     */
    public static function linkOrButton(
        $url, $message, $tag_params = array(),
        $new_form = true, $strip_img = false, $target = '', $force_button = false
    ) {
        $url_length = mb_strlen($url);
        // with this we should be able to catch case of image upload
        // into a (MEDIUM) BLOB; not worth generating even a form for these
        if ($url_length > $GLOBALS['cfg']['LinkLengthLimit'] * 100) {
            return '';
        }

        if (! is_array($tag_params)) {
            $tmp = $tag_params;
            $tag_params = array();
            if (! empty($tmp)) {
                $tag_params['onclick'] = 'return confirmLink(this, \''
                    . Sanitize::escapeJsString($tmp) . '\')';
            }
            unset($tmp);
        }
        if (! empty($target)) {
            $tag_params['target'] = htmlentities($target);
            if ($target === '_blank' && strncmp($url, 'url.php?', 8) == 0) {
                $tag_params['rel'] = 'noopener noreferrer';
            }
        }

        $displayed_message = '';
        // Add text if not already added
        if (stristr($message, '<img')
            && (! $strip_img || ($GLOBALS['cfg']['ActionLinksMode'] == 'icons'))
            && (strip_tags($message) == $message)
        ) {
            $displayed_message = '<span>'
                . htmlspecialchars(
                    preg_replace('/^.*\salt="([^"]*)".*$/si', '\1', $message)
                )
                . '</span>';
        }

        // Suhosin: Check that each query parameter is not above maximum
        $in_suhosin_limits = true;
        if ($url_length <= $GLOBALS['cfg']['LinkLengthLimit']) {
            $suhosin_get_MaxValueLength = ini_get('suhosin.get.max_value_length');
            if ($suhosin_get_MaxValueLength) {
                $query_parts = self::splitURLQuery($url);
                foreach ($query_parts as $query_pair) {
                    if (strpos($query_pair, '=') === false) {
                        continue;
                    }

                    list(, $eachval) = explode('=', $query_pair);
                    if (mb_strlen($eachval) > $suhosin_get_MaxValueLength
                    ) {
                        $in_suhosin_limits = false;
                        break;
                    }
                }
            }
        }

        if (($url_length <= $GLOBALS['cfg']['LinkLengthLimit'])
            && $in_suhosin_limits
            && ! $force_button
        ) {
            $tag_params_strings = array();
            foreach ($tag_params as $par_name => $par_value) {
                // htmlspecialchars() only on non javascript
                $par_value = mb_substr($par_name, 0, 2) == 'on'
                    ? $par_value
                    : htmlspecialchars($par_value);
                $tag_params_strings[] = $par_name . '="' . $par_value . '"';
            }

            // no whitespace within an <a> else Safari will make it part of the link
            $ret = "\n" . '<a href="' . $url . '" '
                . implode(' ', $tag_params_strings) . '>'
                . $message . $displayed_message . '</a>' . "\n";
        } else {
            // no spaces (line breaks) at all
            // or after the hidden fields
            // IE will display them all

            if (! isset($query_parts)) {
                $query_parts = self::splitURLQuery($url);
            }
            $url_parts   = parse_url($url);

            if ($new_form) {
                if ($target) {
                    $target = ' target="' . $target . '"';
                }
                $ret = '<form action="' . $url_parts['path'] . '" class="link"'
                     . ' method="post"' . $target . ' style="display: inline;">';
                $subname_open   = '';
                $subname_close  = '';
                $submit_link    = '#';
            } else {
                $query_parts[] = 'redirect=' . $url_parts['path'];
                if (empty($GLOBALS['subform_counter'])) {
                    $GLOBALS['subform_counter'] = 0;
                }
                $GLOBALS['subform_counter']++;
                $ret            = '';
                $subname_open   = 'subform[' . $GLOBALS['subform_counter'] . '][';
                $subname_close  = ']';
                $submit_link    = '#usesubform[' . $GLOBALS['subform_counter']
                    . ']=1';
            }

            foreach ($query_parts as $query_pair) {
                list($eachvar, $eachval) = explode('=', $query_pair);
                $ret .= '<input type="hidden" name="' . $subname_open . $eachvar
                    . $subname_close . '" value="'
                    . htmlspecialchars(urldecode($eachval)) . '" />';
            } // end while

            if (empty($tag_params['class'])) {
                $tag_params['class'] = 'formLinkSubmit';
            } else {
                $tag_params['class'] .= ' formLinkSubmit';
            }

            $tag_params_strings = array();
            foreach ($tag_params as $par_name => $par_value) {
                // htmlspecialchars() only on non javascript
                $par_value = mb_substr($par_name, 0, 2) == 'on'
                    ? $par_value
                    : htmlspecialchars($par_value);
                $tag_params_strings[] = $par_name . '="' . $par_value . '"';
            }

            $ret .= "\n" . '<a href="' . $submit_link . '" '
                . implode(' ', $tag_params_strings) . '>'
                . $message . ' ' . $displayed_message . '</a>' . "\n";

            if ($new_form) {
                $ret .= '</form>';
            }
        } // end if... else...

        return $ret;
    } // end of the 'linkOrButton()' function
Пример #2
0
 /**
  * Prepares data for input field display and outputs HTML code
  *
  * @param Form      $form                 Form object
  * @param string    $field                field name as it appears in $form
  * @param string    $system_path          field path, eg. Servers/1/verbose
  * @param string    $work_path            work path, eg. Servers/4/verbose
  * @param string    $translated_path      work path changed so that it can be
  *                                        used as XHTML id
  * @param bool      $show_restore_default whether show "restore default" button
  *                                        besides the input field
  * @param bool|null $userprefs_allow      whether user preferences are enabled
  *                                        for this field (null - no support,
  *                                        true/false - enabled/disabled)
  * @param array     &$js_default          array which stores JavaScript code
  *                                        to be displayed
  *
  * @return string HTML for input field
  */
 private function _displayFieldInput(Form $form, $field, $system_path, $work_path, $translated_path, $show_restore_default, $userprefs_allow, array &$js_default)
 {
     $name = PMA_langName($system_path);
     $description = PMA_langName($system_path, 'desc', '');
     $value = $this->_configFile->get($work_path);
     $value_default = $this->_configFile->getDefault($system_path);
     $value_is_default = false;
     if ($value === null || $value === $value_default) {
         $value = $value_default;
         $value_is_default = true;
     }
     $opts = array('doc' => $this->getDocLink($system_path), 'show_restore_default' => $show_restore_default, 'userprefs_allow' => $userprefs_allow, 'userprefs_comment' => PMA_langName($system_path, 'cmt', ''));
     if (isset($form->default[$system_path])) {
         $opts['setvalue'] = $form->default[$system_path];
     }
     if (isset($this->_errors[$work_path])) {
         $opts['errors'] = $this->_errors[$work_path];
     }
     $type = '';
     switch ($form->getOptionType($field)) {
         case 'string':
             $type = 'text';
             break;
         case 'short_string':
             $type = 'short_text';
             break;
         case 'double':
         case 'integer':
             $type = 'number_text';
             break;
         case 'boolean':
             $type = 'checkbox';
             break;
         case 'select':
             $type = 'select';
             $opts['values'] = $form->getOptionValueList($form->fields[$field]);
             break;
         case 'array':
             $type = 'list';
             $value = (array) $value;
             $value_default = (array) $value_default;
             break;
         case 'group':
             // :group:end is changed to :group:end:{unique id} in Form class
             $htmlOutput = '';
             if (mb_substr($field, 7, 4) != 'end:') {
                 $htmlOutput .= PMA_displayGroupHeader(mb_substr($field, 7));
             } else {
                 PMA_displayGroupFooter();
             }
             return $htmlOutput;
         case 'NULL':
             trigger_error("Field {$system_path} has no type", E_USER_WARNING);
             return null;
     }
     // detect password fields
     if ($type === 'text' && mb_substr($translated_path, -9) === '-password') {
         $type = 'password';
     }
     // TrustedProxies requires changes before displaying
     if ($system_path == 'TrustedProxies') {
         foreach ($value as $ip => &$v) {
             if (!preg_match('/^-\\d+$/', $ip)) {
                 $v = $ip . ': ' . $v;
             }
         }
     }
     $this->_setComments($system_path, $opts);
     // send default value to form's JS
     $js_line = '\'' . $translated_path . '\': ';
     switch ($type) {
         case 'text':
         case 'short_text':
         case 'number_text':
         case 'password':
             $js_line .= '\'' . Sanitize::escapeJsString($value_default) . '\'';
             break;
         case 'checkbox':
             $js_line .= $value_default ? 'true' : 'false';
             break;
         case 'select':
             $value_default_js = is_bool($value_default) ? (int) $value_default : $value_default;
             $js_line .= '[\'' . Sanitize::escapeJsString($value_default_js) . '\']';
             break;
         case 'list':
             $js_line .= '\'' . Sanitize::escapeJsString(implode("\n", $value_default)) . '\'';
             break;
     }
     $js_default[] = $js_line;
     return PMA_displayInput($translated_path, $name, $type, $value, $description, $value_is_default, $opts);
 }
Пример #3
0
/**
 * Generate HTML for export form
 *
 * @param array  $url_params Parameters
 * @param string $str1       HTML for logtype select
 * @param string $str2       HTML for "from date"
 * @param string $str3       HTML for "to date"
 * @param string $str4       HTML for user
 * @param string $str5       HTML for "list report"
 *
 * @return string HTML for form
 */
function PMA_getHtmlForTrackingReportExportForm2($url_params, $str1, $str2, $str3, $str4, $str5)
{
    $html = '<form method="post" action="tbl_tracking.php' . URL::getCommon($url_params + array('report' => 'true', 'version' => $_REQUEST['version'])) . '">';
    $html .= sprintf(__('Show %1$s with dates from %2$s to %3$s by user %4$s %5$s'), $str1, $str2, $str3, $str4, $str5);
    $html .= '</form>';
    $html .= '<form class="disableAjax" method="post" action="tbl_tracking.php' . URL::getCommon($url_params + array('report' => 'true', 'version' => $_REQUEST['version'])) . '">';
    $html .= '<input type="hidden" name="logtype" value="' . htmlspecialchars($_REQUEST['logtype']) . '" />';
    $html .= '<input type="hidden" name="date_from" value="' . htmlspecialchars($_REQUEST['date_from']) . '" />';
    $html .= '<input type="hidden" name="date_to" value="' . htmlspecialchars($_REQUEST['date_to']) . '" />';
    $html .= '<input type="hidden" name="users" value="' . htmlspecialchars($_REQUEST['users']) . '" />';
    $str_export1 = '<select name="export_type">' . '<option value="sqldumpfile">' . __('SQL dump (file download)') . '</option>' . '<option value="sqldump">' . __('SQL dump') . '</option>' . '<option value="execution" onclick="alert(\'' . Sanitize::escapeJsString(__('This option will replace your table and contained data.')) . '\')">' . __('SQL execution') . '</option>' . '</select>';
    $str_export2 = '<input type="hidden" name="report_export" value="1" />' . '<input type="submit" value="' . __('Go') . '" />';
    $html .= "<br/>" . sprintf(__('Export as %s'), $str_export1) . $str_export2 . "<br/>";
    $html .= '</form>';
    return $html;
}
Пример #4
0
 /**
  * Returns, as a string, a list of parameters
  * used on the client side
  *
  * @return string
  */
 public function getJsParamsCode()
 {
     $params = $this->getJsParams();
     foreach ($params as $key => $value) {
         $params[$key] = $key . ':"' . Sanitize::escapeJsString($value) . '"';
     }
     return 'PMA_commonParams.setAll({' . implode(',', $params) . '});';
 }
Пример #5
0
/**
 * Appends JS validation code to $js_array
 *
 * @param string       $field_id   ID of field to validate
 * @param string|array $validators validators callback
 * @param array        &$js_array  will be updated with javascript code
 *
 * @return void
 */
function PMA_addJsValidate($field_id, $validators, &$js_array)
{
    foreach ((array) $validators as $validator) {
        $validator = (array) $validator;
        $v_name = array_shift($validator);
        $v_name = "PMA_" . $v_name;
        $v_args = array();
        foreach ($validator as $arg) {
            $v_args[] = Sanitize::escapeJsString($arg);
        }
        $v_args = $v_args ? ", ['" . implode("', '", $v_args) . "']" : '';
        $js_array[] = "validateField('{$field_id}', '{$v_name}', true{$v_args})";
    }
}
Пример #6
0
 * Gets core libraries and defines some variables
 */
define('PMA_MINIMUM_COMMON', true);
require_once './libraries/common.inc.php';

// Only output the http headers
$response = Response::getInstance();
$response->getHeader()->sendHttpHeaders();
$response->disable();

if (! PMA_isValid($_REQUEST['url'])
    || ! preg_match('/^https:\/\/[^\n\r]*$/', $_REQUEST['url'])
    || ! PMA_isAllowedDomain($_REQUEST['url'])
) {
    PMA_sendHeaderLocation('./');
} else {
    // JavaScript redirection is necessary. Because if header() is used
    //  then web browser sometimes does not change the HTTP_REFERER
    //  field and so with old URL as Referer, token also goes to
    //  external site.
    echo "<script type='text/javascript'>
            window.onload=function(){
                window.location='" , Sanitize::escapeJsString($_REQUEST['url']) , "';
            }
        </script>";
    // Display redirecting msg on screen.
    // Do not display the value of $_REQUEST['url'] to avoid showing injected content
    echo __('Taking you to the target site.');
}
die();
Пример #7
0
/**
 * Function to get html for each insert/edit column
 *
 * @param array  $table_columns         table columns
 * @param int    $column_number         column index in table_columns
 * @param array  $comments_map          comments map
 * @param bool   $timestamp_seen        whether timestamp seen
 * @param array  $current_result        current result
 * @param string $chg_evt_handler       javascript change event handler
 * @param string $jsvkey                javascript validation key
 * @param string $vkey                  validation key
 * @param bool   $insert_mode           whether insert mode
 * @param array  $current_row           current row
 * @param int    &$o_rows               row offset
 * @param int    &$tabindex             tab index
 * @param int    $columns_cnt           columns count
 * @param bool   $is_upload             whether upload
 * @param int    $tabindex_for_function tab index offset for function
 * @param array  $foreigners            foreigners
 * @param int    $tabindex_for_null     tab index offset for null
 * @param int    $tabindex_for_value    tab index offset for value
 * @param string $table                 table
 * @param string $db                    database
 * @param int    $row_id                row id
 * @param array  $titles                titles
 * @param int    $biggest_max_file_size biggest max file size
 * @param string $default_char_editing  default char editing mode which is stored
 *                                      in the config.inc.php script
 * @param string $text_dir              text direction
 * @param array  $repopulate            the data to be repopulated
 * @param array  $column_mime           the mime information of column
 * @param string $where_clause          the where clause
 *
 * @return string
 */
function PMA_getHtmlForInsertEditFormColumn($table_columns, $column_number, $comments_map, $timestamp_seen, $current_result, $chg_evt_handler, $jsvkey, $vkey, $insert_mode, $current_row, &$o_rows, &$tabindex, $columns_cnt, $is_upload, $tabindex_for_function, $foreigners, $tabindex_for_null, $tabindex_for_value, $table, $db, $row_id, $titles, $biggest_max_file_size, $default_char_editing, $text_dir, $repopulate, $column_mime, $where_clause)
{
    $column = $table_columns[$column_number];
    $readOnly = false;
    if (!PMA_userHasColumnPrivileges($column, $insert_mode)) {
        $readOnly = true;
    }
    if (!isset($column['processed'])) {
        $column = PMA_analyzeTableColumnsArray($column, $comments_map, $timestamp_seen);
    }
    $as_is = false;
    if (!empty($repopulate) && !empty($current_row)) {
        $current_row[$column['Field']] = $repopulate[$column['Field_md5']];
        $as_is = true;
    }
    $extracted_columnspec = PMA\libraries\Util::extractColumnSpec($column['Type']);
    if (-1 === $column['len']) {
        $column['len'] = $GLOBALS['dbi']->fieldLen($current_result, $column_number);
        // length is unknown for geometry fields,
        // make enough space to edit very simple WKTs
        if (-1 === $column['len']) {
            $column['len'] = 30;
        }
    }
    //Call validation when the form submitted...
    $onChangeClause = $chg_evt_handler . "=\"return verificationsAfterFieldChange('" . Sanitize::escapeJsString($column['Field_md5']) . "', '" . Sanitize::escapeJsString($jsvkey) . "','" . $column['pma_type'] . "')\"";
    // Use an MD5 as an array index to avoid having special characters
    // in the name attribute (see bug #1746964 )
    $column_name_appendix = $vkey . '[' . $column['Field_md5'] . ']';
    if ($column['Type'] === 'datetime' && !isset($column['Default']) && !is_null($column['Default']) && $insert_mode) {
        $column['Default'] = date('Y-m-d H:i:s', time());
    }
    $html_output = PMA_getHtmlForFunctionOption($column, $column_name_appendix);
    if ($GLOBALS['cfg']['ShowFieldTypesInDataEditView']) {
        $html_output .= PMA_getHtmlForInsertEditColumnType($column);
    }
    //End if
    // Get a list of GIS data types.
    $gis_data_types = PMA\libraries\Util::getGISDatatypes();
    // Prepares the field value
    $real_null_value = false;
    $special_chars_encoded = '';
    if (!empty($current_row)) {
        // (we are editing)
        list($real_null_value, $special_chars_encoded, $special_chars, $data, $backup_field) = PMA_getSpecialCharsAndBackupFieldForExistingRow($current_row, $column, $extracted_columnspec, $real_null_value, $gis_data_types, $column_name_appendix, $as_is);
    } else {
        // (we are inserting)
        // display default values
        $tmp = $column;
        if (isset($repopulate[$column['Field_md5']])) {
            $tmp['Default'] = $repopulate[$column['Field_md5']];
        }
        list($real_null_value, $data, $special_chars, $backup_field, $special_chars_encoded) = PMA_getSpecialCharsAndBackupFieldForInsertingMode($tmp, $real_null_value);
        unset($tmp);
    }
    $idindex = $o_rows * $columns_cnt + $column_number + 1;
    $tabindex = $idindex;
    // Get a list of data types that are not yet supported.
    $no_support_types = PMA\libraries\Util::unsupportedDatatypes();
    // The function column
    // -------------------
    $foreignData = PMA_getForeignData($foreigners, $column['Field'], false, '', '');
    if ($GLOBALS['cfg']['ShowFunctionFields']) {
        $html_output .= PMA_getFunctionColumn($column, $is_upload, $column_name_appendix, $onChangeClause, $no_support_types, $tabindex_for_function, $tabindex, $idindex, $insert_mode, $readOnly, $foreignData);
    }
    // The null column
    // ---------------
    $html_output .= PMA_getNullColumn($column, $column_name_appendix, $real_null_value, $tabindex, $tabindex_for_null, $idindex, $vkey, $foreigners, $foreignData, $readOnly);
    // The value column (depends on type)
    // ----------------
    // See bug #1667887 for the reason why we don't use the maxlength
    // HTML attribute
    //add data attributes "no of decimals" and "data type"
    $no_decimals = 0;
    $type = current(explode("(", $column['pma_type']));
    if (preg_match('/\\(([^()]+)\\)/', $column['pma_type'], $match)) {
        $match[0] = trim($match[0], '()');
        $no_decimals = $match[0];
    }
    $html_output .= '<td' . ' data-type="' . $type . '"' . ' data-decimals="' . $no_decimals . '">' . "\n";
    // Will be used by js/tbl_change.js to set the default value
    // for the "Continue insertion" feature
    $html_output .= '<span class="default_value hide">' . $special_chars . '</span>';
    // Check input transformation of column
    $transformed_html = '';
    if (!empty($column_mime['input_transformation'])) {
        $file = $column_mime['input_transformation'];
        $include_file = 'libraries/plugins/transformations/' . $file;
        if (is_file($include_file)) {
            include_once $include_file;
            $class_name = PMA_getTransformationClassName($include_file);
            $transformation_plugin = new $class_name();
            $transformation_options = PMA_Transformation_getOptions($column_mime['input_transformation_options']);
            $_url_params = array('db' => $db, 'table' => $table, 'transform_key' => $column['Field'], 'where_clause' => $where_clause);
            $transformation_options['wrapper_link'] = URL::getCommon($_url_params);
            $current_value = '';
            if (isset($current_row[$column['Field']])) {
                $current_value = $current_row[$column['Field']];
            }
            if (method_exists($transformation_plugin, 'getInputHtml')) {
                $transformed_html = $transformation_plugin->getInputHtml($column, $row_id, $column_name_appendix, $transformation_options, $current_value, $text_dir, $tabindex, $tabindex_for_value, $idindex);
            }
            if (method_exists($transformation_plugin, 'getScripts')) {
                $GLOBALS['plugin_scripts'] = array_merge($GLOBALS['plugin_scripts'], $transformation_plugin->getScripts());
            }
        }
    }
    if (!empty($transformed_html)) {
        $html_output .= $transformed_html;
    } else {
        $html_output .= PMA_getValueColumn($column, $backup_field, $column_name_appendix, $onChangeClause, $tabindex, $tabindex_for_value, $idindex, $data, $special_chars, $foreignData, array($table, $db), $row_id, $titles, $text_dir, $special_chars_encoded, $vkey, $is_upload, $biggest_max_file_size, $default_char_editing, $no_support_types, $gis_data_types, $extracted_columnspec, $readOnly);
    }
    $html_output .= '</td>' . '</tr>';
    return $html_output;
}
Пример #8
0
/**
 * Prints javascript for upload with plugin, upload process bar
 *
 * @param int $upload_id The selected upload id
 *
 * @return string
 */
function PMA_getHtmlForImportWithPlugin($upload_id)
{
    //some variable for javascript
    $ajax_url = "import_status.php?id=" . $upload_id . "&" . URL::getCommonRaw(array('import_status' => 1));
    $promot_str = Sanitize::jsFormat(__('The file being uploaded is probably larger than ' . 'the maximum allowed size or this is a known bug in webkit ' . 'based (Safari, Google Chrome, Arora etc.) browsers.'), false);
    $statustext_str = Sanitize::escapeJsString(__('%s of %s'));
    $upload_str = Sanitize::jsFormat(__('Uploading your import file…'), false);
    $second_str = Sanitize::jsFormat(__('%s/sec.'), false);
    $remaining_min = Sanitize::jsFormat(__('About %MIN min. %SEC sec. remaining.'), false);
    $remaining_second = Sanitize::jsFormat(__('About %SEC sec. remaining.'), false);
    $processed_str = Sanitize::jsFormat(__('The file is being processed, please be patient.'), false);
    $import_url = URL::getCommonRaw(array('import_status' => 1));
    //start output
    $html = 'var finished = false; ';
    $html .= 'var percent  = 0.0; ';
    $html .= 'var total    = 0; ';
    $html .= 'var complete = 0; ';
    $html .= 'var original_title = ' . 'parent && parent.document ? parent.document.title : false; ';
    $html .= 'var import_start; ';
    $html .= 'var perform_upload = function () { ';
    $html .= 'new $.getJSON( ';
    $html .= '        "' . $ajax_url . '", ';
    $html .= '        {}, ';
    $html .= '        function(response) { ';
    $html .= '            finished = response.finished; ';
    $html .= '            percent = response.percent; ';
    $html .= '            total = response.total; ';
    $html .= '            complete = response.complete; ';
    $html .= '            if (total==0 && complete==0 && percent==0) { ';
    $img_tag = '<img src="' . $GLOBALS['pmaThemeImage'] . 'ajax_clock_small.gif"';
    $html .= '                $("#upload_form_status_info").html(\'' . $img_tag . ' width="16" height="16" alt="ajax clock" /> ' . $promot_str . '\'); ';
    $html .= '                $("#upload_form_status").css("display", "none"); ';
    $html .= '            } else { ';
    $html .= '                var now = new Date(); ';
    $html .= '                now = Date.UTC( ';
    $html .= '                    now.getFullYear(), ';
    $html .= '                    now.getMonth(), ';
    $html .= '                    now.getDate(), ';
    $html .= '                    now.getHours(), ';
    $html .= '                    now.getMinutes(), ';
    $html .= '                    now.getSeconds()) ';
    $html .= '                    + now.getMilliseconds() - 1000; ';
    $html .= '                var statustext = PMA_sprintf(';
    $html .= '                    "' . $statustext_str . '", ';
    $html .= '                    formatBytes( ';
    $html .= '                        complete, 1, PMA_messages.strDecimalSeparator';
    $html .= '                    ), ';
    $html .= '                    formatBytes(';
    $html .= '                        total, 1, PMA_messages.strDecimalSeparator';
    $html .= '                    ) ';
    $html .= '                ); ';
    $html .= '                if ($("#importmain").is(":visible")) { ';
    // show progress UI
    $html .= '                    $("#importmain").hide(); ';
    $html .= '                    $("#import_form_status") ';
    $html .= '                    .html(\'<div class="upload_progress">' . '<div class="upload_progress_bar_outer"><div class="percentage">' . '</div><div id="status" class="upload_progress_bar_inner">' . '<div class="percentage"></div></div></div><div>' . '<img src="' . $GLOBALS['pmaThemeImage'] . 'ajax_clock_small.gif" width="16" height="16" alt="ajax clock" /> ' . $upload_str . '</div><div id="statustext"></div></div>\') ';
    $html .= '                    .show(); ';
    $html .= '                    import_start = now; ';
    $html .= '                } ';
    $html .= '                else if (percent > 9 || complete > 2000000) { ';
    // calculate estimated time
    $html .= '                    var used_time = now - import_start; ';
    $html .= '                    var seconds = ' . 'parseInt(((total - complete) / complete) * used_time / 1000); ';
    $html .= '                    var speed = PMA_sprintf("' . $second_str . '"';
    $html .= '                       , formatBytes(complete / used_time * 1000, 1,' . ' PMA_messages.strDecimalSeparator)); ';
    $html .= '                    var minutes = parseInt(seconds / 60); ';
    $html .= '                    seconds %= 60; ';
    $html .= '                    var estimated_time; ';
    $html .= '                    if (minutes > 0) { ';
    $html .= '                        estimated_time = "' . $remaining_min . '"';
    $html .= '                            .replace("%MIN", minutes)';
    $html .= '                            .replace("%SEC", seconds); ';
    $html .= '                    } ';
    $html .= '                    else { ';
    $html .= '                        estimated_time = "' . $remaining_second . '"';
    $html .= '                        .replace("%SEC", seconds); ';
    $html .= '                    } ';
    $html .= '                    statustext += "<br />" + speed + "<br /><br />" ' . '+ estimated_time; ';
    $html .= '                } ';
    $html .= '                var percent_str = Math.round(percent) + "%"; ';
    $html .= '                $("#status").animate({width: percent_str}, 150); ';
    $html .= '                $(".percentage").text(percent_str); ';
    // show percent in window title
    $html .= '                if (original_title !== false) { ';
    $html .= '                    parent.document.title ';
    $html .= '                        = percent_str + " - " + original_title; ';
    $html .= '                } ';
    $html .= '                else { ';
    $html .= '                    document.title ';
    $html .= '                        = percent_str + " - " + original_title; ';
    $html .= '                } ';
    $html .= '                $("#statustext").html(statustext); ';
    $html .= '            }  ';
    $html .= '            if (finished == true) { ';
    $html .= '                if (original_title !== false) { ';
    $html .= '                    parent.document.title = original_title; ';
    $html .= '                } ';
    $html .= '                else { ';
    $html .= '                    document.title = original_title; ';
    $html .= '                } ';
    $html .= '                $("#importmain").hide(); ';
    // loads the message, either success or mysql error
    $html .= '                $("#import_form_status") ';
    $html .= '                .html(\'<img src="' . $GLOBALS['pmaThemeImage'] . 'ajax_clock_small.gif" width="16" height="16" alt="ajax clock" /> ' . $processed_str . '\')';
    $html .= '                .show(); ';
    $html .= '                $("#import_form_status").load("import_status.php?' . 'message=true&' . $import_url . '"); ';
    $html .= '                PMA_reloadNavigation(); ';
    // if finished
    $html .= '            } ';
    $html .= '            else { ';
    $html .= '              setTimeout(perform_upload, 1000); ';
    $html .= '         } ';
    $html .= '}); ';
    $html .= '}; ';
    $html .= 'setTimeout(perform_upload, 1000); ';
    return $html;
}
Пример #9
0
 /**
  * Provides search results row with browse/delete links.
  * (for a table)
  *
  * @param string  $each_table    One of the tables on which search was performed
  * @param array   $newsearchsqls Contains SQL queries
  * @param bool    $odd_row       For displaying contrasting table rows
  * @param integer $res_cnt       Number of results found
  *
  * @return string HTML row
  */
 private function _getResultsRow($each_table, $newsearchsqls, $odd_row, $res_cnt)
 {
     $this_url_params = array('db' => $GLOBALS['db'], 'table' => $each_table, 'goto' => 'db_sql.php', 'pos' => 0, 'is_js_confirmed' => 0);
     // Start forming search results row
     $html_output = '<tr class="noclick ' . ($odd_row ? 'odd' : 'even') . '">';
     // Displays results count for a table
     $html_output .= '<td>';
     $html_output .= sprintf(_ngettext('%1$s match in <strong>%2$s</strong>', '%1$s matches in <strong>%2$s</strong>', $res_cnt), $res_cnt, htmlspecialchars($each_table));
     $html_output .= '</td>';
     // Displays browse/delete link if result count > 0
     if ($res_cnt > 0) {
         $this_url_params['sql_query'] = $newsearchsqls['select_columns'];
         $browse_result_path = 'sql.php' . URL::getCommon($this_url_params);
         $html_output .= '<td><a name="browse_search" class="ajax" href="' . $browse_result_path . '" onclick="loadResult(\'' . $browse_result_path . '\',\'' . Sanitize::escapeJsString(htmlspecialchars($each_table)) . '\',\'' . URL::getCommon(array('db' => $GLOBALS['db'], 'table' => $each_table)) . '\'' . ');return false;" >' . __('Browse') . '</a></td>';
         $this_url_params['sql_query'] = $newsearchsqls['delete'];
         $delete_result_path = 'sql.php' . URL::getCommon($this_url_params);
         $html_output .= '<td><a name="delete_search" class="ajax" href="' . $delete_result_path . '" onclick="deleteResult(\'' . $delete_result_path . '\' , \'' . sprintf(__('Delete the matches for the %s table?'), htmlspecialchars($each_table)) . '\');return false;">' . __('Delete') . '</a></td>';
     } else {
         $html_output .= '<td>&nbsp;</td>' . '<td>&nbsp;</td>';
     }
     // end if else
     $html_output .= '</tr>';
     return $html_output;
 }
Пример #10
0
 /**
  * Renders the footer
  *
  * @return string
  */
 public function getDisplay()
 {
     $retval = '';
     $this->_setHistory();
     if ($this->_isEnabled) {
         if (!$this->_isAjax) {
             $retval .= "</div>";
         }
         if (!$this->_isAjax && !$this->_isMinimal) {
             if (PMA_getenv('SCRIPT_NAME') && empty($_POST) && empty($GLOBALS['checked_special']) && !$this->_isAjax) {
                 $url = $this->getSelfUrl();
                 $header = Response::getInstance()->getHeader();
                 $scripts = $header->getScripts()->getFiles();
                 $menuHash = $header->getMenu()->getHash();
                 // prime the client-side cache
                 $this->_scripts->addCode(sprintf('if (! (history && history.pushState)) ' . 'PMA_MicroHistory.primer = {' . ' url: "%s",' . ' scripts: %s,' . ' menuHash: "%s"' . '};', Sanitize::escapeJsString($url), json_encode($scripts), Sanitize::escapeJsString($menuHash)));
             }
             if (PMA_getenv('SCRIPT_NAME') && !$this->_isAjax) {
                 $url = $this->getSelfUrl();
                 $retval .= $this->_getSelfLink($url);
             }
             $this->_scripts->addCode('var debugSQLInfo = ' . $this->getDebugMessage() . ';');
             $retval .= '<div class="clearfloat" id="pma_errors">';
             $retval .= $this->getErrorMessages();
             $retval .= '</div>';
             $retval .= $this->_scripts->getDisplay();
             if ($GLOBALS['cfg']['DBG']['demo']) {
                 $retval .= '<div id="pma_demo">';
                 $retval .= $this->_getDemoMessage();
                 $retval .= '</div>';
             }
             // Include possible custom footers
             if (file_exists(CUSTOM_FOOTER_FILE)) {
                 $retval .= '<div id="pma_footer">';
                 ob_start();
                 include CUSTOM_FOOTER_FILE;
                 $retval .= ob_get_contents();
                 ob_end_clean();
                 $retval .= '</div>';
             }
         }
         if (!$this->_isAjax) {
             $retval .= "</body></html>";
         }
     }
     return $retval;
 }
 /**
  * Test for PMA_sendHeaderLocation
  *
  * @return void
  */
 public function testSendHeaderLocationIisLongUri()
 {
     $GLOBALS['PMA_Config']->set('PMA_IS_IIS', true);
     // over 600 chars
     $testUri = 'http://testurl.com/test.php?testlonguri=over600chars&test=test' . '&test=test&test=test&test=test&test=test&test=test&test=test' . '&test=test&test=test&test=test&test=test&test=test&test=test' . '&test=test&test=test&test=test&test=test&test=test&test=test' . '&test=test&test=test&test=test&test=test&test=test&test=test' . '&test=test&test=test&test=test&test=test&test=test&test=test' . '&test=test&test=test&test=test&test=test&test=test&test=test' . '&test=test&test=test&test=test&test=test&test=test&test=test' . '&test=test&test=test&test=test&test=test&test=test&test=test' . '&test=test&test=test&test=test&test=test&test=test&test=test' . '&test=test&test=test';
     $testUri_html = htmlspecialchars($testUri);
     $testUri_js = Sanitize::escapeJsString($testUri);
     $header = "<html><head><title>- - -</title>\n    <meta http-equiv=\"expires\" content=\"0\">" . "<meta http-equiv=\"Pragma\" content=\"no-cache\">" . "<meta http-equiv=\"Cache-Control\" content=\"no-cache\">" . "<meta http-equiv=\"Refresh\" content=\"0;url=" . $testUri_html . "\">" . "<script type=\"text/javascript\">//<![CDATA[\n        setTimeout(\"window.location = decodeURI('" . $testUri_js . "')\", 2000);\n        //]]></script></head>\n<body><script type=\"text/javascript\">//<![CDATA[\n    document.write('<p><a href=\"" . $testUri_html . "\">" . __('Go') . "</a></p>');\n    //]]></script></body></html>\n";
     $this->expectOutputString($header);
     $restoreInstance = PMA\libraries\Response::getInstance();
     $mockResponse = $this->getMockBuilder('PMA\\libraries\\Response')->disableOriginalConstructor()->setMethods(array('disable', 'header', 'headersSent'))->getMock();
     $mockResponse->expects($this->once())->method('disable');
     $mockResponse->expects($this->any())->method('headersSent')->with()->will($this->returnValue(false));
     $attrInstance = new ReflectionProperty('PMA\\libraries\\Response', '_instance');
     $attrInstance->setAccessible(true);
     $attrInstance->setValue($mockResponse);
     PMA_sendHeaderLocation($testUri);
     $attrInstance->setValue($restoreInstance);
 }
Пример #12
0
 /**
  * Sanitize::escapeJsString tests
  *
  * @param string $target expected output
  * @param string $source string to be escaped
  *
  * @return void
  *
  * @dataProvider escapeDataProvider
  */
 public function testEscapeJsString($target, $source)
 {
     $this->assertEquals($target, Sanitize::escapeJsString($source));
 }
Пример #13
0
 /**
  * Formats a value for javascript code.
  *
  * @param string $value String to be formatted.
  *
  * @return string formatted value.
  */
 public static function formatJsVal($value)
 {
     if (is_bool($value)) {
         if ($value) {
             return 'true';
         }
         return 'false';
     }
     if (is_int($value)) {
         return (int) $value;
     }
     return '"' . Sanitize::escapeJsString($value) . '"';
 }
Пример #14
0
 /**
  * Renders all the JavaScript file inclusions, code and events
  *
  * @return string
  */
 public function getDisplay()
 {
     $retval = '';
     if (count($this->_files) > 0) {
         $retval .= $this->_includeFiles($this->_files);
     }
     $code = 'AJAX.scriptHandler';
     foreach ($this->_files as $file) {
         $code .= sprintf('.add("%s",%d)', Sanitize::escapeJsString($file['filename']), $file['has_onload'] ? 1 : 0);
     }
     $code .= ';';
     $this->addCode($code);
     $code = '$(function() {';
     foreach ($this->_files as $file) {
         if ($file['has_onload']) {
             $code .= 'AJAX.fireOnload("';
             $code .= Sanitize::escapeJsString($file['filename']);
             $code .= '");';
         }
     }
     $code .= '});';
     $this->addCode($code);
     $retval .= '<script data-cfasync="false" type="text/javascript">';
     $retval .= "// <![CDATA[\n";
     $retval .= $this->_code;
     foreach ($this->_events as $js_event) {
         $retval .= sprintf("\$(window).bind('%s', %s);\n", $js_event['event'], $js_event['function']);
     }
     $retval .= '// ]]>';
     $retval .= '</script>';
     return $retval;
 }
Пример #15
0
<?php

/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
 * URL redirector to avoid leaking Referer with some sensitive information.
 *
 * @package PhpMyAdmin
 */
use PMA\libraries\Sanitize;
/**
 * Gets core libraries and defines some variables
 */
define('PMA_MINIMUM_COMMON', true);
require_once './libraries/common.inc.php';
if (!PMA_isValid($_REQUEST['url']) || !preg_match('/^https?:\\/\\/[^\\n\\r]*$/', $_REQUEST['url']) || !PMA_isAllowedDomain($_REQUEST['url'])) {
    header('Location: ./');
} else {
    // JavaScript redirection is necessary. Because if header() is used
    //  then web browser sometimes does not change the HTTP_REFERER
    //  field and so with old URL as Referer, token also goes to
    //  external site.
    echo "<script type='text/javascript'>\n            window.onload=function(){\n                window.location='", Sanitize::escapeJsString($_REQUEST['url']), "';\n            }\n        </script>";
    // Display redirecting msg on screen.
    // Do not display the value of $_REQUEST['url'] to avoid showing injected content
    echo __('Taking you to the target site.');
}
die;