form_utils.js 0000644 00000013673 14720707315 0007305 0 ustar 00 /** * form_utils.js * * Released under LGPL License. * Copyright (c) 1999-2017 Ephox Corp. All rights reserved * * License: http://www.tinymce.com/license * Contributing: http://www.tinymce.com/contributing */ var themeBaseURL = tinyMCEPopup.editor.baseURI.toAbsolute('themes/' + tinyMCEPopup.getParam("theme")); function getColorPickerHTML(id, target_form_element) { var h = "", dom = tinyMCEPopup.dom; if (label = dom.select('label[for=' + target_form_element + ']')[0]) { label.id = label.id || dom.uniqueId(); } h += ''; h += ' ' + tinyMCEPopup.getLang('browse') + ''; return h; } function updateColor(img_id, form_element_id) { document.getElementById(img_id).style.backgroundColor = document.forms[0].elements[form_element_id].value; } function setBrowserDisabled(id, state) { var img = document.getElementById(id); var lnk = document.getElementById(id + "_link"); if (lnk) { if (state) { lnk.setAttribute("realhref", lnk.getAttribute("href")); lnk.removeAttribute("href"); tinyMCEPopup.dom.addClass(img, 'disabled'); } else { if (lnk.getAttribute("realhref")) { lnk.setAttribute("href", lnk.getAttribute("realhref")); } tinyMCEPopup.dom.removeClass(img, 'disabled'); } } } function getBrowserHTML(id, target_form_element, type, prefix) { var option = prefix + "_" + type + "_browser_callback", cb, html; cb = tinyMCEPopup.getParam(option, tinyMCEPopup.getParam("file_browser_callback")); if (!cb) { return ""; } html = ""; html += ''; html += ' '; return html; } function openBrowser(img_id, target_form_element, type, option) { var img = document.getElementById(img_id); if (img.className != "mceButtonDisabled") { tinyMCEPopup.openBrowser(target_form_element, type, option); } } function selectByValue(form_obj, field_name, value, add_custom, ignore_case) { if (!form_obj || !form_obj.elements[field_name]) { return; } if (!value) { value = ""; } var sel = form_obj.elements[field_name]; var found = false; for (var i = 0; i < sel.options.length; i++) { var option = sel.options[i]; if (option.value == value || (ignore_case && option.value.toLowerCase() == value.toLowerCase())) { option.selected = true; found = true; } else { option.selected = false; } } if (!found && add_custom && value != '') { var option = new Option(value, value); option.selected = true; sel.options[sel.options.length] = option; sel.selectedIndex = sel.options.length - 1; } return found; } function getSelectValue(form_obj, field_name) { var elm = form_obj.elements[field_name]; if (elm == null || elm.options == null || elm.selectedIndex === -1) { return ""; } return elm.options[elm.selectedIndex].value; } function addSelectValue(form_obj, field_name, name, value) { var s = form_obj.elements[field_name]; var o = new Option(name, value); s.options[s.options.length] = o; } function addClassesToList(list_id, specific_option) { // Setup class droplist var styleSelectElm = document.getElementById(list_id); var styles = tinyMCEPopup.getParam('theme_advanced_styles', false); styles = tinyMCEPopup.getParam(specific_option, styles); if (styles) { var stylesAr = styles.split(';'); for (var i = 0; i < stylesAr.length; i++) { if (stylesAr != "") { var key, value; key = stylesAr[i].split('=')[0]; value = stylesAr[i].split('=')[1]; styleSelectElm.options[styleSelectElm.length] = new Option(key, value); } } } else { /*tinymce.each(tinyMCEPopup.editor.dom.getClasses(), function(o) { styleSelectElm.options[styleSelectElm.length] = new Option(o.title || o['class'], o['class']); });*/ } } function isVisible(element_id) { var elm = document.getElementById(element_id); return elm && elm.style.display != "none"; } function convertRGBToHex(col) { var re = new RegExp("rgb\\s*\\(\\s*([0-9]+).*,\\s*([0-9]+).*,\\s*([0-9]+).*\\)", "gi"); var rgb = col.replace(re, "$1,$2,$3").split(','); if (rgb.length == 3) { r = parseInt(rgb[0]).toString(16); g = parseInt(rgb[1]).toString(16); b = parseInt(rgb[2]).toString(16); r = r.length == 1 ? '0' + r : r; g = g.length == 1 ? '0' + g : g; b = b.length == 1 ? '0' + b : b; return "#" + r + g + b; } return col; } function convertHexToRGB(col) { if (col.indexOf('#') != -1) { col = col.replace(new RegExp('[^0-9A-F]', 'gi'), ''); r = parseInt(col.substring(0, 2), 16); g = parseInt(col.substring(2, 4), 16); b = parseInt(col.substring(4, 6), 16); return "rgb(" + r + "," + g + "," + b + ")"; } return col; } function trimSize(size) { return size.replace(/([0-9\.]+)(px|%|in|cm|mm|em|ex|pt|pc)/i, '$1$2'); } function getCSSSize(size) { size = trimSize(size); if (size == "") { return ""; } // Add px if (/^[0-9]+$/.test(size)) { size += 'px'; } // Confidence check, IE doesn't like broken values else if (!(/^[0-9\.]+(px|%|in|cm|mm|em|ex|pt|pc)$/i.test(size))) { return ""; } return size; } function getStyle(elm, attrib, style) { var val = tinyMCEPopup.dom.getAttrib(elm, attrib); if (val != '') { return '' + val; } if (typeof (style) == 'undefined') { style = attrib; } return tinyMCEPopup.dom.getStyle(elm, style); } editable_selects.js 0000644 00000004115 14720707315 0010404 0 ustar 00 /** * editable_selects.js * * Released under LGPL License. * Copyright (c) 1999-2017 Ephox Corp. All rights reserved * * License: http://www.tinymce.com/license * Contributing: http://www.tinymce.com/contributing */ var TinyMCE_EditableSelects = { editSelectElm : null, init : function () { var nl = document.getElementsByTagName("select"), i, d = document, o; for (i = 0; i < nl.length; i++) { if (nl[i].className.indexOf('mceEditableSelect') != -1) { o = new Option(tinyMCEPopup.editor.translate('value'), '__mce_add_custom__'); o.className = 'mceAddSelectValue'; nl[i].options[nl[i].options.length] = o; nl[i].onchange = TinyMCE_EditableSelects.onChangeEditableSelect; } } }, onChangeEditableSelect : function (e) { var d = document, ne, se = window.event ? window.event.srcElement : e.target; if (se.options[se.selectedIndex].value == '__mce_add_custom__') { ne = d.createElement("input"); ne.id = se.id + "_custom"; ne.name = se.name + "_custom"; ne.type = "text"; ne.style.width = se.offsetWidth + 'px'; se.parentNode.insertBefore(ne, se); se.style.display = 'none'; ne.focus(); ne.onblur = TinyMCE_EditableSelects.onBlurEditableSelectInput; ne.onkeydown = TinyMCE_EditableSelects.onKeyDown; TinyMCE_EditableSelects.editSelectElm = se; } }, onBlurEditableSelectInput : function () { var se = TinyMCE_EditableSelects.editSelectElm; if (se) { if (se.previousSibling.value != '') { addSelectValue(document.forms[0], se.id, se.previousSibling.value, se.previousSibling.value); selectByValue(document.forms[0], se.id, se.previousSibling.value); } else { selectByValue(document.forms[0], se.id, ''); } se.style.display = 'inline'; se.parentNode.removeChild(se.previousSibling); TinyMCE_EditableSelects.editSelectElm = null; } }, onKeyDown : function (e) { e = e || window.event; if (e.keyCode == 13) { TinyMCE_EditableSelects.onBlurEditableSelectInput(); } } }; validate.js 0000644 00000014502 14720707315 0006703 0 ustar 00 /** * validate.js * * Released under LGPL License. * Copyright (c) 1999-2017 Ephox Corp. All rights reserved * * License: http://www.tinymce.com/license * Contributing: http://www.tinymce.com/contributing */ /** // String validation: if (!Validator.isEmail('myemail')) alert('Invalid email.'); // Form validation: var f = document.forms['myform']; if (!Validator.isEmail(f.myemail)) alert('Invalid email.'); */ var Validator = { isEmail : function (s) { return this.test(s, '^[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+@[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+\.[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+$'); }, isAbsUrl : function (s) { return this.test(s, '^(news|telnet|nttp|file|http|ftp|https)://[-A-Za-z0-9\\.]+\\/?.*$'); }, isSize : function (s) { return this.test(s, '^[0-9.]+(%|in|cm|mm|em|ex|pt|pc|px)?$'); }, isId : function (s) { return this.test(s, '^[A-Za-z_]([A-Za-z0-9_])*$'); }, isEmpty : function (s) { var nl, i; if (s.nodeName == 'SELECT' && s.selectedIndex < 1) { return true; } if (s.type == 'checkbox' && !s.checked) { return true; } if (s.type == 'radio') { for (i = 0, nl = s.form.elements; i < nl.length; i++) { if (nl[i].type == "radio" && nl[i].name == s.name && nl[i].checked) { return false; } } return true; } return new RegExp('^\\s*$').test(s.nodeType == 1 ? s.value : s); }, isNumber : function (s, d) { return !isNaN(s.nodeType == 1 ? s.value : s) && (!d || !this.test(s, '^-?[0-9]*\\.[0-9]*$')); }, test : function (s, p) { s = s.nodeType == 1 ? s.value : s; return s == '' || new RegExp(p).test(s); } }; var AutoValidator = { settings : { id_cls : 'id', int_cls : 'int', url_cls : 'url', number_cls : 'number', email_cls : 'email', size_cls : 'size', required_cls : 'required', invalid_cls : 'invalid', min_cls : 'min', max_cls : 'max' }, init : function (s) { var n; for (n in s) { this.settings[n] = s[n]; } }, validate : function (f) { var i, nl, s = this.settings, c = 0; nl = this.tags(f, 'label'); for (i = 0; i < nl.length; i++) { this.removeClass(nl[i], s.invalid_cls); nl[i].setAttribute('aria-invalid', false); } c += this.validateElms(f, 'input'); c += this.validateElms(f, 'select'); c += this.validateElms(f, 'textarea'); return c == 3; }, invalidate : function (n) { this.mark(n.form, n); }, getErrorMessages : function (f) { var nl, i, s = this.settings, field, msg, values, messages = [], ed = tinyMCEPopup.editor; nl = this.tags(f, "label"); for (i = 0; i < nl.length; i++) { if (this.hasClass(nl[i], s.invalid_cls)) { field = document.getElementById(nl[i].getAttribute("for")); values = { field: nl[i].textContent }; if (this.hasClass(field, s.min_cls, true)) { message = ed.getLang('invalid_data_min'); values.min = this.getNum(field, s.min_cls); } else if (this.hasClass(field, s.number_cls)) { message = ed.getLang('invalid_data_number'); } else if (this.hasClass(field, s.size_cls)) { message = ed.getLang('invalid_data_size'); } else { message = ed.getLang('invalid_data'); } message = message.replace(/{\#([^}]+)\}/g, function (a, b) { return values[b] || '{#' + b + '}'; }); messages.push(message); } } return messages; }, reset : function (e) { var t = ['label', 'input', 'select', 'textarea']; var i, j, nl, s = this.settings; if (e == null) { return; } for (i = 0; i < t.length; i++) { nl = this.tags(e.form ? e.form : e, t[i]); for (j = 0; j < nl.length; j++) { this.removeClass(nl[j], s.invalid_cls); nl[j].setAttribute('aria-invalid', false); } } }, validateElms : function (f, e) { var nl, i, n, s = this.settings, st = true, va = Validator, v; nl = this.tags(f, e); for (i = 0; i < nl.length; i++) { n = nl[i]; this.removeClass(n, s.invalid_cls); if (this.hasClass(n, s.required_cls) && va.isEmpty(n)) { st = this.mark(f, n); } if (this.hasClass(n, s.number_cls) && !va.isNumber(n)) { st = this.mark(f, n); } if (this.hasClass(n, s.int_cls) && !va.isNumber(n, true)) { st = this.mark(f, n); } if (this.hasClass(n, s.url_cls) && !va.isAbsUrl(n)) { st = this.mark(f, n); } if (this.hasClass(n, s.email_cls) && !va.isEmail(n)) { st = this.mark(f, n); } if (this.hasClass(n, s.size_cls) && !va.isSize(n)) { st = this.mark(f, n); } if (this.hasClass(n, s.id_cls) && !va.isId(n)) { st = this.mark(f, n); } if (this.hasClass(n, s.min_cls, true)) { v = this.getNum(n, s.min_cls); if (isNaN(v) || parseInt(n.value) < parseInt(v)) { st = this.mark(f, n); } } if (this.hasClass(n, s.max_cls, true)) { v = this.getNum(n, s.max_cls); if (isNaN(v) || parseInt(n.value) > parseInt(v)) { st = this.mark(f, n); } } } return st; }, hasClass : function (n, c, d) { return new RegExp('\\b' + c + (d ? '[0-9]+' : '') + '\\b', 'g').test(n.className); }, getNum : function (n, c) { c = n.className.match(new RegExp('\\b' + c + '([0-9]+)\\b', 'g'))[0]; c = c.replace(/[^0-9]/g, ''); return c; }, addClass : function (n, c, b) { var o = this.removeClass(n, c); n.className = b ? c + (o !== '' ? (' ' + o) : '') : (o !== '' ? (o + ' ') : '') + c; }, removeClass : function (n, c) { c = n.className.replace(new RegExp("(^|\\s+)" + c + "(\\s+|$)"), ' '); return n.className = c !== ' ' ? c : ''; }, tags : function (f, s) { return f.getElementsByTagName(s); }, mark : function (f, n) { var s = this.settings; this.addClass(n, s.invalid_cls); n.setAttribute('aria-invalid', 'true'); this.markLabels(f, n, s.invalid_cls); return false; }, markLabels : function (f, n, ic) { var nl, i; nl = this.tags(f, "label"); for (i = 0; i < nl.length; i++) { if (nl[i].getAttribute("for") == n.id || nl[i].htmlFor == n.id) { this.addClass(nl[i], ic); } } return null; } }; mctabs.js 0000644 00000010100 14720707315 0006351 0 ustar 00 /** * mctabs.js * * Released under LGPL License. * Copyright (c) 1999-2017 Ephox Corp. All rights reserved * * License: http://www.tinymce.com/license * Contributing: http://www.tinymce.com/contributing */ /*jshint globals: tinyMCEPopup */ function MCTabs() { this.settings = []; this.onChange = tinyMCEPopup.editor.windowManager.createInstance('tinymce.util.Dispatcher'); } MCTabs.prototype.init = function (settings) { this.settings = settings; }; MCTabs.prototype.getParam = function (name, default_value) { var value = null; value = (typeof (this.settings[name]) == "undefined") ? default_value : this.settings[name]; // Fix bool values if (value == "true" || value == "false") { return (value == "true"); } return value; }; MCTabs.prototype.showTab = function (tab) { tab.className = 'current'; tab.setAttribute("aria-selected", true); tab.setAttribute("aria-expanded", true); tab.tabIndex = 0; }; MCTabs.prototype.hideTab = function (tab) { var t = this; tab.className = ''; tab.setAttribute("aria-selected", false); tab.setAttribute("aria-expanded", false); tab.tabIndex = -1; }; MCTabs.prototype.showPanel = function (panel) { panel.className = 'current'; panel.setAttribute("aria-hidden", false); }; MCTabs.prototype.hidePanel = function (panel) { panel.className = 'panel'; panel.setAttribute("aria-hidden", true); }; MCTabs.prototype.getPanelForTab = function (tabElm) { return tinyMCEPopup.dom.getAttrib(tabElm, "aria-controls"); }; MCTabs.prototype.displayTab = function (tab_id, panel_id, avoid_focus) { var panelElm, panelContainerElm, tabElm, tabContainerElm, selectionClass, nodes, i, t = this; tabElm = document.getElementById(tab_id); if (panel_id === undefined) { panel_id = t.getPanelForTab(tabElm); } panelElm = document.getElementById(panel_id); panelContainerElm = panelElm ? panelElm.parentNode : null; tabContainerElm = tabElm ? tabElm.parentNode : null; selectionClass = t.getParam('selection_class', 'current'); if (tabElm && tabContainerElm) { nodes = tabContainerElm.childNodes; // Hide all other tabs for (i = 0; i < nodes.length; i++) { if (nodes[i].nodeName == "LI") { t.hideTab(nodes[i]); } } // Show selected tab t.showTab(tabElm); } if (panelElm && panelContainerElm) { nodes = panelContainerElm.childNodes; // Hide all other panels for (i = 0; i < nodes.length; i++) { if (nodes[i].nodeName == "DIV") { t.hidePanel(nodes[i]); } } if (!avoid_focus) { tabElm.focus(); } // Show selected panel t.showPanel(panelElm); } }; MCTabs.prototype.getAnchor = function () { var pos, url = document.location.href; if ((pos = url.lastIndexOf('#')) != -1) { return url.substring(pos + 1); } return ""; }; //Global instance var mcTabs = new MCTabs(); tinyMCEPopup.onInit.add(function () { var tinymce = tinyMCEPopup.getWin().tinymce, dom = tinyMCEPopup.dom, each = tinymce.each; each(dom.select('div.tabs'), function (tabContainerElm) { //var keyNav; dom.setAttrib(tabContainerElm, "role", "tablist"); var items = tinyMCEPopup.dom.select('li', tabContainerElm); var action = function (id) { mcTabs.displayTab(id, mcTabs.getPanelForTab(id)); mcTabs.onChange.dispatch(id); }; each(items, function (item) { dom.setAttrib(item, 'role', 'tab'); dom.bind(item, 'click', function (evt) { action(item.id); }); }); dom.bind(dom.getRoot(), 'keydown', function (evt) { if (evt.keyCode === 9 && evt.ctrlKey && !evt.altKey) { // Tab //keyNav.moveFocus(evt.shiftKey ? -1 : 1); tinymce.dom.Event.cancel(evt); } }); each(dom.select('a', tabContainerElm), function (a) { dom.setAttrib(a, 'tabindex', '-1'); }); /*keyNav = tinyMCEPopup.editor.windowManager.createInstance('tinymce.ui.KeyboardNavigation', { root: tabContainerElm, items: items, onAction: action, actOnFocus: true, enableLeftRight: true, enableUpDown: true }, tinyMCEPopup.dom);*/ } ); }); svg/svg-sanitizer.php 0000644 00000034403 14720725675 0010704 0 ustar 00 is_encoded( $original_content ); if ( $is_encoded ) { $decoded = $this->decode_svg( $original_content ); if ( false === $decoded ) { return false; } $original_content = $decoded; } $valid_svg = $this->sanitize( $original_content ); if ( false === $valid_svg ) { return false; } // If we were gzipped, we need to re-zip if ( $is_encoded ) { $valid_svg = $this->encode_svg( $valid_svg ); } file_put_contents( $filename, $valid_svg ); return true; } /** * Sanitize * * @since 3.16.0 * @access public * * @param $content * @return bool|string */ public function sanitize( $content ) { // Strip php tags $content = $this->strip_comments( $content ); $content = $this->strip_php_tags( $content ); $content = $this->strip_line_breaks( $content ); // Find the start and end tags so we can cut out miscellaneous garbage. $start = strpos( $content, '' ); if ( false === $start || false === $end ) { return false; } $content = substr( $content, $start, ( $end - $start + 6 ) ); // If the server's PHP version is 8 or up, make sure to Disable the ability to load external entities $php_version_under_eight = version_compare( PHP_VERSION, '8.0.0', '<' ); if ( $php_version_under_eight ) { $libxml_disable_entity_loader = libxml_disable_entity_loader( true ); // phpcs:ignore Generic.PHP.DeprecatedFunctions.Deprecated } // Suppress the errors $libxml_use_internal_errors = libxml_use_internal_errors( true ); // Create DomDocument instance $this->svg_dom = new \DOMDocument(); $this->svg_dom->formatOutput = false; $this->svg_dom->preserveWhiteSpace = false; $this->svg_dom->strictErrorChecking = false; $open_svg = $this->svg_dom->loadXML( $content ); if ( ! $open_svg ) { return false; } $this->strip_doctype(); $this->sanitize_elements(); // Export sanitized svg to string // Using documentElement to strip out svg_dom->saveXML( $this->svg_dom->documentElement, LIBXML_NOEMPTYTAG ); // Restore defaults if ( $php_version_under_eight ) { libxml_disable_entity_loader( $libxml_disable_entity_loader ); // phpcs:ignore Generic.PHP.DeprecatedFunctions.Deprecated } libxml_use_internal_errors( $libxml_use_internal_errors ); return $sanitized; } /** * Is Encoded * * Check if the contents of the SVG file are gzipped * @see http://www.gzip.org/zlib/rfc-gzip.html#member-format * * @since 3.16.0 * @access private * * @param $contents * * @return bool */ private function is_encoded( $contents ) { $needle = "\x1f\x8b\x08"; if ( function_exists( 'mb_strpos' ) ) { return 0 === mb_strpos( $contents, $needle ); } else { return 0 === strpos( $contents, $needle ); } } /** * Encode SVG * * @since 3.16.0 * @access private * * @param $content * @return string */ private function encode_svg( $content ) { return gzencode( $content ); } /** * Decode SVG * * @since 3.16.0 * @access private * * @param $content * * @return string */ private function decode_svg( $content ) { return gzdecode( $content ); } /** * Is Allowed Tag * * @since 3.16.0 * @access private * * @param $element * @return bool */ private function is_allowed_tag( $element ) { static $allowed_tags = false; if ( false === $allowed_tags ) { $allowed_tags = $this->get_allowed_elements(); } $tag_name = $element->tagName; // phpcs:ignore -- php DomDocument if ( ! in_array( strtolower( $tag_name ), $allowed_tags ) ) { $this->remove_element( $element ); return false; } return true; } /** * Remove Element * * Removes the passed element from its DomDocument tree * * @since 3.16.0 * @access private * * @param $element */ private function remove_element( $element ) { $element->parentNode->removeChild( $element ); // phpcs:ignore -- php DomDocument } /** * Is It An Attribute * * @since 3.16.0 * @access private * * @param $name * @param $check * @return bool */ private function is_a_attribute( $name, $check ) { return 0 === strpos( $name, $check . '-' ); } /** * Is Remote Value * * @since 3.16.0 * @access private * * @param $value * @return string */ private function is_remote_value( $value ) { $value = trim( preg_replace( '/[^ -~]/xu', '', $value ) ); $wrapped_in_url = preg_match( '~^url\(\s*[\'"]\s*(.*)\s*[\'"]\s*\)$~xi', $value, $match ); if ( ! $wrapped_in_url ) { return false; } $value = trim( $match[1], '\'"' ); return preg_match( '~^((https?|ftp|file):)?//~xi', $value ); } /** * Has JS Value * * @since 3.16.0 * @access private * * @param $value * @return false|int */ private function has_js_value( $value ) { return preg_match( '/base64|data|(?:java)?script|alert\(|window\.|document/i', $value ); } /** * Get Allowed Attributes * * Returns an array of allowed tag attributes in SVG files. * * @since 3.16.0 * @access private * * @return array */ private function get_allowed_attributes() { $allowed_attributes = [ 'class', 'clip-path', 'clip-rule', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'id', 'mask', 'opacity', 'stroke', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'style', 'systemlanguage', 'transform', 'href', 'xlink:href', 'xlink:title', 'cx', 'cy', 'r', 'requiredfeatures', 'clippathunits', 'type', 'rx', 'ry', 'color-interpolation-filters', 'stddeviation', 'filterres', 'filterunits', 'height', 'primitiveunits', 'width', 'x', 'y', 'font-size', 'display', 'font-family', 'font-style', 'font-weight', 'text-anchor', 'marker-end', 'marker-mid', 'marker-start', 'x1', 'x2', 'y1', 'y2', 'gradienttransform', 'gradientunits', 'spreadmethod', 'markerheight', 'markerunits', 'markerwidth', 'orient', 'preserveaspectratio', 'refx', 'refy', 'viewbox', 'maskcontentunits', 'maskunits', 'd', 'patterncontentunits', 'patterntransform', 'patternunits', 'points', 'fx', 'fy', 'offset', 'stop-color', 'stop-opacity', 'xmlns', 'xmlns:se', 'xmlns:xlink', 'xml:space', 'method', 'spacing', 'startoffset', 'dx', 'dy', 'rotate', 'textlength', ]; /** * Allowed attributes in SVG file. * * Filters the list of allowed attributes in SVG files. * * Since SVG files can run JS code that may inject malicious code, all attributes * are removed except the allowed attributes. * * This hook can be used to manage allowed SVG attributes. To either add new * attributes or delete existing attributes. To strengthen or weaken site security. * * @param array $allowed_attributes A list of allowed attributes. */ $allowed_attributes = apply_filters( 'elementor/files/svg/allowed_attributes', $allowed_attributes ); return $allowed_attributes; } /** * Get Allowed Elements * * Returns an array of allowed element tags to be in SVG files. * * @since 3.16.0 * @access private * * @return array */ private function get_allowed_elements() { $allowed_elements = [ 'a', 'circle', 'clippath', 'defs', 'style', 'desc', 'ellipse', 'fegaussianblur', 'filter', 'foreignobject', 'g', 'image', 'line', 'lineargradient', 'marker', 'mask', 'metadata', 'path', 'pattern', 'polygon', 'polyline', 'radialgradient', 'rect', 'stop', 'svg', 'switch', 'symbol', 'text', 'textpath', 'title', 'tspan', 'use', ]; /** * Allowed elements in SVG file. * * Filters the list of allowed elements in SVG files. * * Since SVG files can run JS code that may inject malicious code, all elements * are removed except the allowed elements. * * This hook can be used to manage SVG elements. To either add new elements or * delete existing elements. To strengthen or weaken site security. * * @param array $allowed_elements A list of allowed elements. */ $allowed_elements = apply_filters( 'elementor/files/svg/allowed_elements', $allowed_elements ); return $allowed_elements; } /** * Validate Allowed Attributes * * @since 3.16.0 * @access private * * @param \DOMElement $element */ private function validate_allowed_attributes( $element ) { static $allowed_attributes = false; if ( false === $allowed_attributes ) { $allowed_attributes = $this->get_allowed_attributes(); } for ( $index = $element->attributes->length - 1; $index >= 0; $index-- ) { // get attribute name $attr_name = $element->attributes->item( $index )->name; $attr_name_lowercase = strtolower( $attr_name ); // Remove attribute if not in whitelist if ( ! in_array( $attr_name_lowercase, $allowed_attributes ) && ! $this->is_a_attribute( $attr_name_lowercase, 'aria' ) && ! $this->is_a_attribute( $attr_name_lowercase, 'data' ) ) { $element->removeAttribute( $attr_name ); continue; } $attr_value = $element->attributes->item( $index )->value; // Remove attribute if it has a remote reference or js or data-URI/base64 if ( ! empty( $attr_value ) && ( $this->is_remote_value( $attr_value ) || $this->has_js_value( $attr_value ) ) ) { $element->removeAttribute( $attr_name ); continue; } } } /** * Strip xlinks * * @since 3.16.0 * @access private * * @param \DOMElement $element */ private function strip_xlinks( $element ) { $xlinks = $element->getAttributeNS( 'http://www.w3.org/1999/xlink', 'href' ); if ( ! $xlinks ) { return; } if ( ! $this->is_safe_href( $xlinks ) ) { $element->removeAttributeNS( 'http://www.w3.org/1999/xlink', 'href' ); } } /** * @see https://github.com/darylldoyle/svg-sanitizer/blob/2321a914e/src/Sanitizer.php#L454 */ private function is_safe_href( $value ) { // Allow empty values. if ( empty( $value ) ) { return true; } // Allow fragment identifiers. if ( '#' === substr( $value, 0, 1 ) ) { return true; } // Allow relative URIs. if ( '/' === substr( $value, 0, 1 ) ) { return true; } // Allow HTTPS domains. if ( 'https://' === substr( $value, 0, 8 ) ) { return true; } // Allow HTTP domains. if ( 'http://' === substr( $value, 0, 7 ) ) { return true; } // Allow known data URIs. if ( in_array( substr( $value, 0, 14 ), [ 'data:image/png', // PNG 'data:image/gif', // GIF 'data:image/jpg', // JPG 'data:image/jpe', // JPEG 'data:image/pjp', // PJPEG ], true ) ) { return true; } // Allow known short data URIs. if ( in_array( substr( $value, 0, 12 ), [ 'data:img/png', // PNG 'data:img/gif', // GIF 'data:img/jpg', // JPG 'data:img/jpe', // JPEG 'data:img/pjp', // PJPEG ], true ) ) { return true; } return false; } /** * Validate Use Tag * * @since 3.16.0 * @access private * * @param $element */ private function validate_use_tag( $element ) { $xlinks = $element->getAttributeNS( 'http://www.w3.org/1999/xlink', 'href' ); if ( $xlinks && '#' !== substr( $xlinks, 0, 1 ) ) { $element->parentNode->removeChild( $element ); // phpcs:ignore -- php DomNode } } /** * Strip Doctype * * @since 3.16.0 * @access private * */ private function strip_doctype() { foreach ( $this->svg_dom->childNodes as $child ) { if ( XML_DOCUMENT_TYPE_NODE === $child->nodeType ) { // phpcs:ignore -- php DomDocument $child->parentNode->removeChild( $child ); // phpcs:ignore -- php DomDocument } } } /** * Sanitize Elements * * @since 3.16.0 * @access private */ private function sanitize_elements() { $elements = $this->svg_dom->getElementsByTagName( '*' ); // loop through all elements // we do this backwards so we don't skip anything if we delete a node // see comments at: http://php.net/manual/en/class.domnamednodemap.php for ( $index = $elements->length - 1; $index >= 0; $index-- ) { /** * @var \DOMElement $current_element */ $current_element = $elements->item( $index ); // If the tag isn't in the whitelist, remove it and continue with next iteration if ( ! $this->is_allowed_tag( $current_element ) ) { continue; } //validate element attributes $this->validate_allowed_attributes( $current_element ); $this->strip_xlinks( $current_element ); if ( 'use' === strtolower( $current_element->tagName ) ) { // phpcs:ignore -- php DomDocument $this->validate_use_tag( $current_element ); } } } /** * Strip PHP Tags * * @since 3.16.0 * @access private * * @param $string * @return string */ private function strip_php_tags( $string ) { $string = preg_replace( '/<\?(=|php)(.+?)\?>/i', '', $string ); // Remove XML, ASP, etc. $string = preg_replace( '/<\?(.*)\?>/Us', '', $string ); $string = preg_replace( '/<\%(.*)\%>/Us', '', $string ); if ( ( false !== strpos( $string, '' ) ) || ( false !== strpos( $string, '<%' ) ) ) { return ''; } return $string; } /** * Strip Comments * * @since 3.16.0 * @access private * * @param $string * @return string */ private function strip_comments( $string ) { // Remove comments. $string = preg_replace( '//Us', '', $string ); $string = preg_replace( '/\/\*(.*)\*\//Us', '', $string ); if ( ( false !== strpos( $string, ' $generator $rss_info_name $rss_info_url $rss_info_description $pub_date $rss_info_language $wxr_version $wxr_site_url $rss_info_url $page_on_front_xml $dynamic EOT; return $result; } public function __construct( array $args = [] ) { global $wpdb; $this->args = wp_parse_args( $args, self::$default_args ); $this->wpdb = $wpdb; } } assets-translation-loader.php 0000644 00000004774 14720725675 0012412 0 ustar 00 registered[ $handle ]->src; }, $handles ); } private static function default_replace_translation( $relative_path ) { // Translations are always based on the non-minified filename. $relative_path_without_ext = preg_replace( '/(\.min)?\.js$/i', '', $relative_path ); // By default, we suffix the file with `.strings` (e.g 'assets/js/editor.js' => 'assets/js/editor.strings.js'). return implode( '.', [ $relative_path_without_ext, 'strings', 'js', ] ); } } http.php 0000644 00000001725 14720725675 0006260 0 ustar 00 request( $url, $args ); if ( $this->is_successful_response( $response ) ) { return $response; } } return $response; } /** * @param $response * * @return bool */ private function is_successful_response( $response ) { if ( is_wp_error( $response ) ) { return false; } $response_code = (int) wp_remote_retrieve_response_code( $response ); if ( in_array( $response_code, [ 0, 404, 500 ], true ) ) { return false; } return true; } } force-locale.php 0000644 00000007070 14720725675 0007633 0 ustar 00 new_locale = $new_locale; $this->original_locale = $original_locale ? $original_locale : determine_locale(); $this->filter = function() use ( $new_locale ) { return $new_locale; }; } /** * Force the translations to use a specific locale. * * @return void */ public function force() { switch_to_locale( $this->new_locale ); /** * Reset the \WP_Textdomain_Registry instance to clear its cache. * * @see https://github.com/WordPress/wordpress-develop/blob/799d7dc86f5b07b17f7a418948fc851bd2fc334b/src/wp-includes/class-wp-textdomain-registry.php#L179-L187 * @see https://github.com/WordPress/wordpress-develop/blob/799d7dc86f5b07b17f7a418948fc851bd2fc334b/tests/phpunit/tests/l10n/wpLocaleSwitcher.php#L19-L31 */ $this->reset_textdomain_registry(); /** * Reset l10n in order to clear the translations cache. * * @see https://github.com/WordPress/wordpress-develop/blob/2437ef5130f10153bc4fffa412d4f37e65e3d66b/src/wp-includes/l10n.php#L1324 * @see https://github.com/WordPress/wordpress-develop/blob/2437ef5130f10153bc4fffa412d4f37e65e3d66b/src/wp-includes/l10n.php#L1222 * @see https://github.com/WordPress/wordpress-develop/blob/2437ef5130f10153bc4fffa412d4f37e65e3d66b/src/wp-includes/l10n.php#L821 */ $this->reset_l10n(); /** * Force the translations of `$new_locale` to be loaded. * * @see https://github.com/WordPress/wordpress-develop/blob/2437ef5130f10153bc4fffa412d4f37e65e3d66b/src/wp-includes/l10n.php#L1294 */ add_filter( 'pre_determine_locale', $this->filter ); } /** * Restore the original locale and cleanup filters, etc. * * @return void */ public function restore() { $this->restore_textdomain_registry(); $this->reset_l10n(); switch_to_locale( $this->original_locale ); remove_filter( 'pre_determine_locale', $this->filter ); } private function reset_textdomain_registry() { if ( ! class_exists( '\WP_Textdomain_Registry' ) ) { return; } /** @var \WP_Textdomain_Registry $wp_textdomain_registry */ global $wp_textdomain_registry; $this->original_textdomain_registry = $wp_textdomain_registry; $wp_textdomain_registry = new \WP_Textdomain_Registry(); } private function restore_textdomain_registry() { if ( ! $this->original_textdomain_registry ) { return; } /** @var \WP_Textdomain_Registry $wp_textdomain_registry */ global $wp_textdomain_registry; $wp_textdomain_registry = $this->original_textdomain_registry; } /** * Reset the l10n global variables. * * @return void */ private function reset_l10n() { global $l10n, $l10n_unloaded; if ( is_array( $l10n ) ) { foreach ( $l10n as $domain => $l10n_data ) { unset( $l10n[ $domain ] ); } } if ( is_array( $l10n_unloaded ) ) { foreach ( $l10n_unloaded as $domain => $l10n_unloaded_data ) { unset( $l10n_unloaded[ $domain ] ); } } } } hints.php 0000644 00000023266 14720725675 0006432 0 ustar 00 [ self::DISMISSED => 'image-optimization-once', self::CAPABILITY => 'install_plugins', self::DEFINED => 'IMAGE_OPTIMIZATION_VERSION', ], 'image-optimization-once-media-modal' => [ self::DISMISSED => 'image-optimization-once-media-modal', self::CAPABILITY => 'install_plugins', self::DEFINED => 'IMAGE_OPTIMIZATION_VERSION', ], 'image-optimization' => [ self::DISMISSED => 'image_optimizer_hint', self::CAPABILITY => 'install_plugins', self::DEFINED => 'IMAGE_OPTIMIZATION_VERSION', ], 'image-optimization-media-modal' => [ self::DISMISSED => 'image-optimization-media-modal', self::CAPABILITY => 'install_plugins', self::DEFINED => 'IMAGE_OPTIMIZATION_VERSION', ], ]; if ( ! $hint_key ) { return $hints; } return $hints[ $hint_key ] ?? []; } /** * get_notice_icon * @return string */ public static function get_notice_icon(): string { return ' '; } /** * get_notice_template * * Print or Retrieve the notice template. * @param array $notice * @param bool $return * * @return string|void */ public static function get_notice_template( array $notice, bool $return = false ) { $default_settings = [ 'type' => 'info', 'icon' => false, 'heading' => '', 'content' => '', 'dismissible' => false, 'button_text' => '', 'button_event' => '', 'button_data' => [], 'display' => false, ]; $notice_settings = array_merge( $default_settings, $notice ); if ( empty( $notice_settings['heading'] ) && empty( $notice_settings['content'] ) ) { return ''; } if ( ! in_array( $notice_settings['type'], self::get_notice_types(), true ) ) { $notice_settings['type'] = 'info'; } $icon = ''; $heading = ''; $content = ''; $dismissible = ''; $button = ''; if ( $notice_settings['icon'] ) { $icon = self::get_notice_icon(); } if ( ! empty( $notice_settings['heading'] ) ) { $heading = '' . $notice_settings['heading'] . ''; } if ( ! empty( $notice_settings['content'] ) ) { $content = '' . $notice_settings['content'] . ''; } if ( ! empty( $notice_settings['button_text'] ) ) { $button_settings = ( ! empty( $notice_settings['button_data'] ) ) ? ' data-settings="' . esc_attr( json_encode( $notice_settings['button_data'] ) ) . '"' : ''; $button = ' ' . $notice_settings['button_text'] . ' '; } if ( $notice_settings['dismissible'] ) { $dismissible = ' ' . esc_html__( 'Don’t show again.', 'elementor' ) . ' '; } $notice_template = sprintf( ' %2$s %3$s %4$s %5$s %6$s ', $notice_settings['type'], $icon, $heading, $content, $button, $dismissible, $notice_settings['display'] ); if ( $return ) { return $notice_template; } echo wp_kses( $notice_template, self::get_notice_allowed_html() ); } /** * get_plugin_install_url * @param $plugin_slug * * @return string */ public static function get_plugin_install_url( $plugin_slug ): string { $action = 'install-plugin'; return wp_nonce_url( add_query_arg( [ 'action' => $action, 'plugin' => $plugin_slug, ], admin_url( 'update.php' ) ), $action . '_' . $plugin_slug ); } /** * get_plugin_activate_url * @param $plugin_slug * * @return string */ public static function get_plugin_activate_url( $plugin_slug ): string { $path = "$plugin_slug/$plugin_slug.php"; return wp_nonce_url( admin_url( 'plugins.php?action=activate&plugin=' . $path ), 'activate-plugin_' . $path ); } /** * is_dismissed * @param $key * * @return bool */ public static function is_dismissed( $key ): bool { $dismissed = User::get_dismissed_editor_notices(); return in_array( $key, $dismissed, true ); } /** * should_display_hint * @param $hint_key * * @return bool */ public static function should_display_hint( $hint_key ): bool { $hint = self::get_hints( $hint_key ); if ( empty( $hint ) ) { return false; } foreach ( $hint as $key => $value ) { switch ( $key ) { case self::DISMISSED: if ( self::is_dismissed( $value ) ) { return false; } break; case self::CAPABILITY: if ( ! current_user_can( $value ) ) { return false; } break; case self::DEFINED: if ( defined( $value ) ) { return false; } break; case self::PLUGIN_INSTALLED: if ( ! self::is_plugin_installed( $value ) ) { return false; } break; case self::PLUGIN_ACTIVE: if ( ! self::is_plugin_active( $value ) ) { return false; } break; } } return true; } private static function is_conflict_plugin_installed(): bool { if ( ! Utils::has_pro() ) { return false; } $conflicting_plugins = [ 'imagify/imagify.php', 'optimole-wp/optimole-wp.php', 'ewww-image-optimizer/ewww-image-optimizer.php', 'ewww-image-optimizer-cloud/ewww-image-optimizer-cloud.php', 'kraken-image-optimizer/kraken.php', 'shortpixel-image-optimiser/wp-shortpixel.php', 'wp-smushit/wp-smush.php', 'wp-smush-pro/wp-smush.php', 'tiny-compress-images/tiny-compress-images.php', ]; foreach ( $conflicting_plugins as $plugin ) { if ( self::is_plugin_active( $plugin ) ) { return true; } } return false; } /** * is_plugin_installed * @param $plugin * * @return bool */ public static function is_plugin_installed( $plugin ) : bool { $plugins = get_plugins(); $plugin = self::ensure_plugin_folder( $plugin ); return ! empty( $plugins[ $plugin ] ); } /** * is_plugin_active * @param $plugin * * @return bool */ public static function is_plugin_active( $plugin ): bool { $plugin = self::ensure_plugin_folder( $plugin ); return is_plugin_active( $plugin ); } /** * get_plugin_action_url * @param $plugin * * @return string */ public static function get_plugin_action_url( $plugin ): string { if ( ! self::is_plugin_installed( $plugin ) ) { return self::get_plugin_install_url( $plugin ); } if ( ! self::is_plugin_active( $plugin ) ) { return self::get_plugin_activate_url( $plugin ); } return ''; } /** * ensure_plugin_folder * @param $plugin * * @return string */ private static function ensure_plugin_folder( $plugin ): string { if ( false === strpos( $plugin, '/' ) ) { $plugin = $plugin . '/' . $plugin . '.php'; } return $plugin; } /** * get_notice_allowed_html * @return array[] */ public static function get_notice_allowed_html(): array { return [ 'div' => [ 'class' => [], 'data-display' => [], ], 'svg' => [ 'width' => [], 'height' => [], 'viewbox' => [], 'fill' => [], 'xmlns' => [], ], 'path' => [ 'd' => [], 'stroke' => [], 'stroke-width' => [], 'stroke-linecap' => [], 'stroke-linejoin' => [], ], 'button' => [ 'class' => [], 'data-event' => [], 'data-settings' => [], 'data-tooltip' => [], ], 'i' => [ 'class' => [], 'aria-hidden' => [], ], 'span' => [ 'class' => [], ], 'a' => [ 'href' => [], 'style' => [], 'target' => [], ], ]; } } promotions/filtered-promotions-manager.php 0000644 00000004143 14720725675 0015124 0 ustar 00 path_resolver = $path_resolver; return $this; } /** * Load asset config from a file into the collection. * * @param $key * @param $path * * @return $this */ public function load( $key, $path = null ) { if ( ! $path && $this->path_resolver ) { $path_resolver_callback = $this->path_resolver; $path = $path_resolver_callback( $key ); } if ( ! $path || ! file_exists( $path ) ) { return $this; } $config = require $path; if ( ! $this->is_valid_handle( $config ) ) { return $this; } $this->items[ $key ] = [ 'handle' => $config['handle'], 'deps' => $this->is_valid_deps( $config ) ? $config['deps'] : [], ]; return $this; } /** * Check that the handle property in the config is a valid. * * @param $config * * @return bool */ private function is_valid_handle( $config ) { return ! empty( $config['handle'] ) && is_string( $config['handle'] ); } /** * Check that the deps property in the config is a valid. * * @param $config * * @return bool */ private function is_valid_deps( $config ) { return isset( $config['deps'] ) && is_array( $config['deps'] ); } } collection.php 0000644 00000022573 14720725675 0007440 0 ustar 00 items = $items; } /** * @param array $items * * @return static */ public static function make( array $items = [] ) { return new static( $items ); } /** * @param callable|null $callback * * @return $this */ public function filter( callable $callback = null ) { if ( ! $callback ) { return new static( array_filter( $this->items ) ); } return new static( array_filter( $this->items, $callback, ARRAY_FILTER_USE_BOTH ) ); } /** * @param $items * * @return $this */ public function merge( $items ) { if ( $items instanceof Collection ) { $items = $items->all(); } return new static( array_merge( $this->items, $items ) ); } /** * Union the collection with the given items. * * @param array $items * * @return $this */ public function union( array $items ) { return new static( $this->all() + $items ); } /** * Merge array recursively * * @param $items * * @return $this */ public function merge_recursive( $items ) { if ( $items instanceof Collection ) { $items = $items->all(); } return new static( array_merge_recursive( $this->items, $items ) ); } /** * Replace array recursively * * @param $items * * @return $this */ public function replace_recursive( $items ) { if ( $items instanceof Collection ) { $items = $items->all(); } return new static( array_replace_recursive( $this->items, $items ) ); } /** * Implode the items * * @param $glue * * @return string */ public function implode( $glue ) { return implode( $glue, $this->items ); } /** * Run a map over each of the items. * * @param callable $callback * @return $this */ public function map( callable $callback ) { $keys = array_keys( $this->items ); $items = array_map( $callback, $this->items, $keys ); return new static( array_combine( $keys, $items ) ); } /** * Run a callback over each of the items. * * @param callable $callback * @return $this */ public function each( callable $callback ) { foreach ( $this->items as $key => $value ) { if ( false === $callback( $value, $key ) ) { break; } } return $this; } /** * @param callable $callback * @param null $initial * * @return mixed|null */ public function reduce( callable $callback, $initial = null ) { $result = $initial; foreach ( $this->all() as $key => $value ) { $result = $callback( $result, $value, $key ); } return $result; } /** * @param callable $callback * * @return $this */ public function map_with_keys( callable $callback ) { $result = []; foreach ( $this->items as $key => $value ) { $assoc = $callback( $value, $key ); foreach ( $assoc as $map_key => $map_value ) { $result[ $map_key ] = $map_value; } } return new static( $result ); } /** * Get all items except for those with the specified keys. * * @param array $keys * * @return $this */ public function except( array $keys ) { return $this->filter( function ( $value, $key ) use ( $keys ) { return ! in_array( $key, $keys, true ); } ); } /** * Get the items with the specified keys. * * @param array $keys * * @return $this */ public function only( array $keys ) { return $this->filter( function ( $value, $key ) use ( $keys ) { return in_array( $key, $keys, true ); } ); } /** * Run over the collection to get specific prop from the collection item. * * @param $key * * @return $this */ public function pluck( $key ) { $result = []; foreach ( $this->items as $item ) { $result[] = $this->get_item_value( $item, $key ); } return new static( $result ); } /** * Group the collection items by specific key in each collection item. * * @param $group_by * * @return $this */ public function group_by( $group_by ) { $result = []; foreach ( $this->items as $item ) { $group_key = $this->get_item_value( $item, $group_by, 0 ); $result[ $group_key ][] = $item; } return new static( $result ); } /** * Sort keys * * @param false $descending * * @return $this */ public function sort_keys( $descending = false ) { $items = $this->items; if ( $descending ) { krsort( $items ); } else { ksort( $items ); } return new static( $items ); } /** * Get specific item from the collection. * * @param $key * @param null $default * * @return mixed|null */ public function get( $key, $default = null ) { if ( ! array_key_exists( $key, $this->items ) ) { return $default; } return $this->items[ $key ]; } /** * Get the first item. * * @param null $default * * @return mixed|null */ public function first( $default = null ) { if ( $this->is_empty() ) { return $default; } foreach ( $this->items as $item ) { return $item; } } /** * Find an element from the items. * * @param callable $callback * @param null $default * * @return mixed|null */ public function find( callable $callback, $default = null ) { foreach ( $this->all() as $key => $item ) { if ( $callback( $item, $key ) ) { return $item; } } return $default; } /** * @param callable|string|int $value * * @return bool */ public function contains( $value ) { $callback = $value instanceof \Closure ? $value : function ( $item ) use ( $value ) { return $item === $value; }; foreach ( $this->all() as $key => $item ) { if ( $callback( $item, $key ) ) { return true; } } return false; } /** * Make sure all the values inside the array are uniques. * * @param null|string|string[] $keys * * @return $this */ public function unique( $keys = null ) { if ( ! $keys ) { return new static( array_unique( $this->items ) ); } if ( ! is_array( $keys ) ) { $keys = [ $keys ]; } $exists = []; return $this->filter( function ( $item ) use ( $keys, &$exists ) { $value = null; foreach ( $keys as $key ) { $current_value = $this->get_item_value( $item, $key ); $value .= "{$key}:{$current_value};"; } // If no value for the specific key return the item. if ( null === $value ) { return true; } // If value is not exists, add to the exists array and return the item. if ( ! in_array( $value, $exists, true ) ) { $exists[] = $value; return true; } return false; } ); } /** * @return array */ public function keys() { return array_keys( $this->items ); } /** * @return bool */ public function is_empty() { return empty( $this->items ); } /** * @return array */ public function all() { return $this->items; } /** * @return array */ public function values() { return array_values( $this->all() ); } /** * Support only one level depth. * * @return $this */ public function flatten() { $result = []; foreach ( $this->all() as $item ) { $item = $item instanceof Collection ? $item->all() : $item; if ( ! is_array( $item ) ) { $result[] = $item; } else { $values = array_values( $item ); foreach ( $values as $value ) { $result[] = $value; } } } return new static( $result ); } /** * @param ...$values * * @return $this */ public function push( ...$values ) { foreach ( $values as $value ) { $this->items[] = $value; } return $this; } public function prepend( ...$values ) { $this->items = array_merge( $values, $this->items ); return $this; } public function some( callable $callback ) { foreach ( $this->items as $key => $item ) { if ( $callback( $item, $key ) ) { return true; } } return false; } /** * @param mixed $offset * * @return bool */ #[\ReturnTypeWillChange] public function offsetExists( $offset ) { return isset( $this->items[ $offset ] ); } /** * @param mixed $offset * * @return mixed */ #[\ReturnTypeWillChange] public function offsetGet( $offset ) { return $this->items[ $offset ]; } /** * @param mixed $offset * @param mixed $value */ #[\ReturnTypeWillChange] public function offsetSet( $offset, $value ) { if ( is_null( $offset ) ) { $this->items[] = $value; } else { $this->items[ $offset ] = $value; } } /** * @param mixed $offset */ #[\ReturnTypeWillChange] public function offsetUnset( $offset ) { unset( $this->items[ $offset ] ); } /** * @return \ArrayIterator|\Traversable */ #[\ReturnTypeWillChange] public function getIterator() { return new \ArrayIterator( $this->items ); } /** * @return int|void */ #[\ReturnTypeWillChange] public function count() { return count( $this->items ); } /** * @param $item * @param $key * @param null $default * * @return mixed|null */ private function get_item_value( $item, $key, $default = null ) { $value = $default; if ( is_object( $item ) && isset( $item->{$key} ) ) { $value = $item->{$key}; } elseif ( is_array( $item ) && isset( $item[ $key ] ) ) { $value = $item[ $key ]; } return $value; } } plugins-manager.php 0000644 00000005532 14720725675 0010372 0 ustar 00 upgrader = $upgrader; } else { $skin = new WP_Ajax_Upgrader_Skin(); $this->upgrader = new Plugin_Upgrader( $skin ); } } /** * Install plugin or an array of plugins. * * @since 3.6.2 * * @param string|array $plugins * @return array [ 'succeeded' => [] , 'failed' => [] ] */ public function install( $plugins ) { $succeeded = []; $failed = []; $already_installed_plugins = Plugin::$instance->wp->get_plugins(); if ( ! is_array( $plugins ) ) { $plugins = [ $plugins ]; } foreach ( $plugins as $plugin ) { if ( in_array( $plugin, $already_installed_plugins->keys(), true ) ) { $succeeded[] = $plugin; continue; } $slug = $this->clean_slug( $plugin ); $api = Plugin::$instance->wp->plugins_api('plugin_information', [ 'slug' => $slug, 'fields' => array( 'short_description' => false, 'sections' => false, 'requires' => false, 'rating' => false, 'ratings' => false, 'downloaded' => false, 'last_updated' => false, 'added' => false, 'tags' => false, 'compatibility' => false, 'homepage' => false, 'donate_link' => false, ), ] ); if ( ! isset( $api->download_link ) ) { $failed[] = $plugin; continue; } $installation = $this->upgrader->install( $api->download_link ); if ( $installation ) { $succeeded[] = $plugin; } else { $failed[] = $plugin; } } return [ 'succeeded' => $succeeded, 'failed' => $failed, ]; } /** * Activate plugin or array off plugins. * * @since 3.6.2 * * @param array|string $plugins * @return array [ 'succeeded' => [] , 'failed' => [] ] */ public function activate( $plugins ) { $succeeded = []; $failed = []; if ( ! is_array( $plugins ) ) { $plugins = [ $plugins ]; } foreach ( $plugins as $plugin ) { if ( Plugin::$instance->wp->is_plugin_active( $plugin ) ) { $succeeded[] = $plugin; continue; } Plugin::$instance->wp->activate_plugin( $plugin ); if ( Plugin::$instance->wp->is_plugin_active( $plugin ) ) { $succeeded[] = $plugin; } else { $failed[] = $plugin; } } return [ 'succeeded' => $succeeded, 'failed' => $failed, ]; } private function clean_slug( $initial_slug ) { return explode( '/', $initial_slug )[0]; } } version.php 0000644 00000007211 14720725675 0006762 0 ustar 00 major1 = $major1; $this->major2 = $major2; $this->patch = $patch; $this->stage = $stage; } /** * Create Version instance. * * @param string $major1 * @param string $major2 * @param string $patch * @param null $stage * * @return static */ public static function create( $major1 = '0', $major2 = '0', $patch = '0', $stage = null ) { return new static( $major1, $major2, $patch, $stage ); } /** * Checks if the current version string is valid. * * @param $version * * @return bool */ public static function is_valid_version( $version ) { return ! ! preg_match( '/^(\d+\.)?(\d+\.)?(\*|\d+)(-.+)?$/', $version ); } /** * Creates a Version instance from a string. * * @param $version * @param bool $should_validate * * @return static * @throws \Exception */ public static function create_from_string( $version, $should_validate = true ) { if ( $should_validate && ! static::is_valid_version( $version ) ) { throw new \Exception( "{$version} is an invalid version." ); } $parts = explode( '.', $version ); $patch_parts = []; $major1 = '0'; $major2 = '0'; $patch = '0'; $stage = null; if ( isset( $parts[0] ) ) { $major1 = $parts[0]; } if ( isset( $parts[1] ) ) { $major2 = $parts[1]; } if ( isset( $parts[2] ) ) { $patch_parts = explode( '-', $parts[2] ); $patch = $patch_parts[0]; } if ( isset( $patch_parts[1] ) ) { $stage = $patch_parts[1]; } return static::create( $major1, $major2, $patch, $stage ); } /** * Compare the current version instance with another version. * * @param $operator * @param $version * @param string $part * * @return bool * @throws \Exception */ public function compare( $operator, $version, $part = self::PART_STAGE ) { if ( ! ( $version instanceof Version ) ) { if ( ! static::is_valid_version( $version ) ) { $version = '0.0.0'; } $version = static::create_from_string( $version, false ); } $current_version = clone $this; $compare_version = clone $version; if ( in_array( $part, [ self::PART_PATCH, self::PART_MAJOR_2, self::PART_MAJOR_1 ], true ) ) { $current_version->stage = null; $compare_version->stage = null; } if ( in_array( $part, [ self::PART_MAJOR_2, self::PART_MAJOR_1 ], true ) ) { $current_version->patch = '0'; $compare_version->patch = '0'; } if ( self::PART_MAJOR_1 === $part ) { $current_version->major2 = '0'; $compare_version->major2 = '0'; } return version_compare( $current_version, $compare_version, $operator ); } /** * Implode the version and return it as string. * * @return string */ public function __toString() { $version = implode( '.', [ $this->major1, $this->major2, $this->patch ] ); if ( $this->stage ) { $version .= '-' . $this->stage; } return $version; } } __init__.py 0000644 00000110001 14722165061 0006652 0 ustar 00 """passlib.utils -- helpers for writing password hashes""" #============================================================================= # imports #============================================================================= from passlib.utils.compat import JYTHON # core from binascii import b2a_base64, a2b_base64, Error as _BinAsciiError from base64 import b64encode, b64decode import collections from codecs import lookup as _lookup_codec from functools import update_wrapper import itertools import inspect import logging; log = logging.getLogger(__name__) import math import os import sys import random import re if JYTHON: # pragma: no cover -- runtime detection # Jython 2.5.2 lacks stringprep module - # see http://bugs.jython.org/issue1758320 try: import stringprep except ImportError: stringprep = None _stringprep_missing_reason = "not present under Jython" else: import stringprep import time if stringprep: import unicodedata import types from warnings import warn # site # pkg from passlib.utils.binary import ( # [remove these aliases in 2.0] BASE64_CHARS, AB64_CHARS, HASH64_CHARS, BCRYPT_CHARS, Base64Engine, LazyBase64Engine, h64, h64big, bcrypt64, ab64_encode, ab64_decode, b64s_encode, b64s_decode ) from passlib.utils.decor import ( # [remove these aliases in 2.0] deprecated_function, deprecated_method, memoized_property, classproperty, hybrid_method, ) from passlib.exc import ExpectedStringError from passlib.utils.compat import (add_doc, join_bytes, join_byte_values, join_byte_elems, irange, imap, PY3, u, join_unicode, unicode, byte_elem_value, nextgetter, unicode_or_bytes_types, get_method_function, suppress_cause) # local __all__ = [ # constants 'JYTHON', 'sys_bits', 'unix_crypt_schemes', 'rounds_cost_values', # unicode helpers 'consteq', 'saslprep', # bytes helpers "xor_bytes", "render_bytes", # encoding helpers 'is_same_codec', 'is_ascii_safe', 'to_bytes', 'to_unicode', 'to_native_str', # host OS 'has_crypt', 'test_crypt', 'safe_crypt', 'tick', # randomness 'rng', 'getrandbytes', 'getrandstr', 'generate_password', # object type / interface tests 'is_crypt_handler', 'is_crypt_context', 'has_rounds_info', 'has_salt_info', ] #============================================================================= # constants #============================================================================= # bitsize of system architecture (32 or 64) sys_bits = int(math.log(sys.maxsize if PY3 else sys.maxint, 2) + 1.5) # list of hashes algs supported by crypt() on at least one OS. # XXX: move to .registry for passlib 2.0? unix_crypt_schemes = [ "sha512_crypt", "sha256_crypt", "sha1_crypt", "bcrypt", "md5_crypt", # "bsd_nthash", "bsdi_crypt", "des_crypt", ] # list of rounds_cost constants rounds_cost_values = [ "linear", "log2" ] # legacy import, will be removed in 1.8 from passlib.exc import MissingBackendError # internal helpers _BEMPTY = b'' _UEMPTY = u("") _USPACE = u(" ") # maximum password size which passlib will allow; see exc.PasswordSizeError MAX_PASSWORD_SIZE = int(os.environ.get("PASSLIB_MAX_PASSWORD_SIZE") or 4096) #============================================================================= # type helpers #============================================================================= class SequenceMixin(object): """ helper which lets result object act like a fixed-length sequence. subclass just needs to provide :meth:`_as_tuple()`. """ def _as_tuple(self): raise NotImplemented("implement in subclass") def __repr__(self): return repr(self._as_tuple()) def __getitem__(self, idx): return self._as_tuple()[idx] def __iter__(self): return iter(self._as_tuple()) def __len__(self): return len(self._as_tuple()) def __eq__(self, other): return self._as_tuple() == other def __ne__(self, other): return not self.__eq__(other) if PY3: # getargspec() is deprecated, use this under py3. # even though it's a lot more awkward to get basic info :| _VAR_KEYWORD = inspect.Parameter.VAR_KEYWORD _VAR_ANY_SET = set([_VAR_KEYWORD, inspect.Parameter.VAR_POSITIONAL]) def accepts_keyword(func, key): """test if function accepts specified keyword""" params = inspect.signature(get_method_function(func)).parameters if not params: return False arg = params.get(key) if arg and arg.kind not in _VAR_ANY_SET: return True # XXX: annoying what we have to do to determine if VAR_KWDS in use. return params[list(params)[-1]].kind == _VAR_KEYWORD else: def accepts_keyword(func, key): """test if function accepts specified keyword""" spec = inspect.getargspec(get_method_function(func)) return key in spec.args or spec.keywords is not None def update_mixin_classes(target, add=None, remove=None, append=False, before=None, after=None, dryrun=False): """ helper to update mixin classes installed in target class. :param target: target class whose bases will be modified. :param add: class / classes to install into target's base class list. :param remove: class / classes to remove from target's base class list. :param append: by default, prepends mixins to front of list. if True, appends to end of list instead. :param after: optionally make sure all mixins are inserted after this class / classes. :param before: optionally make sure all mixins are inserted before this class / classes. :param dryrun: optionally perform all calculations / raise errors, but don't actually modify the class. """ if isinstance(add, type): add = [add] bases = list(target.__bases__) # strip out requested mixins if remove: if isinstance(remove, type): remove = [remove] for mixin in remove: if add and mixin in add: continue if mixin in bases: bases.remove(mixin) # add requested mixins if add: for mixin in add: # if mixin already present (explicitly or not), leave alone if any(issubclass(base, mixin) for base in bases): continue # determine insertion point if append: for idx, base in enumerate(bases): if issubclass(mixin, base): # don't insert mixin after one of it's own bases break if before and issubclass(base, before): # don't insert mixin after any classes. break else: # append to end idx = len(bases) elif after: for end_idx, base in enumerate(reversed(bases)): if issubclass(base, after): # don't insert mixin before any classes. idx = len(bases) - end_idx assert bases[idx-1] == base break else: idx = 0 else: # insert at start idx = 0 # insert mixin bases.insert(idx, mixin) # modify class if not dryrun: target.__bases__ = tuple(bases) #============================================================================= # collection helpers #============================================================================= def batch(source, size): """ split iterable into chunks of elements. """ if size < 1: raise ValueError("size must be positive integer") if isinstance(source, collections.Sequence): end = len(source) i = 0 while i < end: n = i + size yield source[i:n] i = n elif isinstance(source, collections.Iterable): itr = iter(source) while True: chunk_itr = itertools.islice(itr, size) try: first = next(chunk_itr) except StopIteration: break yield itertools.chain((first,), chunk_itr) else: raise TypeError("source must be iterable") #============================================================================= # unicode helpers #============================================================================= # XXX: should this be moved to passlib.crypto, or compat backports? def consteq(left, right): """Check two strings/bytes for equality. This function uses an approach designed to prevent timing analysis, making it appropriate for cryptography. a and b must both be of the same type: either str (ASCII only), or any type that supports the buffer protocol (e.g. bytes). Note: If a and b are of different lengths, or if an error occurs, a timing attack could theoretically reveal information about the types and lengths of a and b--but not their values. """ # NOTE: # resources & discussions considered in the design of this function: # hmac timing attack -- # http://rdist.root.org/2009/05/28/timing-attack-in-google-keyczar-library/ # python developer discussion surrounding similar function -- # http://bugs.python.org/issue15061 # http://bugs.python.org/issue14955 # validate types if isinstance(left, unicode): if not isinstance(right, unicode): raise TypeError("inputs must be both unicode or both bytes") is_py3_bytes = False elif isinstance(left, bytes): if not isinstance(right, bytes): raise TypeError("inputs must be both unicode or both bytes") is_py3_bytes = PY3 else: raise TypeError("inputs must be both unicode or both bytes") # do size comparison. # NOTE: the double-if construction below is done deliberately, to ensure # the same number of operations (including branches) is performed regardless # of whether left & right are the same size. same_size = (len(left) == len(right)) if same_size: # if sizes are the same, setup loop to perform actual check of contents. tmp = left result = 0 if not same_size: # if sizes aren't the same, set 'result' so equality will fail regardless # of contents. then, to ensure we do exactly 'len(right)' iterations # of the loop, just compare 'right' against itself. tmp = right result = 1 # run constant-time string comparision # TODO: use izip instead (but first verify it's faster than zip for this case) if is_py3_bytes: for l,r in zip(tmp, right): result |= l ^ r else: for l,r in zip(tmp, right): result |= ord(l) ^ ord(r) return result == 0 # keep copy of this around since stdlib's version throws error on non-ascii chars in unicode strings. # our version does, but suffers from some underlying VM issues. but something is better than # nothing for plaintext hashes, which need this. everything else should use consteq(), # since the stdlib one is going to be as good / better in the general case. str_consteq = consteq try: # for py3.3 and up, use the stdlib version from hmac import compare_digest as consteq except ImportError: pass # TODO: could check for cryptography package's version, # but only operates on bytes, so would need a wrapper, # or separate consteq() into a unicode & a bytes variant. # from cryptography.hazmat.primitives.constant_time import bytes_eq as consteq def splitcomma(source, sep=","): """split comma-separated string into list of elements, stripping whitespace. """ source = source.strip() if source.endswith(sep): source = source[:-1] if not source: return [] return [ elem.strip() for elem in source.split(sep) ] def saslprep(source, param="value"): """Normalizes unicode strings using SASLPrep stringprep profile. The SASLPrep profile is defined in :rfc:`4013`. It provides a uniform scheme for normalizing unicode usernames and passwords before performing byte-value sensitive operations such as hashing. Among other things, it normalizes diacritic representations, removes non-printing characters, and forbids invalid characters such as ``\\n``. Properly internationalized applications should run user passwords through this function before hashing. :arg source: unicode string to normalize & validate :param param: Optional noun identifying source parameter in error messages (Defaults to the string ``"value"``). This is mainly useful to make the caller's error messages make more sense contextually. :raises ValueError: if any characters forbidden by the SASLPrep profile are encountered. :raises TypeError: if input is not :class:`!unicode` :returns: normalized unicode string .. note:: This function is not available under Jython, as the Jython stdlib is missing the :mod:`!stringprep` module (`Jython issue 1758320 `_). .. versionadded:: 1.6 """ # saslprep - http://tools.ietf.org/html/rfc4013 # stringprep - http://tools.ietf.org/html/rfc3454 # http://docs.python.org/library/stringprep.html # validate type # XXX: support bytes (e.g. run through want_unicode)? # might be easier to just integrate this into cryptcontext. if not isinstance(source, unicode): raise TypeError("input must be unicode string, not %s" % (type(source),)) # mapping stage # - map non-ascii spaces to U+0020 (stringprep C.1.2) # - strip 'commonly mapped to nothing' chars (stringprep B.1) in_table_c12 = stringprep.in_table_c12 in_table_b1 = stringprep.in_table_b1 data = join_unicode( _USPACE if in_table_c12(c) else c for c in source if not in_table_b1(c) ) # normalize to KC form data = unicodedata.normalize('NFKC', data) if not data: return _UEMPTY # check for invalid bi-directional strings. # stringprep requires the following: # - chars in C.8 must be prohibited. # - if any R/AL chars in string: # - no L chars allowed in string # - first and last must be R/AL chars # this checks if start/end are R/AL chars. if so, prohibited loop # will forbid all L chars. if not, prohibited loop will forbid all # R/AL chars instead. in both cases, prohibited loop takes care of C.8. is_ral_char = stringprep.in_table_d1 if is_ral_char(data[0]): if not is_ral_char(data[-1]): raise ValueError("malformed bidi sequence in " + param) # forbid L chars within R/AL sequence. is_forbidden_bidi_char = stringprep.in_table_d2 else: # forbid R/AL chars if start not setup correctly; L chars allowed. is_forbidden_bidi_char = is_ral_char # check for prohibited output - stringprep tables A.1, B.1, C.1.2, C.2 - C.9 in_table_a1 = stringprep.in_table_a1 in_table_c21_c22 = stringprep.in_table_c21_c22 in_table_c3 = stringprep.in_table_c3 in_table_c4 = stringprep.in_table_c4 in_table_c5 = stringprep.in_table_c5 in_table_c6 = stringprep.in_table_c6 in_table_c7 = stringprep.in_table_c7 in_table_c8 = stringprep.in_table_c8 in_table_c9 = stringprep.in_table_c9 for c in data: # check for chars mapping stage should have removed assert not in_table_b1(c), "failed to strip B.1 in mapping stage" assert not in_table_c12(c), "failed to replace C.1.2 in mapping stage" # check for forbidden chars if in_table_a1(c): raise ValueError("unassigned code points forbidden in " + param) if in_table_c21_c22(c): raise ValueError("control characters forbidden in " + param) if in_table_c3(c): raise ValueError("private use characters forbidden in " + param) if in_table_c4(c): raise ValueError("non-char code points forbidden in " + param) if in_table_c5(c): raise ValueError("surrogate codes forbidden in " + param) if in_table_c6(c): raise ValueError("non-plaintext chars forbidden in " + param) if in_table_c7(c): # XXX: should these have been caught by normalize? # if so, should change this to an assert raise ValueError("non-canonical chars forbidden in " + param) if in_table_c8(c): raise ValueError("display-modifying / deprecated chars " "forbidden in" + param) if in_table_c9(c): raise ValueError("tagged characters forbidden in " + param) # do bidi constraint check chosen by bidi init, above if is_forbidden_bidi_char(c): raise ValueError("forbidden bidi character in " + param) return data # replace saslprep() with stub when stringprep is missing if stringprep is None: # pragma: no cover -- runtime detection def saslprep(source, param="value"): """stub for saslprep()""" raise NotImplementedError("saslprep() support requires the 'stringprep' " "module, which is " + _stringprep_missing_reason) #============================================================================= # bytes helpers #============================================================================= def render_bytes(source, *args): """Peform ``%`` formating using bytes in a uniform manner across Python 2/3. This function is motivated by the fact that :class:`bytes` instances do not support ``%`` or ``{}`` formatting under Python 3. This function is an attempt to provide a replacement: it converts everything to unicode (decoding bytes instances as ``latin-1``), performs the required formatting, then encodes the result to ``latin-1``. Calling ``render_bytes(source, *args)`` should function roughly the same as ``source % args`` under Python 2. """ if isinstance(source, bytes): source = source.decode("latin-1") result = source % tuple(arg.decode("latin-1") if isinstance(arg, bytes) else arg for arg in args) return result.encode("latin-1") if PY3: # new in py32 def bytes_to_int(value): return int.from_bytes(value, 'big') def int_to_bytes(value, count): return value.to_bytes(count, 'big') else: # XXX: can any of these be sped up? from binascii import hexlify, unhexlify def bytes_to_int(value): return int(hexlify(value),16) def int_to_bytes(value, count): return unhexlify(('%%0%dx' % (count<<1)) % value) add_doc(bytes_to_int, "decode byte string as single big-endian integer") add_doc(int_to_bytes, "encode integer as single big-endian byte string") def xor_bytes(left, right): """Perform bitwise-xor of two byte strings (must be same size)""" return int_to_bytes(bytes_to_int(left) ^ bytes_to_int(right), len(left)) def repeat_string(source, size): """repeat or truncate string, so it has length """ cur = len(source) if size > cur: mult = (size+cur-1)//cur return (source*mult)[:size] else: return source[:size] _BNULL = b"\x00" _UNULL = u("\x00") def right_pad_string(source, size, pad=None): """right-pad or truncate string, so it has length """ cur = len(source) if size > cur: if pad is None: pad = _UNULL if isinstance(source, unicode) else _BNULL return source+pad*(size-cur) else: return source[:size] #============================================================================= # encoding helpers #============================================================================= _ASCII_TEST_BYTES = b"\x00\n aA:#!\x7f" _ASCII_TEST_UNICODE = _ASCII_TEST_BYTES.decode("ascii") def is_ascii_codec(codec): """Test if codec is compatible with 7-bit ascii (e.g. latin-1, utf-8; but not utf-16)""" return _ASCII_TEST_UNICODE.encode(codec) == _ASCII_TEST_BYTES def is_same_codec(left, right): """Check if two codec names are aliases for same codec""" if left == right: return True if not (left and right): return False return _lookup_codec(left).name == _lookup_codec(right).name _B80 = b'\x80'[0] _U80 = u('\x80') def is_ascii_safe(source): """Check if string (bytes or unicode) contains only 7-bit ascii""" r = _B80 if isinstance(source, bytes) else _U80 return all(c < r for c in source) def to_bytes(source, encoding="utf-8", param="value", source_encoding=None): """Helper to normalize input to bytes. :arg source: Source bytes/unicode to process. :arg encoding: Target encoding (defaults to ``"utf-8"``). :param param: Optional name of variable/noun to reference when raising errors :param source_encoding: If this is specified, and the source is bytes, the source will be transcoded from *source_encoding* to *encoding* (via unicode). :raises TypeError: if source is not unicode or bytes. :returns: * unicode strings will be encoded using *encoding*, and returned. * if *source_encoding* is not specified, byte strings will be returned unchanged. * if *source_encoding* is specified, byte strings will be transcoded to *encoding*. """ assert encoding if isinstance(source, bytes): if source_encoding and not is_same_codec(source_encoding, encoding): return source.decode(source_encoding).encode(encoding) else: return source elif isinstance(source, unicode): return source.encode(encoding) else: raise ExpectedStringError(source, param) def to_unicode(source, encoding="utf-8", param="value"): """Helper to normalize input to unicode. :arg source: source bytes/unicode to process. :arg encoding: encoding to use when decoding bytes instances. :param param: optional name of variable/noun to reference when raising errors. :raises TypeError: if source is not unicode or bytes. :returns: * returns unicode strings unchanged. * returns bytes strings decoded using *encoding* """ assert encoding if isinstance(source, unicode): return source elif isinstance(source, bytes): return source.decode(encoding) else: raise ExpectedStringError(source, param) if PY3: def to_native_str(source, encoding="utf-8", param="value"): if isinstance(source, bytes): return source.decode(encoding) elif isinstance(source, unicode): return source else: raise ExpectedStringError(source, param) else: def to_native_str(source, encoding="utf-8", param="value"): if isinstance(source, bytes): return source elif isinstance(source, unicode): return source.encode(encoding) else: raise ExpectedStringError(source, param) add_doc(to_native_str, """Take in unicode or bytes, return native string. Python 2: encodes unicode using specified encoding, leaves bytes alone. Python 3: leaves unicode alone, decodes bytes using specified encoding. :raises TypeError: if source is not unicode or bytes. :arg source: source unicode or bytes string. :arg encoding: encoding to use when encoding unicode or decoding bytes. this defaults to ``"utf-8"``. :param param: optional name of variable/noun to reference when raising errors. :returns: :class:`str` instance """) @deprecated_function(deprecated="1.6", removed="1.7") def to_hash_str(source, encoding="ascii"): # pragma: no cover -- deprecated & unused """deprecated, use to_native_str() instead""" return to_native_str(source, encoding, param="hash") _true_set = set("true t yes y on 1 enable enabled".split()) _false_set = set("false f no n off 0 disable disabled".split()) _none_set = set(["", "none"]) def as_bool(value, none=None, param="boolean"): """ helper to convert value to boolean. recognizes strings such as "true", "false" """ assert none in [True, False, None] if isinstance(value, unicode_or_bytes_types): clean = value.lower().strip() if clean in _true_set: return True if clean in _false_set: return False if clean in _none_set: return none raise ValueError("unrecognized %s value: %r" % (param, value)) elif isinstance(value, bool): return value elif value is None: return none else: return bool(value) #============================================================================= # host OS helpers #============================================================================= try: from crypt import crypt as _crypt except ImportError: # pragma: no cover _crypt = None has_crypt = False def safe_crypt(secret, hash): return None else: has_crypt = True _NULL = '\x00' # some crypt() variants will return various constant strings when # an invalid/unrecognized config string is passed in; instead of # returning NULL / None. examples include ":", ":0", "*0", etc. # safe_crypt() returns None for any string starting with one of the # chars in this string... _invalid_prefixes = u("*:!") if PY3: def safe_crypt(secret, hash): if isinstance(secret, bytes): # Python 3's crypt() only accepts unicode, which is then # encoding using utf-8 before passing to the C-level crypt(). # so we have to decode the secret. orig = secret try: secret = secret.decode("utf-8") except UnicodeDecodeError: return None assert secret.encode("utf-8") == orig, \ "utf-8 spec says this can't happen!" if _NULL in secret: raise ValueError("null character in secret") if isinstance(hash, bytes): hash = hash.decode("ascii") result = _crypt(secret, hash) if not result or result[0] in _invalid_prefixes: return None return result else: def safe_crypt(secret, hash): if isinstance(secret, unicode): secret = secret.encode("utf-8") if _NULL in secret: raise ValueError("null character in secret") if isinstance(hash, unicode): hash = hash.encode("ascii") result = _crypt(secret, hash) if not result: return None result = result.decode("ascii") if result[0] in _invalid_prefixes: return None return result add_doc(safe_crypt, """Wrapper around stdlib's crypt. This is a wrapper around stdlib's :func:`!crypt.crypt`, which attempts to provide uniform behavior across Python 2 and 3. :arg secret: password, as bytes or unicode (unicode will be encoded as ``utf-8``). :arg hash: hash or config string, as ascii bytes or unicode. :returns: resulting hash as ascii unicode; or ``None`` if the password couldn't be hashed due to one of the issues: * :func:`crypt()` not available on platform. * Under Python 3, if *secret* is specified as bytes, it must be use ``utf-8`` or it can't be passed to :func:`crypt()`. * Some OSes will return ``None`` if they don't recognize the algorithm being used (though most will simply fall back to des-crypt). * Some OSes will return an error string if the input config is recognized but malformed; current code converts these to ``None`` as well. """) def test_crypt(secret, hash): """check if :func:`crypt.crypt` supports specific hash :arg secret: password to test :arg hash: known hash of password to use as reference :returns: True or False """ assert secret and hash return safe_crypt(secret, hash) == hash # pick best timer function to expose as "tick" - lifted from timeit module. if sys.platform == "win32": # On Windows, the best timer is time.clock() from time import clock as timer else: # On most other platforms the best timer is time.time() from time import time as timer # legacy alias, will be removed in passlib 2.0 tick = timer def parse_version(source): """helper to parse version string""" m = re.search(r"(\d+(?:\.\d+)+)", source) if m: return tuple(int(elem) for elem in m.group(1).split(".")) return None #============================================================================= # randomness #============================================================================= #------------------------------------------------------------------------ # setup rng for generating salts #------------------------------------------------------------------------ # NOTE: # generating salts (e.g. h64_gensalt, below) doesn't require cryptographically # strong randomness. it just requires enough range of possible outputs # that making a rainbow table is too costly. so it should be ok to # fall back on python's builtin mersenne twister prng, as long as it's seeded each time # this module is imported, using a couple of minor entropy sources. try: os.urandom(1) has_urandom = True except NotImplementedError: # pragma: no cover has_urandom = False def genseed(value=None): """generate prng seed value from system resources""" from hashlib import sha512 if hasattr(value, "getstate") and hasattr(value, "getrandbits"): # caller passed in RNG as seed value try: value = value.getstate() except NotImplementedError: # this method throws error for e.g. SystemRandom instances, # so fall back to extracting 4k of state value = value.getrandbits(1 << 15) text = u("%s %s %s %.15f %.15f %s") % ( # if caller specified a seed value, mix it in value, # add current process id # NOTE: not available in some environments, e.g. GAE os.getpid() if hasattr(os, "getpid") else None, # id of a freshly created object. # (at least 1 byte of which should be hard to predict) id(object()), # the current time, to whatever precision os uses time.time(), time.clock(), # if urandom available, might as well mix some bytes in. os.urandom(32).decode("latin-1") if has_urandom else 0, ) # hash it all up and return it as int/long return int(sha512(text.encode("utf-8")).hexdigest(), 16) if has_urandom: rng = random.SystemRandom() else: # pragma: no cover -- runtime detection # NOTE: to reseed use ``rng.seed(genseed(rng))`` # XXX: could reseed on every call rng = random.Random(genseed()) #------------------------------------------------------------------------ # some rng helpers #------------------------------------------------------------------------ def getrandbytes(rng, count): """return byte-string containing *count* number of randomly generated bytes, using specified rng""" # NOTE: would be nice if this was present in stdlib Random class ###just in case rng provides this... ##meth = getattr(rng, "getrandbytes", None) ##if meth: ## return meth(count) if not count: return _BEMPTY def helper(): # XXX: break into chunks for large number of bits? value = rng.getrandbits(count<<3) i = 0 while i < count: yield value & 0xff value >>= 3 i += 1 return join_byte_values(helper()) def getrandstr(rng, charset, count): """return string containing *count* number of chars/bytes, whose elements are drawn from specified charset, using specified rng""" # NOTE: tests determined this is 4x faster than rng.sample(), # which is why that's not being used here. # check alphabet & count if count < 0: raise ValueError("count must be >= 0") letters = len(charset) if letters == 0: raise ValueError("alphabet must not be empty") if letters == 1: return charset * count # get random value, and write out to buffer def helper(): # XXX: break into chunks for large number of letters? value = rng.randrange(0, letters**count) i = 0 while i < count: yield charset[value % letters] value //= letters i += 1 if isinstance(charset, unicode): return join_unicode(helper()) else: return join_byte_elems(helper()) _52charset = '2346789ABCDEFGHJKMNPQRTUVWXYZabcdefghjkmnpqrstuvwxyz' @deprecated_function(deprecated="1.7", removed="2.0", replacement="passlib.pwd.genword() / passlib.pwd.genphrase()") def generate_password(size=10, charset=_52charset): """generate random password using given length & charset :param size: size of password. :param charset: optional string specified set of characters to draw from. the default charset contains all normal alphanumeric characters, except for the characters ``1IiLl0OoS5``, which were omitted due to their visual similarity. :returns: :class:`!str` containing randomly generated password. .. note:: Using the default character set, on a OS with :class:`!SystemRandom` support, this function should generate passwords with 5.7 bits of entropy per character. """ return getrandstr(rng, charset, size) #============================================================================= # object type / interface tests #============================================================================= _handler_attrs = ( "name", "setting_kwds", "context_kwds", "verify", "hash", "identify", ) def is_crypt_handler(obj): """check if object follows the :ref:`password-hash-api`""" # XXX: change to use isinstance(obj, PasswordHash) under py26+? return all(hasattr(obj, name) for name in _handler_attrs) _context_attrs = ( "needs_update", "genconfig", "genhash", "verify", "encrypt", "identify", ) def is_crypt_context(obj): """check if object appears to be a :class:`~passlib.context.CryptContext` instance""" # XXX: change to use isinstance(obj, CryptContext)? return all(hasattr(obj, name) for name in _context_attrs) ##def has_many_backends(handler): ## "check if handler provides multiple baceknds" ## # NOTE: should also provide get_backend(), .has_backend(), and .backends attr ## return hasattr(handler, "set_backend") def has_rounds_info(handler): """check if handler provides the optional :ref:`rounds information ` attributes""" return ('rounds' in handler.setting_kwds and getattr(handler, "min_rounds", None) is not None) def has_salt_info(handler): """check if handler provides the optional :ref:`salt information ` attributes""" return ('salt' in handler.setting_kwds and getattr(handler, "min_salt_size", None) is not None) ##def has_raw_salt(handler): ## "check if handler takes in encoded salt as unicode (False), or decoded salt as bytes (True)" ## sc = getattr(handler, "salt_chars", None) ## if sc is None: ## return None ## elif isinstance(sc, unicode): ## return False ## elif isinstance(sc, bytes): ## return True ## else: ## raise TypeError("handler.salt_chars must be None/unicode/bytes") #============================================================================= # eof #============================================================================= hashes.py 0000644 00000005462 14722165061 0006404 0 ustar 00 from __future__ import absolute_import import hashlib from pip.exceptions import HashMismatch, HashMissing, InstallationError from pip.utils import read_chunks from pip._vendor.six import iteritems, iterkeys, itervalues # The recommended hash algo of the moment. Change this whenever the state of # the art changes; it won't hurt backward compatibility. FAVORITE_HASH = 'sha256' # Names of hashlib algorithms allowed by the --hash option and ``pip hash`` # Currently, those are the ones at least as collision-resistant as sha256. STRONG_HASHES = ['sha256', 'sha384', 'sha512'] class Hashes(object): """A wrapper that builds multiple hashes at once and checks them against known-good values """ def __init__(self, hashes=None): """ :param hashes: A dict of algorithm names pointing to lists of allowed hex digests """ self._allowed = {} if hashes is None else hashes def check_against_chunks(self, chunks): """Check good hashes against ones built from iterable of chunks of data. Raise HashMismatch if none match. """ gots = {} for hash_name in iterkeys(self._allowed): try: gots[hash_name] = hashlib.new(hash_name) except (ValueError, TypeError): raise InstallationError('Unknown hash name: %s' % hash_name) for chunk in chunks: for hash in itervalues(gots): hash.update(chunk) for hash_name, got in iteritems(gots): if got.hexdigest() in self._allowed[hash_name]: return self._raise(gots) def _raise(self, gots): raise HashMismatch(self._allowed, gots) def check_against_file(self, file): """Check good hashes against a file-like object Raise HashMismatch if none match. """ return self.check_against_chunks(read_chunks(file)) def check_against_path(self, path): with open(path, 'rb') as file: return self.check_against_file(file) def __nonzero__(self): """Return whether I know any known-good hashes.""" return bool(self._allowed) def __bool__(self): return self.__nonzero__() class MissingHashes(Hashes): """A workalike for Hashes used when we're missing a hash for a requirement It computes the actual hash of the requirement and raises a HashMissing exception showing it to the user. """ def __init__(self): """Don't offer the ``hashes`` kwarg.""" # Pass our favorite hash in to generate a "gotten hash". With the # empty list, it will never match, so an error will always raise. super(MissingHashes, self).__init__(hashes={FAVORITE_HASH: []}) def _raise(self, gots): raise HashMissing(gots[FAVORITE_HASH].hexdigest()) outdated.py 0000644 00000013545 14722165061 0006743 0 ustar 00 from __future__ import absolute_import import datetime import json import logging import os.path import sys from pip._vendor import lockfile from pip._vendor.packaging import version as packaging_version from pip.compat import total_seconds, WINDOWS from pip.models import PyPI from pip.locations import USER_CACHE_DIR, running_under_virtualenv from pip.utils import ensure_dir, get_installed_version from pip.utils.filesystem import check_path_owner SELFCHECK_DATE_FMT = "%Y-%m-%dT%H:%M:%SZ" logger = logging.getLogger(__name__) class VirtualenvSelfCheckState(object): def __init__(self): self.statefile_path = os.path.join(sys.prefix, "pip-selfcheck.json") # Load the existing state try: with open(self.statefile_path) as statefile: self.state = json.load(statefile) except (IOError, ValueError): self.state = {} def save(self, pypi_version, current_time): # Attempt to write out our version check file with open(self.statefile_path, "w") as statefile: json.dump( { "last_check": current_time.strftime(SELFCHECK_DATE_FMT), "pypi_version": pypi_version, }, statefile, sort_keys=True, separators=(",", ":") ) class GlobalSelfCheckState(object): def __init__(self): self.statefile_path = os.path.join(USER_CACHE_DIR, "selfcheck.json") # Load the existing state try: with open(self.statefile_path) as statefile: self.state = json.load(statefile)[sys.prefix] except (IOError, ValueError, KeyError): self.state = {} def save(self, pypi_version, current_time): # Check to make sure that we own the directory if not check_path_owner(os.path.dirname(self.statefile_path)): return # Now that we've ensured the directory is owned by this user, we'll go # ahead and make sure that all our directories are created. ensure_dir(os.path.dirname(self.statefile_path)) # Attempt to write out our version check file with lockfile.LockFile(self.statefile_path): if os.path.exists(self.statefile_path): with open(self.statefile_path) as statefile: state = json.load(statefile) else: state = {} state[sys.prefix] = { "last_check": current_time.strftime(SELFCHECK_DATE_FMT), "pypi_version": pypi_version, } with open(self.statefile_path, "w") as statefile: json.dump(state, statefile, sort_keys=True, separators=(",", ":")) def load_selfcheck_statefile(): if running_under_virtualenv(): return VirtualenvSelfCheckState() else: return GlobalSelfCheckState() def pip_installed_by_pip(): """Checks whether pip was installed by pip This is used not to display the upgrade message when pip is in fact installed by system package manager, such as dnf on Fedora. """ import pkg_resources try: dist = pkg_resources.get_distribution('pip') return (dist.has_metadata('INSTALLER') and 'pip' in dist.get_metadata_lines('INSTALLER')) except pkg_resources.DistributionNotFound: return False def pip_version_check(session): """Check for an update for pip. Limit the frequency of checks to once per week. State is stored either in the active virtualenv or in the user's USER_CACHE_DIR keyed off the prefix of the pip script path. """ installed_version = get_installed_version("pip") if installed_version is None: return pip_version = packaging_version.parse(installed_version) pypi_version = None try: state = load_selfcheck_statefile() current_time = datetime.datetime.utcnow() # Determine if we need to refresh the state if "last_check" in state.state and "pypi_version" in state.state: last_check = datetime.datetime.strptime( state.state["last_check"], SELFCHECK_DATE_FMT ) if total_seconds(current_time - last_check) < 7 * 24 * 60 * 60: pypi_version = state.state["pypi_version"] # Refresh the version if we need to or just see if we need to warn if pypi_version is None: resp = session.get( PyPI.pip_json_url, headers={"Accept": "application/json"}, ) resp.raise_for_status() pypi_version = [ v for v in sorted( list(resp.json()["releases"]), key=packaging_version.parse, ) if not packaging_version.parse(v).is_prerelease ][-1] # save that we've performed a check state.save(pypi_version, current_time) remote_version = packaging_version.parse(pypi_version) # Determine if our pypi_version is older if (pip_version < remote_version and pip_version.base_version != remote_version.base_version and pip_installed_by_pip()): # Advise "python -m pip" on Windows to avoid issues # with overwriting pip.exe. if WINDOWS: pip_cmd = "python -m pip" else: pip_cmd = "pip" logger.warning( "You are using pip version %s, however version %s is " "available.\nYou should consider upgrading via the " "'%s install --upgrade pip' command.", pip_version, pypi_version, pip_cmd ) except Exception: logger.debug( "There was an error checking the latest version of pip", exc_info=True, ) __pycache__/filesystem.cpython-36.opt-1.pyc 0000644 00000001064 14722165061 0014532 0 ustar 00 3 . g @ s( d dl Z d dlZ d dlmZ dd ZdS ) N)get_path_uidc C s t tdsdS d }xp| |krtjj| rntj dkr^yt| }W n tk rT dS X |dkS tj| tjS q| tjj | }} qW d S )NgeteuidTr F) hasattrospathlexistsr r OSErroraccessW_OKdirname)r ZpreviousZpath_uid r /usr/lib/python3.6/filesystem.pycheck_path_owner s r )r Zos.pathZ pip.compatr r r r r r s __pycache__/filesystem.cpython-36.pyc 0000644 00000001064 14722165061 0013573 0 ustar 00 3 . g @ s( d dl Z d dlZ d dlmZ dd ZdS ) N)get_path_uidc C s t tdsdS d }xp| |krtjj| rntj dkr^yt| }W n tk rT dS X |dkS tj| tjS q| tjj | }} qW d S )NgeteuidTr F) hasattrospathlexistsr r OSErroraccessW_OKdirname)r ZpreviousZpath_uid r /usr/lib/python3.6/filesystem.pycheck_path_owner s r )r Zos.pathZ pip.compatr r r r r r s __pycache__/hashes.cpython-36.pyc 0000644 00000006227 14722165061 0012670 0 ustar 00 3 . g2 @ sz d dl mZ d dlZd dlmZmZmZ d dlmZ d dl m Z mZmZ dZ dddgZG d d d eZG dd deZdS ) )absolute_importN)HashMismatchHashMissingInstallationError)read_chunks) iteritemsiterkeys itervaluesZsha256Zsha384Zsha512c @ sJ e Zd ZdZdddZdd Zdd Zd d Zdd Zd d Z dd Z dS )HasheszaA wrapper that builds multiple hashes at once and checks them against known-good values Nc C s |dkri n|| _ dS )zo :param hashes: A dict of algorithm names pointing to lists of allowed hex digests N)_allowed)selfhashes r /usr/lib/python3.6/hashes.py__init__ s zHashes.__init__c C s i }xJt | jD ]<}ytj|||<