Initial commit xmarticaims

This commit is contained in:
2026-11-02 10:26:32 -06:00
commit e74236f5c1
9764 changed files with 2880647 additions and 0 deletions
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 80 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

@@ -0,0 +1,6 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 80 80">
<path d="M40 0C17.9 0 0 17.9 0 40s17.9 40 40 40 40-17.9 40-40S62.1 0 40 0zm0 72C22.3 72 8 57.7 8 40S22.3 8 40 8s32 14.3 32 32-14.3 32-32 32z"
opacity=".15"/>
<path fill="#3568B7"
d="M75.8 47.4h-.4c-2.2-.2-3.8-2.2-3.6-4.4.1-1 .1-2 .1-3C72 22.4 57.6 8 40 8c-2.2 0-4-1.8-4-4s1.8-4 4-4c22.1 0 40 17.9 40 40 0 1.3-.1 2.5-.2 3.8-.2 2.1-1.9 3.6-4 3.6z"/>
</svg>

After

Width:  |  Height:  |  Size: 444 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 78 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 129 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 131 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 77 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.3 KiB

@@ -0,0 +1,418 @@
/* WPCode Packs — pack-specific styles only.
Sidebar, grid, list items, and buttons use the existing plugin styles
(wpcode-items-sidebar, wpcode-items-list-category, wpcode-list-item,
wpcode-button*) — no overrides needed there. */
/* ===========================================================
Pack card icon + category badge (inside wpcode-list-item)
=========================================================== */
/* Installed-state indicator: subtle 3px green left accent strip. */
.wpcode-pack-list-item[data-installed="1"] {
border-left: 3px solid var(--wpcode-notice-success-bg, #009966);
}
.wpcode-pack-list-item .wpcode-pack-head {
display: flex;
align-items: stretch;
gap: 12px;
margin-bottom: 8px;
}
.wpcode-pack-list-item .wpcode-pack-head-text {
flex: 1;
min-width: 0;
display: flex;
flex-direction: column;
justify-content: center;
gap: 4px;
}
.wpcode-pack-list-item h3 {
margin: 0;
}
.wpcode-pack-icon {
width: 48px;
min-height: 48px;
border-radius: 6px;
display: grid;
place-items: center;
flex-shrink: 0;
background: var(--wpcode-background-highlight, #F6FAFF);
color: var(--wpcode-color-primary, #3568B7);
align-self: stretch;
}
.wpcode-pack-icon .dashicons {
font-size: 24px;
width: 24px;
height: 24px;
line-height: 1;
}
.wpcode-pack-icon-lg {
width: 56px;
height: 56px;
min-height: 56px;
border-radius: 10px;
}
.wpcode-pack-icon-lg .dashicons {
font-size: 30px;
width: 30px;
height: 30px;
}
.cat-badge {
display: inline-block;
padding: 2px 8px;
border-radius: 999px;
font-size: 11px;
font-weight: 600;
letter-spacing: 0.02em;
background: var(--wpcode-background-highlight, #F6FAFF);
color: var(--wpcode-color-primary, #3568B7);
align-self: flex-start;
width: auto;
}
/* Snippet name chips below the title (max 2 + "+N more"). */
.wpcode-pack-snippets {
display: flex;
flex-wrap: wrap;
gap: 6px;
margin: 6px 0 10px;
}
.wpcode-pack-snippet-chip {
display: inline-block;
max-width: 100%;
padding: 3px 8px;
border-radius: 4px;
border: 1px solid var(--wpcode-border-color, #e5e7eb);
background: var(--wpcode-background-gray, #f6f7f7);
color: var(--wpcode-text-color-paragraph, #50575e);
font-size: 11.5px;
font-weight: 500;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.wpcode-pack-snippet-chip-more {
background: transparent;
border-color: transparent;
color: var(--wpcode-text-color-highlight, #2271b1);
}
/* Pack card description (sits between the title row and the snippet chips). */
.wpcode-pack-desc {
margin: 0 0 10px;
font-size: 13px;
line-height: 1.45;
color: var(--wpcode-text-color-paragraph, #50575e);
}
/* Pack card footer — snippet chips on the left, button on the right, same row. */
.wpcode-pack-foot {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-top: 12px;
}
.wpcode-pack-foot .wpcode-pack-snippets {
margin: 0;
flex: 1;
min-width: 0;
}
.wpcode-pack-foot .wpcode-pack-actions {
flex-shrink: 0;
}
/* ----- NEW pill on the Packs tab button ----- */
.wpcode-library-tab-button .wpcode-tab-new-pill {
display: inline-block;
margin-left: 6px;
font-size: 10px;
font-weight: 700;
color: #fff;
background: var(--wpcode-color-primary, #3568B7);
padding: 2px 6px;
border-radius: 3px;
letter-spacing: 0.04em;
vertical-align: 2px;
}
/* ----- Danger variant on the secondary button (Remove pack) ----- */
.wpcode-button.wpcode-button-danger {
color: var(--wpcode-color-red, #DF2A35);
border-color: var(--wpcode-color-red, #DF2A35);
}
.wpcode-button.wpcode-button-danger:hover {
background: var(--wpcode-color-red, #DF2A35);
color: #fff;
}
/* ===========================================================
Detail view (post-install)
=========================================================== */
.wpcode-pack-detail-back {
display: inline-block;
margin: 0 0 16px;
font-size: 13px;
color: var(--wpcode-text-color-highlight, #2271b1);
text-decoration: none;
}
.wpcode-pack-detail-back:hover { text-decoration: underline; }
.wpcode-pack-detail {
background: var(--wpcode-background-white, #fff);
border: 1px solid var(--wpcode-border-color, #dcdcde);
border-radius: 4px;
padding: 24px;
}
.wpcode-detail-desc {
margin: 0 0 16px;
font-size: 13px;
line-height: 1.5;
color: var(--wpcode-text-color-paragraph, #50575e);
}
.wpcode-detail-actions {
display: flex;
justify-content: flex-end;
margin-top: 16px;
}
.wpcode-detail-head {
display: flex;
align-items: flex-start;
gap: 14px;
margin-bottom: 22px;
}
.wpcode-detail-head .info { flex: 1; min-width: 0; }
.wpcode-detail-head h2 {
margin: 0 0 6px;
font-size: var(--wpcode-font-size-xl, 22px);
font-weight: 600;
color: var(--wpcode-text-color-heading, #1d2327);
}
.wpcode-detail-head .meta-row {
display: flex;
gap: 10px;
align-items: center;
font-size: var(--wpcode-font-size-s, 14px);
color: var(--wpcode-text-color-paragraph, #646970);
}
.wpcode-detail-head .meta-row .dot {
width: 3px; height: 3px;
border-radius: 50%;
background: var(--wpcode-border-color, #c3c4c7);
}
.wpcode-detail-head .cat-name {
font-weight: 600;
color: var(--wpcode-text-color-highlight, #2271b1);
}
/* Snippets card */
.wpcode-snippets-card {
background: #fff;
border: 1px solid var(--wpcode-border-color, #dcdcde);
border-radius: 4px;
overflow: hidden;
}
.wpcode-snippets-card .head {
display: flex;
align-items: center;
justify-content: space-between;
padding: 12px 16px;
background: var(--wpcode-background-gray, #f8f8f8);
border-bottom: 1px solid var(--wpcode-border-color, #dcdcde);
}
.wpcode-snippets-card .head h3 {
margin: 0;
font-size: var(--wpcode-font-size-s, 14px);
font-weight: 600;
color: var(--wpcode-text-color-heading, #1d2327);
}
.wpcode-snippets-card .head .meta {
font-size: 12px;
color: var(--wpcode-text-color-paragraph, #646970);
}
.wpcode-snippet-row {
display: flex;
align-items: center;
gap: 14px;
padding: 14px 16px;
border-bottom: 1px solid var(--wpcode-border-color, #dcdcde);
}
.wpcode-snippet-row:last-child { border-bottom: 0; }
.wpcode-snippet-row .toggle-wrap { flex-shrink: 0; }
.wpcode-snippet-row .snippet-info { flex: 1; min-width: 0; }
.wpcode-snippet-row h5 {
margin: 0 0 2px;
font-size: var(--wpcode-font-size-s, 14px);
font-weight: 600;
color: var(--wpcode-text-color-heading, #1d2327);
}
.wpcode-snippet-row .actions { flex-shrink: 0; }
.wpcode-snippet-row.is-inactive h5 { color: #8c8f94; }
/* Hint shown on options flagged as needing personalization on the library. */
.wpcode-snippet-personalize-note {
display: inline-flex;
align-items: center;
gap: 4px;
margin-top: 2px;
font-size: var(--wpcode-font-size-xs, 12px);
color: #b26200;
}
.wpcode-snippet-personalize-note .dashicons {
width: 14px;
height: 14px;
font-size: 14px;
}
/* Note shown when a snippet is shared with (also part of) another pack. */
.wpcode-snippet-shared-note {
display: block;
margin-top: 2px;
font-size: var(--wpcode-font-size-xs, 12px);
color: var(--wpcode-text-color-paragraph, #646970);
}
/* Toggle switch */
.wpcode-toggle {
width: 36px; height: 20px;
border-radius: 999px;
background: #c3c4c7;
position: relative;
cursor: pointer;
transition: background 150ms ease;
flex-shrink: 0;
}
.wpcode-toggle::after {
content: "";
position: absolute;
top: 2px; left: 2px;
width: 16px; height: 16px;
border-radius: 50%;
background: #fff;
transition: transform 180ms cubic-bezier(0.4, 0, 0.2, 1);
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.2);
}
.wpcode-toggle.is-on { background: var(--wpcode-color-primary, #3568B7); }
.wpcode-toggle.is-on::after { transform: translateX(16px); }
/* ===========================================================
Install confirmation modal (renamed to wpcode-rmodal-* to
avoid colliding with the existing .wpcode-modal class in
src/admin/modal.css which is display:none by default).
=========================================================== */
.wpcode-rmodal-backdrop {
position: fixed; inset: 0;
background: rgba(16, 24, 40, 0.45);
display: grid;
place-items: center;
z-index: 100000;
}
.wpcode-rmodal {
background: #fff;
border-radius: 6px;
width: 520px;
max-width: calc(100vw - 40px);
box-shadow: 0 24px 48px -12px rgba(0, 0, 0, 0.25);
overflow: hidden;
}
.wpcode-rmodal-head {
padding: 18px 20px 12px;
border-bottom: 1px solid var(--wpcode-border-color, #f0f0f1);
}
.wpcode-rmodal-head h3 {
margin: 0;
font-size: 16px;
font-weight: 600;
color: var(--wpcode-text-color-heading, #1d2327);
}
.wpcode-rmodal-head .sub {
margin-top: 4px;
font-size: 12px;
color: var(--wpcode-text-color-paragraph, #646970);
}
.wpcode-rmodal-body { padding: 16px 20px; }
.wpcode-rmodal-body .js-wpcode-rmodal-lead {
margin: 0 0 12px;
font-size: 13px;
color: var(--wpcode-text-color-paragraph, #50575e);
}
.wpcode-rmodal-body .wpcode-checklist {
margin: 0;
padding: 0;
list-style: none;
border: 1px solid var(--wpcode-border-color, #f0f0f1);
border-radius: 4px;
overflow: hidden;
}
.wpcode-rmodal-body .wpcode-check-row {
padding: 9px 14px;
font-size: 13px;
border-bottom: 1px solid var(--wpcode-border-color, #f0f0f1);
}
.wpcode-rmodal-body .wpcode-check-row:last-child { border-bottom: 0; }
.wpcode-rmodal-body .wpcode-check-row.pending .label-name { color: #8c8f94; }
.wpcode-rmodal-body .wpcode-check-row.active { background: #f6faff; }
.wpcode-rmodal-body .wpcode-check-row.done { color: var(--wpcode-text-color-heading, #1d2327); }
.wpcode-rmodal-body .wpcode-progress-track {
height: 4px;
background: #f0f0f1;
border-radius: 999px;
margin: 14px 0 6px;
overflow: hidden;
}
.wpcode-rmodal-body .wpcode-progress-fill {
height: 100%;
background: var(--wpcode-color-primary, #3568B7);
transition: width 320ms cubic-bezier(0.4, 0, 0.2, 1);
}
.wpcode-rmodal-body .wpcode-progress-label {
display: flex;
justify-content: space-between;
font-size: 12px;
color: var(--wpcode-text-color-paragraph, #646970);
}
.wpcode-rmodal-body .wpcode-success-state {
display: flex;
flex-direction: column;
align-items: center;
text-align: center;
padding: 24px 16px 8px;
}
.wpcode-rmodal-body .wpcode-success-state[hidden] {
display: none;
}
.wpcode-rmodal-body .wpcode-success-state .wpcode-icon-checkmark {
margin-bottom: 14px;
}
.wpcode-rmodal-body .wpcode-success-state h4 {
margin: 0 0 6px;
font-size: 16px;
font-weight: 600;
color: var(--wpcode-text-color-heading, #1d2327);
}
.wpcode-rmodal-body .wpcode-success-state p {
margin: 0;
max-width: 340px;
font-size: 13px;
line-height: 1.5;
color: var(--wpcode-text-color-paragraph, #50575e);
}
.wpcode-rmodal-foot {
padding: 12px 20px 16px;
display: flex;
justify-content: flex-end;
gap: 8px;
border-top: 1px solid var(--wpcode-border-color, #f0f0f1);
background: var(--wpcode-background-gray, #fafafa);
}
@@ -0,0 +1,336 @@
/* global ajaxurl */
(function () {
'use strict';
const payloadEl = document.getElementById('wpcode-packs-payload');
if (!payloadEl) {
return;
}
const payload = JSON.parse(payloadEl.textContent);
const packs = payload.packs;
const nonce = payload.nonce;
const i18n = payload.i18n;
// ----- Install modal -----
function openInstallModal(slug) {
const data = packs[slug];
if (!data || !data.snippets || !data.snippets.length) {
return;
}
const tpl = document.getElementById('wpcode-packs-install-modal');
const node = tpl.content.firstElementChild.cloneNode(true);
document.body.appendChild(node);
const titleEl = node.querySelector('.js-wpcode-rmodal-title');
const subEl = node.querySelector('.js-wpcode-rmodal-sub span');
const leadEl = node.querySelector('.js-wpcode-rmodal-lead');
const listEl = node.querySelector('.wpcode-checklist');
const trackEl = node.querySelector('.wpcode-progress-track');
const labelEl = node.querySelector('.wpcode-progress-label');
const progressFill = node.querySelector('.wpcode-progress-fill');
const progressText = node.querySelector('.js-wpcode-progress-text');
const progressPercent = node.querySelector('.js-wpcode-progress-percent');
const successEl = node.querySelector('.wpcode-success-state');
const successHeading = node.querySelector('.js-wpcode-success-heading');
const successBody = node.querySelector('.js-wpcode-success-body');
const cancelBtn = node.querySelector('.js-wpcode-rmodal-cancel');
const primaryBtn = node.querySelector('.js-wpcode-rmodal-primary');
const primaryLabel = primaryBtn.querySelector('span');
titleEl.textContent = i18n.install_title.replace('%s', data.name);
subEl.textContent = i18n.snippets_subtitle
.replace('%1$d', data.snippets.length)
.replace('%2$s', data.category);
leadEl.textContent = i18n.confirm_lead;
data.snippets.forEach(function (s) {
const row = document.createElement('li');
row.className = 'wpcode-check-row pending';
const label = document.createElement('span');
label.className = 'label-name';
label.textContent = s;
row.appendChild(label);
listEl.appendChild(row);
});
cancelBtn.textContent = i18n.cancel;
primaryLabel.textContent = i18n.install_button;
function close() {
node.remove();
}
node.addEventListener('click', function (e) {
if (e.target === node) {
close();
}
});
cancelBtn.addEventListener('click', close);
// Guard so the success-state primary button (rebound to a redirect) can't
// re-trigger an install when clicked.
let installing = false;
primaryBtn.addEventListener('click', function () {
if (installing) {
return;
}
installing = true;
titleEl.textContent = i18n.installing_title.replace('%s', data.name);
primaryBtn.disabled = true;
primaryLabel.textContent = i18n.installing_button;
cancelBtn.style.display = 'none';
const rows = listEl.querySelectorAll('.wpcode-check-row');
let step = 0;
trackEl.hidden = false;
labelEl.hidden = false;
progressText.textContent = i18n.creating_snippets;
function tick() {
if (step >= rows.length) {
return;
}
rows[step].classList.remove('pending');
rows[step].classList.add('active');
}
tick();
const interval = setInterval(function () {
const r = rows[step];
if (!r) {
return;
}
r.classList.remove('active');
r.classList.add('done');
step += 1;
const pct = Math.round((step / rows.length) * 100);
progressFill.style.width = pct + '%';
progressPercent.textContent = pct + '%';
if (step >= rows.length) {
clearInterval(interval);
} else {
tick();
}
}, 520);
const fd = new FormData();
fd.append('action', 'wpcode_install_pack');
fd.append('nonce', nonce);
fd.append('slug', slug);
fetch(ajaxurl, { method: 'POST', body: fd })
.then(function (r) { return r.json(); })
.then(function (resp) {
if (!resp.success) {
clearInterval(interval);
alert(resp.data && resp.data.message ? resp.data.message : 'Install failed');
close();
return;
}
function showSuccess() {
if (step < rows.length) {
setTimeout(showSuccess, 200);
return;
}
titleEl.textContent = i18n.installed_title.replace('%s', data.name);
leadEl.hidden = true;
listEl.hidden = true;
trackEl.hidden = true;
labelEl.hidden = true;
successEl.hidden = false;
// Report the real outcome, not an optimistic "all activated".
// A snippet can fail to create (failed_options) or fail its
// activation safety check (activation_failed).
const result = (resp.data && resp.data.result) || {};
const total = data.snippets.length;
const issues =
((result.failed_options || []).length) +
((result.activation_failed || []).length);
// Prefer the server's real active count; fall back to total - issues.
const active = typeof result.active_count === 'number'
? result.active_count
: Math.max(0, total - issues);
if (active < total) {
successHeading.textContent = i18n.success_heading_partial
.replace('%1$d', active)
.replace('%2$d', total);
successBody.textContent = i18n.success_body_partial;
} else {
successHeading.textContent = i18n.success_heading.replace('%d', total);
successBody.textContent = i18n.success_body;
}
primaryBtn.disabled = false;
primaryLabel.textContent = i18n.open_dashboard;
cancelBtn.style.display = '';
cancelBtn.textContent = i18n.back_to_packs;
primaryBtn.onclick = function () {
window.location.href = resp.data.redirect_url;
};
}
showSuccess();
})
.catch(function () {
clearInterval(interval);
alert('Install failed');
close();
});
});
}
// ----- Card click → install -----
document.querySelectorAll('.js-wpcode-open-install').forEach(function (btn) {
btn.addEventListener('click', function (e) {
e.preventDefault();
e.stopPropagation();
const card = btn.closest('.wpcode-list-item');
if (!card) {
return;
}
openInstallModal(card.dataset.packSlug);
});
});
// ----- Toggle -----
document.querySelectorAll('.js-wpcode-toggle-option').forEach(function (el) {
el.addEventListener('click', function () {
const row = el.closest('.wpcode-snippet-row');
const detail = el.closest('.wpcode-pack-detail');
if (!row || !detail) {
return;
}
const libraryId = row.dataset.libraryId;
const slug = detail.dataset.packSlug;
const turnOn = !el.classList.contains('is-on');
function setToggle(state) {
el.classList.toggle('is-on', state);
el.setAttribute('aria-checked', state ? 'true' : 'false');
row.classList.toggle('is-inactive', !state);
}
// Optimistic update, reconciled to the server's real state below.
setToggle(turnOn);
const fd = new FormData();
fd.append('action', 'wpcode_toggle_pack_option');
fd.append('nonce', detail.dataset.nonce);
fd.append('slug', slug);
fd.append('library_id', libraryId);
fd.append('active', turnOn ? '1' : '0');
fetch(ajaxurl, { method: 'POST', body: fd })
.then(function (r) { return r.json(); })
.then(function (resp) {
if (resp && resp.success && resp.data) {
// Sync to the real state — activation can be refused.
setToggle(!!resp.data.active);
if (resp.data.activation_refused) {
window.alert(i18n.activation_refused);
}
} else {
setToggle(!turnOn);
}
})
.catch(function () {
setToggle(!turnOn);
});
});
el.addEventListener('keydown', function (e) {
if (e.key === ' ' || e.key === 'Enter') {
e.preventDefault();
el.click();
}
});
});
// ----- Add / Reinstall option -----
document.querySelectorAll('.js-wpcode-add-option').forEach(function (btn) {
btn.addEventListener('click', function () {
const row = btn.closest('.wpcode-snippet-row');
const detail = btn.closest('.wpcode-pack-detail');
if (!row || !detail) {
return;
}
btn.disabled = true;
const fd = new FormData();
fd.append('action', 'wpcode_add_pack_option');
fd.append('nonce', detail.dataset.nonce);
fd.append('slug', detail.dataset.packSlug);
fd.append('library_id', row.dataset.libraryId);
fetch(ajaxurl, { method: 'POST', body: fd })
.then(function (r) { return r.json(); })
.then(function (resp) {
// Already installed (e.g. a concurrent add) is not an error —
// the snippet is present, so just refresh to show it.
if (resp.success || (resp.data && resp.data.code === 'already_installed')) {
window.location.reload();
} else {
btn.disabled = false;
alert(resp.data && resp.data.message ? resp.data.message : 'Could not add option');
}
})
.catch(function () {
btn.disabled = false;
});
});
});
// ----- Remove pack -----
document.querySelectorAll('.js-wpcode-remove-pack').forEach(function (btn) {
btn.addEventListener('click', function () {
const detail = btn.closest('.wpcode-pack-detail');
if (!detail) {
return;
}
const packName = document.querySelector('.wpcode-detail-head h2').textContent;
const snippetCount = detail.querySelectorAll('.wpcode-snippet-row').length;
const msg = i18n.confirm_remove
.replace('%1$s', packName)
.replace('%2$d', snippetCount);
function doRemove() {
const fd = new FormData();
fd.append('action', 'wpcode_remove_pack');
fd.append('nonce', detail.dataset.nonce);
fd.append('slug', detail.dataset.packSlug);
fetch(ajaxurl, { method: 'POST', body: fd })
.then(function (r) { return r.json(); })
.then(function (resp) {
if (resp.success) {
window.location.href = resp.data.redirect_url;
}
});
}
// Use WPCode's jquery-confirm dialog to match the rest of the admin,
// falling back to the native confirm if it isn't available.
const jq = window.jQuery;
if (jq && typeof jq.confirm === 'function') {
jq.confirm({
title: i18n.remove_title,
content: msg,
type: 'blue',
backgroundDismiss: true,
buttons: {
confirm: {
text: i18n.remove_confirm_button,
btnClass: 'wpcode-btn-confirm',
action: doRemove
},
cancel: {
text: i18n.cancel
}
}
});
} else if (window.confirm(msg)) {
doRemove();
}
});
});
})();
@@ -0,0 +1 @@
<?php return array('dependencies' => array(), 'version' => 'c95624a69c80301272a0');
@@ -0,0 +1,2 @@
#wpadminbar .wpcode-admin-bar-info-separator-top{margin-top:5px;padding-top:5px;border-top:1px solid}#wpadminbar .wpcode-admin-bar-description .ab-item{font-weight:700}#wpadminbar .wpcode-pro-indicator{background:#bbb;color:#333 !important;text-transform:uppercase;padding:4px 7px;border-radius:9px;font-size:8px;line-height:1;display:inline-block;vertical-align:text-top;font-weight:600}#wpadminbar #wp-admin-bar-wpcode-upgrade a{background-color:#59A56D !important;color:#fff !important}#wpadminbar .quicklinks .wpcode-admin-bar-upsell-submenu .ab-empty-item{display:none}#wpadminbar .quicklinks .wpcode-admin-bar-has-upsell-submenu .ab-sub-wrapper{background:transparent;box-shadow:none}#wpadminbar .wpcode-admin-bar-submenu-upsell{min-width:660px;border-radius:8px;box-shadow:0 2px 5px rgba(0,0,0,.2);background:#fff;color:#1d2327;padding:40px;text-align:center}#wpadminbar .wpcode-admin-bar-submenu-upsell .wpcode-heading{font-size:24px;padding:8px 12px;line-height:1.5}#wpadminbar .wpcode-admin-bar-submenu-upsell p{color:#777777;font-size:16px;margin:16px 0;line-height:1.5}#wpadminbar .wpcode-admin-bar-submenu-upsell .wpcode-button{margin-top:6px !important;background-color:#E06B44;color:#fff !important;font-size:16px;display:inline-block;border-radius:4px;padding:10px 36px;font-weight:700;height:auto}#wpadminbar .wpcode-menu-notification-counter{display:inline-block !important;min-width:18px !important;height:18px !important;border-radius:9px !important;margin:7px 0 0 2px !important;vertical-align:top !important;font-size:11px !important;line-height:1.6 !important;text-align:center !important}#wpadminbar .wpcode-admin-bar-info-submenu .wpcode-menu-notification-counter{float:right;margin-top:5px !important}body:not(.wp-admin) .wpcode-menu-notification-counter{background-color:#d63638 !important;color:#ffffff !important}.wpcode-testing-mode #wp-admin-bar-wpcode-admin-bar-info>.ab-item{color:#fff;background-color:#09A347}
@@ -0,0 +1 @@
(()=>{"use strict";document.addEventListener("DOMContentLoaded",function(){!function(){if(window.wpcode_admin_bar_info){var e=document.getElementById("wp-admin-bar-wpcode-loaded-on-this-page");if(e){var a=e.querySelector(".ab-submenu");a.innerHTML="",wpcode_admin_bar_info.forEach(function(e){var n=document.createElement("li");n.className="wpcode-admin-bar-info-location menupop",n.setAttribute("data-location-id",e.location_id),n.innerHTML='<a class="ab-item" aria-haspopup="true" href="'+e.href+'"><span class="wp-admin-bar-arrow" aria-hidden="true"></span>'+e.label+"</a>";var i=document.createElement("ul");i.className="ab-submenu",e.snippets.forEach(function(e){var a=document.createElement("li");a.className="wpcode-admin-bar-info-snippet",a.setAttribute("data-snippet-id",e.id),a.innerHTML='<a href="'+e.edit_link+'" class="ab-item">'+e.title+"</a>",i.appendChild(a)});var t=document.createElement("div");t.className="ab-sub-wrapper",t.appendChild(i),n.appendChild(t),a.appendChild(n)})}if(0===wpcode_admin_bar_info_count){var n=document.querySelector("#wp-admin-bar-wpcode-loaded-on-this-page .wp-admin-bar-arrow");n&&(n.style.display="none")}var i=document.querySelector("#wp-admin-bar-wpcode-loaded-on-this-page > .ab-item");i&&(i.innerHTML+=" ("+wpcode_admin_bar_info_count+")")}}()})})();
@@ -0,0 +1 @@
<?php return array('dependencies' => array(), 'version' => '981c2c1b0bc4dc9f90f3');
File diff suppressed because one or more lines are too long
@@ -0,0 +1 @@
(()=>{var e={744(){jQuery(function(e){e(".wpcode-admin-tabs-navigation").on("click",".wpcode-admin-tabs button",function(t){t.preventDefault();const r=e(this).data("target");e(this).addClass("active").parent().siblings().find("button").removeClass("active"),e(document.getElementById(r)).addClass("active").siblings().removeClass("active"),e(document).trigger("wpcode-tab-change",r),window.wpcode_editor&&jQuery.each(window.wpcode_editor,function(e,t){t.codemirror.refresh()})})})}},t={};function r(o){var n=t[o];if(void 0!==n)return n.exports;var a=t[o]={exports:{}};return e[o](a,a.exports,r),a.exports}r.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return r.d(t,{a:t}),t},r.d=(e,t)=>{for(var o in t)r.o(t,o)&&!r.o(e,o)&&Object.defineProperty(e,o,{enumerable:!0,get:t[o]})},r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),(()=>{"use strict";r(744)})()})();
@@ -0,0 +1 @@
<?php return array('dependencies' => array('jquery'), 'version' => '7490ccfa5e2931fd0100');
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1 @@
<?php return array('dependencies' => array(), 'version' => '23af03e215b7a990b5ad');
@@ -0,0 +1 @@
(()=>{"use strict";(window.WPCodeConnect||function(n,o,t){jconfirm.defaults={closeIcon:!1,backgroundDismiss:!1,escapeKey:!0,animationBounce:1,useBootstrap:!1,theme:"modern",boxWidth:"560px",type:"blue",animateFromElement:!1,scrollToPreviousElement:!1};var e={$connectBtn:t("#wpcode-settings-connect-btn"),$connectKey:t("#wpcode-settings-upgrade-license-key")},c="<div class='excl-mark'>!</div>",i={init:function(){console.log("WPCodeConnect: init"),t(i.ready)},ready:function(){i.events()},events:function(){i.connectBtnClick()},connectBtnClick:function(){e.$connectBtn.on("click",function(){i.gotoUpgradeUrl()})},proAlreadyInstalled:function(n){const e=WPCodeSVG.WPCodeIcon("checkmark",88,88,"0 0 130.2 130.2","iconId","path circle");t.confirm({title:e+wpcode.almost_done,content:n.data.message,type:"blue",buttons:{confirm:{text:wpcode.plugin_activate_btn,btnClass:"wpcode-btn-confirm",action:function(){o.location.reload()}}}})},gotoUpgradeUrl:function(){var n={action:"wpcode_connect_url",key:e.$connectKey.val(),_wpnonce:wpcode.nonce};t.post(ajaxurl,n).done(function(n){if(n.success)return n.data.reload?void i.proAlreadyInstalled(n):void(o.location.href=n.data.url);t.confirm({title:c+wpcode.oops,closeIcon:!1,content:n.data.message,type:"blue",buttons:{ok:{text:wpcode.ok,btnClass:"wpcode-btn-confirm",action:function(){}}}})}).fail(function(n){i.failAlert(n)})},failAlert:function(n){t.confirm({title:c+wpcode.oops,content:wpcode.server_error+"<br>"+n.status+" "+n.statusText+" "+n.responseText,type:"blue",buttons:{ok:{text:wpcode.ok,btnClass:"wpcode-btn-confirm",action:function(){}}}})}};return i}(document,window,jQuery)).init()})();
@@ -0,0 +1 @@
<?php return array('dependencies' => array(), 'version' => '0d17e0791c807b87b205');
@@ -0,0 +1 @@
(window.WPCodeCSSLivePreview||function(e,t){const n={previewStyle:null,adminOrigin:null,previewParams:null,init:function(){"undefined"!=typeof wpcodePreviewFrame&&(n.adminOrigin=new URL(wpcodePreviewFrame.adminUrl).origin,n.previewParams={wpcode_preview:"1",snippet_id:String(wpcodePreviewFrame.snippetId)},n.inject_css(),n.listen_for_updates(),n.ensure_preview_navigation(),n.send_ready_message())},inject_css:function(){const i="wpcode-snippet-"+(wpcodePreviewFrame.codeType||"css")+"-"+String(wpcodePreviewFrame.snippetId);if(n.previewStyle=e.getElementById(i),t.parent&&t.parent!==t)try{t.parent.postMessage({action:n.previewStyle?"cssFound":"cssNotFound",snippetId:String(wpcodePreviewFrame.snippetId)},n.adminOrigin)}catch(e){}},listen_for_updates:function(){t.addEventListener("message",function(e){if(e.origin!==n.adminOrigin)return;const t=e.data;"updateCSS"===t.action&&void 0!==t.css&&n.previewStyle&&(n.previewStyle.textContent=t.css)})},ensure_preview_navigation:function(){const i=function(e){try{const i=new URL(e,t.location.href);return i.origin!==t.location.origin?e:(i.searchParams.set("wpcode_preview",n.previewParams.wpcode_preview),i.searchParams.set("snippet_id",n.previewParams.snippet_id),i.toString())}catch(t){return e}};!function(){const t=e.getElementsByTagName("a"),r=t.length;for(let e=0;e<r;e++)n.rewriteLinkHref(t[e],i);const o=e.getElementsByTagName("form"),a=o.length;for(let e=0;e<a;e++)n.rewriteForm(o[e],i,n.previewParams.snippet_id)}(),e.addEventListener("click",function(t){if(t.defaultPrevented||0!==t.button||t.metaKey||t.ctrlKey||t.shiftKey||t.altKey)return;let n=t.target;for(;n&&n!==e.body;){if(n.tagName&&"a"===n.tagName.toLowerCase()){const e=n.getAttribute("href");e&&0!==e.indexOf("#")&&""!==e.trim()&&n.setAttribute("href",i(e));break}n=n.parentNode}},!0),new MutationObserver(function(e){const t=e.length;for(let r=0;r<t;r++){const t=e[r].addedNodes,o=t.length;for(let e=0;e<o;e++){const r=t[e];if(1!==r.nodeType)continue;r.tagName&&("a"===r.tagName.toLowerCase()&&n.rewriteLinkHref(r,i),"form"===r.tagName.toLowerCase()&&n.rewriteForm(r,i,n.previewParams.snippet_id));const o=r.querySelectorAll?r.querySelectorAll("a[href]"):[],a=o.length;for(let e=0;e<a;e++)n.rewriteLinkHref(o[e],i);const s=r.querySelectorAll?r.querySelectorAll("form"):[],p=s.length;for(let e=0;e<p;e++)n.rewriteForm(s[e],i,n.previewParams.snippet_id)}}}).observe(e.documentElement||e.body,{childList:!0,subtree:!0})},send_ready_message:function(){t.parent!==t&&t.parent.postMessage({action:"previewReady",snippetId:wpcodePreviewFrame.snippetId},n.adminOrigin)},rewriteLinkHref:function(e,t){const n=e.getAttribute("href");if(e.hasAttribute("href")&&n&&""!==n.trim()){const i=t(n);i!==n&&e.setAttribute("href",i)}},rewriteForm:function(n,i,r){const o=(n.getAttribute("method")||"GET").toUpperCase(),a=n.getAttribute("action")||t.location.href;if("GET"===o){const e=i(a);e!==a&&n.setAttribute("action",e)}else{if(!n.querySelector('input[name="wpcode_preview"]')){const t=e.createElement("input");t.type="hidden",t.name="wpcode_preview",t.value="1",n.appendChild(t)}if(!n.querySelector('input[name="snippet_id"]')){const t=e.createElement("input");t.type="hidden",t.name="snippet_id",t.value=r,n.appendChild(t)}}}};return n}(document,window,jQuery)).init();
@@ -0,0 +1 @@
<?php return array('dependencies' => array(), 'version' => '0b691f4bb2185cdcf818');
@@ -0,0 +1 @@
(()=>{"use strict";(window.WPCodeAdminWideNotices||function(i,e,c){var o={init:function(){c(o.ready)},ready:function(){o.events()},events:function(){c(i).on("click",".wpcode-notice .notice-dismiss, .wpcode-notice .wpcode-notice-dismiss",o.dismissNotice)},dismissNotice:function(i){i.target.classList.contains("wpcode-notice-dismiss")&&c(this).closest(".wpcode-notice").slideUp(),c.post(wpcode_admin_notices.ajax_url,{action:"wpcode_notice_dismiss",_wpnonce:wpcode_admin_notices.nonce,id:(c(this).closest(".wpcode-notice").attr("id")||"").replace("wpcode-notice-","")})}};return o}(document,window,jQuery)).init()})();
@@ -0,0 +1,464 @@
<?php
/**
* Plugin Name: WPCode Lite
* Plugin URI: https://www.wpcode.com/
* Version: 2.3.9
* Requires at least: 5.0
* Requires PHP: 7.0
* Tested up to: 7.1
* Author: WPCode
* Author URI: https://www.wpcode.com/
* Description: Easily add code snippets in WordPress. Insert scripts to the header and footer, add PHP code snippets with conditional logic, insert ads pixel, custom content, and more.
* License: GPLv2 or later
*
* Text Domain: insert-headers-and-footers
* Domain Path: /languages
*
* @package WPCode
*/
/*
Copyright 2019 WPBeginner
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License, version 2, as
published by the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
// Don't allow multiple versions to be active.
if ( function_exists( 'WPCode' ) ) {
if ( ! function_exists( 'wpcode_pro_just_activated' ) ) {
/**
* When we activate a Pro version, we need to do additional operations:
* 1) deactivate a Lite version;
* 2) register option which help to run all activation process for Pro version (custom tables creation, etc.).
*/
function wpcode_pro_just_activated() {
wpcode_deactivate();
add_option( 'wpcode_install', 1 );
}
}
add_action( 'activate_wpcode-premium/wpcode.php', 'wpcode_pro_just_activated' );
if ( ! function_exists( 'wpcode_lite_just_activated' ) ) {
/**
* Store temporarily that the Lite version of the plugin was activated.
* This is needed because WP does a redirect after activation and
* we need to preserve this state to know whether user activated Lite or not.
*/
function wpcode_lite_just_activated() {
set_transient( 'wpcode_lite_just_activated', true );
}
}
add_action( 'activate_insert-headers-and-footers/ihaf.php', 'wpcode_lite_just_activated' );
if ( ! function_exists( 'wpcode_lite_just_deactivated' ) ) {
/**
* Store temporarily that Lite plugin was deactivated.
* Convert temporary "activated" value to a global variable,
* so it is available through the request. Remove from the storage.
*/
function wpcode_lite_just_deactivated() {
global $wpcode_lite_just_activated, $wpcode_lite_just_deactivated;
$wpcode_lite_just_activated = (bool) get_transient( 'wpcode_lite_just_activated' );
$wpcode_lite_just_deactivated = true;
delete_transient( 'wpcode_lite_just_activated' );
}
}
add_action( 'deactivate_insert-headers-and-footers/ihaf.php', 'wpcode_lite_just_deactivated' );
if ( ! function_exists( 'wpcode_deactivate' ) ) {
/**
* Deactivate Lite if WPCode already activated.
*/
function wpcode_deactivate() {
$plugin = 'insert-headers-and-footers/ihaf.php';
deactivate_plugins( $plugin );
do_action( 'wpcode_plugin_deactivated', $plugin );
}
}
add_action( 'admin_init', 'wpcode_deactivate' );
if ( ! function_exists( 'wpcode_lite_notice' ) ) {
/**
* Display the notice after deactivation when Pro is still active
* and user wanted to activate the Lite version of the plugin.
*/
function wpcode_lite_notice() {
global $wpcode_lite_just_activated, $wpcode_lite_just_deactivated;
if (
empty( $wpcode_lite_just_activated ) ||
empty( $wpcode_lite_just_deactivated )
) {
return;
}
// Currently tried to activate Lite with Pro still active, so display the message.
printf(
'<div class="notice notice-warning">
<p>%1$s</p>
<p>%2$s</p>
</div>',
esc_html__( 'Heads up!', 'insert-headers-and-footers' ),
esc_html__( 'Your site already has WPCode Pro activated. If you want to switch to WPCode Lite, please first go to Plugins → Installed Plugins and deactivate WPCode. Then, you can activate WPCode Lite.', 'insert-headers-and-footers' )
);
if ( isset( $_GET['activate'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
unset( $_GET['activate'] ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended
}
unset( $wpcode_lite_just_activated, $wpcode_lite_just_deactivated );
}
}
add_action( 'admin_notices', 'wpcode_lite_notice' );
// Do not process the plugin code further.
return;
}
/**
* Main WPCode Class
*/
class WPCode {
/**
* Holds the instance of the plugin.
*
* @since 2.0.0
*
* @var WPCode The one true WPCode
*/
private static $instance;
/**
* Plugin version.
*
* @since 2.0.0
*
* @var string
*/
public $version = '';
/**
* The auto-insert instance.
*
* @var WPCode_Auto_Insert
*/
public $auto_insert;
/**
* The snippet execution instance.
*
* @var WPCode_Snippet_Execute
*/
public $execute;
/**
* The error handling instance.
*
* @var WPCode_Error
*/
public $error;
/**
* The conditional logic instance.
*
* @var WPCode_Conditional_Logic
*/
public $conditional_logic;
/**
* The conditional logic instance.
*
* @var WPCode_Snippet_Cache
*/
public $cache;
/**
* The snippet library.
*
* @var WPCode_Library
*/
public $library;
/**
* The Snippet Generator.
*
* @var WPCode_Generator
*/
public $generator;
/**
* The plugin settings.
*
* @var WPCode_Settings
*/
public $settings;
/**
* The plugin importers.
*
* @var WPCode_Importers
*/
public $importers;
/**
* The file cache class.
*
* @var WPCode_File_Cache
*/
public $file_cache;
/**
* The notifications instance (admin-only).
*
* @var WPCode_Notifications
*/
public $notifications;
/**
* The admin page loader.
*
* @var WPCode_Admin_Page_Loader
*/
public $admin_page_loader;
/**
* The library auth instance.
*
* @var WPCode_Library_Auth
*/
public $library_auth;
/**
* The admin notices instance.
*
* @var WPCode_Notice
*/
public $notice;
/**
* Instance for logging errors.
*
* @var WPCode_File_Logger
*/
public $logger;
/**
* Load the smart tags.
*
* @var WPCode_Smart_Tags
*/
public $smart_tags;
/**
* Main instance of WPCode.
*
* @return WPCode
* @since 2.0.0
*/
public static function instance() {
if ( ! isset( self::$instance ) && ! ( self::$instance instanceof WPCode ) ) {
self::$instance = new WPCode();
}
return self::$instance;
}
/**
* Constructor.
*/
private function __construct() {
$this->setup_constants();
$this->includes();
add_action( 'plugins_loaded', array( $this, 'load_components' ), - 1 );
}
/**
* Set up global constants.
*
* @return void
*/
private function setup_constants() {
define( 'WPCODE_FILE', __FILE__ );
$plugin_headers = get_file_data( WPCODE_FILE, array( 'version' => 'Version' ) );
define( 'WPCODE_VERSION', $plugin_headers['version'] );
define( 'WPCODE_PLUGIN_BASENAME', plugin_basename( WPCODE_FILE ) );
define( 'WPCODE_PLUGIN_URL', plugin_dir_url( WPCODE_FILE ) );
define( 'WPCODE_PLUGIN_PATH', plugin_dir_path( WPCODE_FILE ) );
$this->version = WPCODE_VERSION;
}
/**
* Require the files needed for the plugin.
*
* @return void
*/
private function includes() {
// Load the safe mode logic first.
require_once WPCODE_PLUGIN_PATH . 'includes/safe-mode.php';
// Plugin helper functions.
require_once WPCODE_PLUGIN_PATH . 'includes/helpers.php';
// Functions for global headers & footers output.
require_once WPCODE_PLUGIN_PATH . 'includes/global-output.php';
// Use the old class name for backwards compatibility.
require_once WPCODE_PLUGIN_PATH . 'includes/legacy.php';
// Add backwards compatibility for older versions of PHP or WP.
require_once WPCODE_PLUGIN_PATH . 'includes/compat.php';
// Register code snippets post type.
require_once WPCODE_PLUGIN_PATH . 'includes/post-type.php';
// The snippet class.
require_once WPCODE_PLUGIN_PATH . 'includes/class-wpcode-snippet.php';
// Auto-insert options.
require_once WPCODE_PLUGIN_PATH . 'includes/class-wpcode-auto-insert.php';
// Execute snippets.
require_once WPCODE_PLUGIN_PATH . 'includes/class-wpcode-snippet-execute.php';
// Handle PHP errors.
require_once WPCODE_PLUGIN_PATH . 'includes/class-wpcode-error.php';
// [wpcode] shortcode.
require_once WPCODE_PLUGIN_PATH . 'includes/shortcode.php';
// Conditional logic.
require_once WPCODE_PLUGIN_PATH . 'includes/class-wpcode-conditional-logic.php';
// Snippet Cache.
require_once WPCODE_PLUGIN_PATH . 'includes/class-wpcode-snippet-cache.php';
// Settings class.
require_once WPCODE_PLUGIN_PATH . 'includes/class-wpcode-settings.php';
// Custom capabilities.
require_once WPCODE_PLUGIN_PATH . 'includes/class-wpcode-capabilities.php';
// Map capabilities for backwards compatibility.
require_once WPCODE_PLUGIN_PATH . 'includes/capabilities.php';
// Install routines.
require_once WPCODE_PLUGIN_PATH . 'includes/class-wpcode-install.php';
// Logging class.
require_once WPCODE_PLUGIN_PATH . 'includes/class-wpcode-file-logger.php';
// Smart tags class.
require_once WPCODE_PLUGIN_PATH . 'includes/class-wpcode-smart-tags.php';
// Admin bar info class.
require_once WPCODE_PLUGIN_PATH . 'includes/class-wpcode-admin-bar-info.php';
// Preview frame handler for live CSS preview.
require_once WPCODE_PLUGIN_PATH . 'includes/admin/class-wpcode-preview-frame.php';
// Abilities API Integration (WordPress 6.9+).
require_once WPCODE_PLUGIN_PATH . 'includes/class-wpcode-abilities-api.php';
if ( is_admin() || ( defined( 'DOING_CRON' ) && DOING_CRON ) ) {
require_once WPCODE_PLUGIN_PATH . 'includes/icons.php'; // This is not needed in the frontend atm.
// Code Editor class.
require_once WPCODE_PLUGIN_PATH . 'includes/admin/class-wpcode-code-editor.php';
require_once WPCODE_PLUGIN_PATH . 'includes/admin/class-wpcode-admin-page-loader.php';
require_once WPCODE_PLUGIN_PATH . 'includes/admin/admin-scripts.php';
require_once WPCODE_PLUGIN_PATH . 'includes/admin/admin-ajax-handlers.php';
// Always used just in the backend.
require_once WPCODE_PLUGIN_PATH . 'includes/class-wpcode-generator.php';
// Snippet Library.
require_once WPCODE_PLUGIN_PATH . 'includes/class-wpcode-library.php';
// Authentication for the library site.
require_once WPCODE_PLUGIN_PATH . 'includes/class-wpcode-library-auth.php';
// Packs feature.
require_once WPCODE_PLUGIN_PATH . 'includes/class-wpcode-packs.php';
require_once WPCODE_PLUGIN_PATH . 'includes/admin/class-wpcode-packs-view.php';
// Importers.
require_once WPCODE_PLUGIN_PATH . 'includes/admin/class-wpcode-importers.php';
// File cache.
require_once WPCODE_PLUGIN_PATH . 'includes/class-wpcode-file-cache.php';
// The docs.
require_once WPCODE_PLUGIN_PATH . 'includes/admin/class-wpcode-docs.php';
// Notifications class.
require_once WPCODE_PLUGIN_PATH . 'includes/admin/class-wpcode-notifications.php';
// Metabox class.
require_once WPCODE_PLUGIN_PATH . 'includes/admin/class-wpcode-metabox-snippets.php';
// Metabox class.
require_once WPCODE_PLUGIN_PATH . 'includes/admin/class-wpcode-admin-notice.php';
// Ask for some love.
require_once WPCODE_PLUGIN_PATH . 'includes/admin/class-wpcode-review.php';
// Suggest free plugins.
require_once WPCODE_PLUGIN_PATH . 'includes/admin/class-wpcode-suggested-plugins.php';
// Highlight features.
require_once WPCODE_PLUGIN_PATH . 'includes/admin/class-wpcode-features-notices.php';
}
// Load lite-specific files.
require_once WPCODE_PLUGIN_PATH . 'includes/lite/loader.php';
}
/**
* Load the Generator on demand.
*
* @return WPCode_Generator
*/
public function generator() {
if ( ! isset( $this->generator ) ) {
$this->generator = new WPCode_Generator();
}
return $this->generator;
}
/**
* Load components in the main plugin instance.
*
* @return void
*/
public function load_components() {
$this->auto_insert = new WPCode_Auto_Insert();
$this->execute = new WPCode_Snippet_Execute();
$this->error = new WPCode_Error();
$this->conditional_logic = new WPCode_Conditional_Logic();
$this->cache = new WPCode_Snippet_Cache();
$this->settings = new WPCode_Settings();
$this->logger = new WPCode_File_Logger();
if ( is_admin() || ( defined( 'DOING_CRON' ) && DOING_CRON ) ) {
$this->file_cache = new WPCode_File_Cache();
$this->library = new WPCode_Library();
$this->library_auth = new WPCode_Library_Auth();
$this->importers = new WPCode_Importers();
$this->notifications = new WPCode_Notifications();
$this->admin_page_loader = new WPCode_Admin_Page_Loader_Lite();
$this->notice = new WPCode_Notice();
$this->smart_tags = new WPCode_Smart_Tags_Lite();
// Metabox class.
new WPCode_Metabox_Snippets_Lite();
// Usage tracking class.
new WPCode_Usage_Tracking_Lite();
// Suggested plugins.
new WPCode_Suggested_Plugins();
}
new WPCode_Admin_Bar_Info_Lite();
do_action( 'wpcode_loaded' );
// Load the pluggable functions late to allow plugins to hook in.
require_once WPCODE_PLUGIN_PATH . 'includes/pluggable.php';
}
}
require_once dirname( __FILE__ ) . '/includes/ihaf.php';
WPCode();
@@ -0,0 +1,854 @@
<?php
/**
* Ajax handlers for the admin.
*
* @package WPCode
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
add_action( 'wp_ajax_wpcode_update_snippet_status', 'wpcode_update_snippet_status' );
add_action( 'wp_ajax_wpcode_filter_snippets_by_type', 'wpcode_filter_snippets_by_type' );
add_action( 'wp_ajax_wpcode_search_terms', 'wpcode_search_terms' );
add_action( 'wp_ajax_wpcode_generate_snippet', 'wpcode_generate_snippet' );
add_action( 'wp_ajax_wpcode_save_generated_snippet', 'wpcode_save_generated_snippet' );
add_action( 'wp_ajax_wpcode_verify_ssl', 'wpcode_verify_ssl' );
add_filter( 'heartbeat_received', 'wpcode_heartbeat_data', 10, 3 );
add_action( 'wp_ajax_wpcode_save_editor_height', 'wpcode_save_editor_height' );
add_action( 'wp_ajax_wpcode_get_shortcode_locations', 'wpcode_get_shortcode_locations' );
add_action( 'wp_ajax_wpcode_sync_snippet', 'wpcode_sync_snippet' );
add_action( 'wp_ajax_wpcode_save_preview_css', 'wpcode_save_preview_css' );
add_action( 'wp_ajax_wpcode_clear_preview_css', 'wpcode_clear_preview_css' );
add_action( 'wp_ajax_wpcode_set_preview_css', 'wpcode_set_preview_css' );
add_action( 'wp_ajax_wpcode_install_pack', 'wpcode_ajax_install_pack' );
add_action( 'wp_ajax_wpcode_toggle_pack_option', 'wpcode_ajax_toggle_pack_option' );
add_action( 'wp_ajax_wpcode_remove_pack', 'wpcode_ajax_remove_pack' );
add_action( 'wp_ajax_wpcode_add_pack_option', 'wpcode_ajax_add_pack_option' );
/**
* Handles toggling a snippet status from the admin.
*
* @return void
*/
function wpcode_update_snippet_status() {
check_ajax_referer( 'wpcode_admin' );
if ( empty( $_POST['snippet_id'] ) ) {
return;
}
$snippet_id = absint( $_POST['snippet_id'] );
$active = isset( $_POST['active'] ) && 'true' === $_POST['active'];
$snippet = wpcode_get_snippet( $snippet_id );
if ( ! current_user_can( 'wpcode_activate_snippets', $snippet ) ) { //phpcs:ignore
wpcode()->error->add_error(
array(
'message' => __( 'You are not allowed to change snippet status, please contact your webmaster.', 'insert-headers-and-footers' ),
'type' => 'permissions',
)
);
$active = false;
} elseif ( $active ) {
$snippet->activate();
} else {
$snippet->deactivate();
}
if ( ! isset( $snippet->active ) || $active !== $snippet->active ) {
$error_message = sprintf(
// Translators: %2$s is the action that they were trying to perform, either activated or deactivated. %1$s is the error message why the action failed.
__( 'Snippet not %2$s, the following error was encountered: %1$s', 'insert-headers-and-footers' ),
'<code>' . wpcode()->error->get_last_error_message() . '</code>',
$active ? _x( 'activated', 'Snippet status change', 'insert-headers-and-footers' ) : _x( 'deactivated', 'Snippet status change', 'insert-headers-and-footers' )
);
// We failed to activate it, so it's an error.
wp_send_json_error(
array(
'message' => $error_message,
)
);
}
exit;
}
/**
* Filter snippets by type.
*
* @return void
*/
function wpcode_filter_snippets_by_type() {
check_ajax_referer( 'wpcode_admin' );
// If the current user can't edit snippets they should not be trying this.
if ( ! current_user_can( 'wpcode_edit_snippets' ) ) { //phpcs:ignore
wp_send_json_error();
}
if ( ! isset( $_POST['snippet_type'] ) ) {
wp_send_json_error();
}
require_once WPCODE_PLUGIN_PATH . 'includes/admin/pages/class-wpcode-code-snippets-table.php';
$snippet_type = isset( $_POST['snippet_type'] ) ? sanitize_text_field( wp_unslash( $_POST['snippet_type'] ) ) : '';
$location = isset( $_POST['location'] ) ? sanitize_text_field( wp_unslash( $_POST['location'] ) ) : '';
$search_term = isset( $_POST['s'] ) ? sanitize_text_field( wp_unslash( $_POST['s'] ) ) : '';
$screen_id = 'toplevel_page_wpcode';
$current_screen = convert_to_screen( $screen_id );
set_current_screen( $screen_id );
$snippets_table = new WPCode_Code_Snippets_Table();
// Used screen object to set up table.
$snippets_table->screen = $current_screen;
$_GET['type'] = $snippet_type;
$_GET['location'] = $location;
$_GET['s'] = $search_term;
$snippets_table->prepare_items();
$count = $snippets_table->get_total_items();
// Output table HTML.
ob_start();
?>
<input type="hidden" name="page" value="wpcode"/>
<?php
$snippets_table->search_box( __( 'Search Snippets', 'insert-headers-and-footers' ), 'wpcode_snippet_search' );
$snippets_table->views();
$snippets_table->display();
$table_html = ob_get_clean();
// Send success response.
wp_send_json_success(
array(
'html' => $table_html,
'count' => $count,
)
);
}
/**
* Ajax handler to search for terms through all the public taxonomies.
*
* @return void
*/
function wpcode_search_terms() {
check_ajax_referer( 'wpcode_admin' );
if ( ! current_user_can( 'wpcode_edit_snippets' ) ) { //phpcs:ignore
wp_send_json_error();
}
$term = isset( $_GET['term'] ) ? sanitize_text_field( wp_unslash( $_GET['term'] ) ) : '';
$public_taxonomies = get_taxonomies(
array(
'public' => true,
)
);
$terms = get_terms(
array(
'search' => $term,
'taxonomy' => $public_taxonomies,
'hide_empty' => false,
)
);
$results = array();
foreach ( $terms as $term ) {
$results[] = array(
'id' => $term->term_id,
'text' => $term->name,
);
}
wp_send_json(
array(
'results' => $results,
)
);
}
/**
* Ajax handler for the generator.
*
* @return void
*/
function wpcode_generate_snippet() {
check_ajax_referer( 'wpcode_generate', 'nonce' );
if ( ! current_user_can( 'wpcode_edit_snippets' ) ) { //phpcs:ignore
wp_send_json_error();
}
$generator_type = isset( $_POST['type'] ) ? sanitize_text_field( wp_unslash( $_POST['type'] ) ) : '';
$generator = wpcode()->generator()->get_type( $generator_type );
if ( ! $generator ) {
wp_send_json_error();
}
$snippet_code = $generator->process_form_data( $_POST );
wp_send_json( $snippet_code );
}
/**
* Take the values from a generated snippet and save as a new snippet.
*
* @return void
*/
function wpcode_save_generated_snippet() {
check_ajax_referer( 'wpcode_generate', 'nonce' );
// If the current user can't edit snippets they should not be trying this.
if ( ! current_user_can( 'wpcode_edit_snippets' ) ) { //phpcs:ignore
wp_send_json_error();
}
$generator_type = isset( $_POST['type'] ) ? sanitize_text_field( wp_unslash( $_POST['type'] ) ) : '';
$generator = wpcode()->generator()->get_type( $generator_type );
// If a snippet id is passed, let's attempt to update it.
$snippet_id = isset( $_POST['snippet_id'] ) ? absint( $_POST['snippet_id'] ) : '';
if ( ! $generator ) {
wp_send_json_error();
}
$snippet_code = $generator->process_form_data( $_POST );
$snippet_data = array(
// Translators: this an auto-generated title for when a snippet is saved from the generator.
'title' => sprintf( __( 'Generated Snippet %s', 'insert-headers-and-footers' ), $generator->get_title() ),
'code' => $snippet_code,
'code_type' => $generator->get_code_type(),
'tags' => $generator->get_tags(),
'location' => $generator->get_location(),
'generator' => $generator->get_name(),
'generator_data' => $generator->get_generator_data(),
'auto_insert' => $generator->get_auto_insert(),
);
// If a snippet id is passed, let's attempt to update the snippet.
if ( ! empty( $snippet_id ) ) {
$snippet = new WPCode_Snippet( $snippet_id );
// Let's make sure this is an id for a snippet.
if ( null !== $snippet->get_post_data() ) {
$snippet_data['id'] = $snippet_id;
$snippet_data['active'] = false;
// Don't change the title of an existing snippet.
unset( $snippet_data['title'] );
}
}
$new_snippet = new WPCode_Snippet( $snippet_data );
$new_snippet_id = $new_snippet->save();
wp_send_json_success(
array(
'url' => add_query_arg(
array(
'page' => 'wpcode-snippet-manager',
'snippet_id' => $new_snippet_id,
),
admin_url( 'admin.php' )
),
)
);
}
/**
* Ajax handler to verify that the current web host can successfully
* make outbound SSL connections.
*
* @return void
*/
function wpcode_verify_ssl() {
if ( ! current_user_can( 'wpcode_edit_snippets' ) ) { //phpcs:ignore
wp_send_json_error();
}
$response = wp_remote_post( 'https://wpcode.com' );
if ( 200 === wp_remote_retrieve_response_code( $response ) ) {
wp_send_json_success(
array(
'msg' => esc_html__( 'Success! Your server can make SSL connections.', 'insert-headers-and-footers' ),
)
);
}
wp_send_json_error(
array(
'msg' => esc_html__( 'There was an error and the connection failed. Please contact your web host with the technical details below.', 'insert-headers-and-footers' ),
'debug' => '<pre>' . print_r( map_deep( $response, 'wp_strip_all_tags' ), true ) . '</pre>', // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_print_r
)
);
}
/**
* Use heartbeat to update lock status when editing a snippet.
*
* @param array $response The Heartbeat response.
* @param array $data The $_POST data sent with the Heartbeat.
* @param string $screen_id The screen ID.
*
* @return array
*/
function wpcode_heartbeat_data( $response, $data, $screen_id ) {
if ( 'code-snippets_page_wpcode-snippet-manager' === $screen_id && isset( $data['wpcode_lock'] ) ) {
// Update the post lock while they are still editing.
$post_id = absint( $data['wpcode_lock'] );
if ( $post_id && current_user_can( 'edit_post', $post_id ) ) {
wp_set_post_lock( $post_id );
}
}
return $response;
}
/**
* AJAX handler to save the editor height.
*
* @return void
*/
function wpcode_save_editor_height() {
check_ajax_referer( 'wpcode_admin' );
// If the current user can't edit snippets they should not be trying this.
if ( ! current_user_can( 'wpcode_edit_snippets' ) ) { //phpcs:ignore
wp_send_json_error();
}
$height = isset( $_POST['height'] ) ? absint( $_POST['height'] ) : false;
if ( false !== $height ) {
wpcode()->settings->update_option( 'editor_height', $height );
wp_send_json_success();
}
wp_send_json_error();
}
/**
* Get the list of locations where a shortcode is used.
*
* @return void
*/
function wpcode_get_shortcode_locations() {
check_ajax_referer( 'wpcode_admin', '_wpnonce' );
if ( ! current_user_can( 'wpcode_edit_snippets' ) ) { //phpcs:ignore
wp_send_json_error();
}
if ( empty( $_POST['snippet_id'] ) ) {
wp_send_json_error( 'No snippet ID provided' );
}
$snippet_id = absint( $_POST['snippet_id'] );
$snippet = wpcode_get_snippet( $snippet_id );
$page = isset( $_POST['page'] ) ? absint( $_POST['page'] ) : 1;
$per_page = 100;
$post_types = array_merge(
get_post_types( array( 'public' => true ) ),
array(
'wp_template',
'wp_template_part',
'wpcode',
)
);
// Add post types to params.
$params = $post_types;
global $wpdb;
$search_terms = array();
$search_terms[] = '[wpcode';
if ( $snippet->get_custom_shortcode() ) {
$search_terms[] = '[' . $snippet->get_custom_shortcode();
}
$like_clauses = array();
foreach ( $search_terms as $term ) {
$like_clauses[] = 'post_content LIKE %s';
$params[] = '%' . $wpdb->esc_like( $term ) . '%';
}
$where_like = implode( ' OR ', $like_clauses );
$offset = ( $page - 1 ) * $per_page;
$post_type_placeholders = implode( ', ', array_fill( 0, count( $post_types ), '%s' ) );
$params[] = $per_page;
$params[] = $offset;
// Build query structure with sprintf, escaping prepare() placeholders with %%.
$query = sprintf(
"SELECT ID FROM {$wpdb->posts} WHERE post_type IN (%s) AND post_status != 'trash' AND (%s) LIMIT %%d OFFSET %%d",
$post_type_placeholders,
$where_like
);
$candidate_ids = $wpdb->get_col( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.DirectQuery
$wpdb->prepare( $query, $params ) // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
);
$candidate_ids = array_unique( $candidate_ids );
$matching_posts = array();
if ( ! empty( $candidate_ids ) ) {
$candidate_posts = get_posts(
array(
'post_type' => array_values( $post_types ),
'post_status' => 'any',
'posts_per_page' => - 1,
'include' => $candidate_ids,
)
);
foreach ( $candidate_posts as $post ) {
$content = $post->post_content;
if ( has_shortcode( $content, 'wpcode' ) && preg_match( '/\[wpcode[^\]]*id\s*=\s*["\']\s*' . preg_quote( $snippet_id, '/' ) . '\s*["\'][^\]]*\]/', $content ) ) {
$matching_posts[] = $post;
continue;
}
if ( $snippet->get_custom_shortcode() && has_shortcode( $content, $snippet->get_custom_shortcode() ) && preg_match( '/\[' . preg_quote( $snippet->get_custom_shortcode(), '/' ) . '[^\]]*\]/', $content ) ) {
$matching_posts[] = $post;
}
}
}
if ( empty( $matching_posts ) ) {
if ( 1 === $page ) {
$html = '<ul><li>' . esc_html__( 'This shortcode is not used in any content yet.', 'insert-headers-and-footers' ) . '</li></ul>';
} else {
$html = '';
}
} else {
$html = '<ul>';
foreach ( $matching_posts as $post ) {
if ( 'wpcode' === $post->post_type ) {
$edit_link = esc_url( add_query_arg( 'snippet_id', $post->ID, admin_url( 'admin.php?page=wpcode-snippet-manager' ) ) );
$post_type_label = esc_html__( 'WPCode Snippet', 'insert-headers-and-footers' );
} else {
$edit_link = get_edit_post_link( $post->ID );
$post_type_obj = get_post_type_object( $post->post_type );
$post_type_label = $post_type_obj ? $post_type_obj->labels->singular_name : $post->post_type;
}
$html .= sprintf(
'<li><a href="%1$s" target="_blank" rel="noopener noreferrer">%2$s</a> <span class="wpcode-post-type">(%3$s)</span></li>',
esc_url( $edit_link ),
// Translators: %d is the post id.
esc_html( empty( $post->post_title ) ? sprintf( esc_html__( 'Untitled (#%d)', 'insert-headers-and-footers' ), $post->ID ) : $post->post_title ),
esc_html( $post_type_label )
);
}
$html .= '</ul>';
}
$has_more = count( $candidate_ids ) >= $per_page;
wp_send_json_success(
array(
'html' => $html,
'has_more' => $has_more,
'page' => $page,
)
);
}
/**
* AJAX handler for syncing a snippet from the library.
*
* @return void
*/
function wpcode_sync_snippet() {
// Check nonce.
if ( ! check_ajax_referer( 'wpcode_admin', 'nonce', false ) ) {
wp_send_json_error( array( 'message' => __( 'Security check failed.', 'insert-headers-and-footers' ) ) );
}
// Check permissions.
if ( ! current_user_can( 'wpcode_edit_snippets' ) ) { //phpcs:ignore
wp_send_json_error( array( 'message' => __( 'You do not have permission to edit snippets.', 'insert-headers-and-footers' ) ) );
}
$snippet_id = isset( $_POST['snippet_id'] ) ? absint( $_POST['snippet_id'] ) : 0;
$library_id = isset( $_POST['library_id'] ) ? absint( $_POST['library_id'] ) : 0;
if ( ! $snippet_id || ! $library_id ) {
wp_send_json_error( array( 'message' => __( 'Invalid snippet ID.', 'insert-headers-and-footers' ) ) );
}
$result = wpcode()->library->update_snippet_from_library( $snippet_id, $library_id );
if ( ! $result ) {
wp_send_json_error( array( 'message' => __( 'Failed to update snippet from library.', 'insert-headers-and-footers' ) ) );
}
// No need to update the option as we're checking for updates on the fly.
wp_send_json_success(
array(
'message' => __( 'Snippet successfully updated.', 'insert-headers-and-footers' ),
'version' => isset( $result['version'] ) ? $result['version'] : '',
)
);
}
/**
* AJAX handler to save preview CSS to snippet.
* Supports both CSS and SCSS snippets.
*
* @return void
*/
function wpcode_save_preview_css() {
// Check nonce.
check_ajax_referer( 'wpcode_admin', 'nonce' );
$snippet_id = isset( $_POST['snippet_id'] ) ? absint( $_POST['snippet_id'] ) : 0;
// Check permissions against the specific snippet's code type.
if ( ! $snippet_id || ! current_user_can( 'edit_post', $snippet_id ) ) {
wp_send_json_error( array( 'message' => __( 'You do not have permission to edit this snippet.', 'insert-headers-and-footers' ) ) );
}
$css = isset( $_POST['css'] ) ? wp_unslash( $_POST['css'] ) : ''; // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
$code_type = isset( $_POST['code_type'] ) ? sanitize_text_field( wp_unslash( $_POST['code_type'] ) ) : '';
$source_code = isset( $_POST['source_code'] ) ? wp_unslash( $_POST['source_code'] ) : ''; // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
// Strip script/event-handler HTML from the stored code for authors without unfiltered_html.
if ( ! current_user_can( 'unfiltered_html' ) ) {
$css = wp_kses_post( $css );
$source_code = wp_kses_post( $source_code );
}
// Get the snippet.
$snippet = wpcode_get_snippet( $snippet_id );
if ( ! $snippet || ! $snippet->get_id() ) {
wp_send_json_error( array( 'message' => __( 'Snippet not found.', 'insert-headers-and-footers' ) ) );
}
// Preserve existing "Compress Output" option explicitly without mutating the property to a false value.
$compress_enabled = get_post_meta( $snippet_id, '_wpcode_compress_output', true );
// For SCSS snippets, save the source code and compiled CSS.
if ( 'scss' === $code_type || 'scss' === $snippet->get_code_type() ) {
// Use source code if provided, otherwise use the compiled CSS as source (shouldn't happen).
$snippet->code = ! empty( $source_code ) ? $source_code : $css;
// Store the compiled CSS.
$snippet->compiled_code = $css;
} else {
// For CSS snippets, just save the CSS directly.
$snippet->code = $css;
}
// Re-apply compress_output flag only if it was previously enabled.
if ( $compress_enabled ) {
$snippet->compress_output = true;
}
$result = $snippet->save();
if ( ! $result ) {
wp_send_json_error( array( 'message' => __( 'Failed to save snippet.', 'insert-headers-and-footers' ) ) );
}
// Clear the preview transients.
$user_id = get_current_user_id();
$transient_key = "wpcode_preview_css_{$user_id}_{$snippet_id}";
delete_transient( $transient_key );
// Also clear SCSS source transient if it exists.
$source_transient_key = "wpcode_preview_scss_source_{$user_id}_{$snippet_id}";
delete_transient( $source_transient_key );
// Return success with redirect URL.
wp_send_json_success(
array(
'message' => __( 'Snippet saved successfully.', 'insert-headers-and-footers' ),
'url' => add_query_arg(
array(
'page' => 'wpcode-snippet-manager',
'snippet_id' => $snippet_id,
'message' => 1,
),
admin_url( 'admin.php' )
),
)
);
}
/**
* AJAX handler to clear preview CSS transient.
* Supports both CSS and SCSS snippets.
*
* @return void
*/
function wpcode_clear_preview_css() {
// Check nonce.
check_ajax_referer( 'wpcode_admin', 'nonce' );
// Check permissions.
if ( ! current_user_can( 'wpcode_edit_snippets' ) ) { //phpcs:ignore
wp_send_json_error( array( 'message' => __( 'You do not have permission.', 'insert-headers-and-footers' ) ) );
}
$snippet_id = isset( $_POST['snippet_id'] ) ? absint( $_POST['snippet_id'] ) : 0;
if ( ! $snippet_id ) {
wp_send_json_error( array( 'message' => __( 'Invalid snippet ID.', 'insert-headers-and-footers' ) ) );
}
// Clear the preview transients.
$user_id = get_current_user_id();
$transient_key = "wpcode_preview_css_{$user_id}_{$snippet_id}";
delete_transient( $transient_key );
// Also clear SCSS source transient if it exists.
$source_transient_key = "wpcode_preview_scss_source_{$user_id}_{$snippet_id}";
delete_transient( $source_transient_key );
wp_send_json_success(
array(
'message' => __( 'Preview cleared.', 'insert-headers-and-footers' ),
)
);
}
/**
* AJAX handler to set preview CSS transient only (no DB save).
* Supports both CSS and SCSS snippets.
*
* @return void
*/
function wpcode_set_preview_css() {
// Check nonce.
check_ajax_referer( 'wpcode_admin', 'nonce' );
// Check permissions.
if ( ! current_user_can( 'wpcode_edit_snippets' ) ) { //phpcs:ignore
wp_send_json_error( array( 'message' => __( 'You do not have permission to edit snippets.', 'insert-headers-and-footers' ) ) );
}
$snippet_id = isset( $_POST['snippet_id'] ) ? absint( $_POST['snippet_id'] ) : 0;
$css = isset( $_POST['css'] ) ? wp_unslash( $_POST['css'] ) : ''; // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
$code_type = isset( $_POST['code_type'] ) ? sanitize_text_field( wp_unslash( $_POST['code_type'] ) ) : 'css';
$source_code = isset( $_POST['source_code'] ) ? wp_unslash( $_POST['source_code'] ) : ''; // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
if ( ! $snippet_id ) {
wp_send_json_error( array( 'message' => __( 'Invalid snippet ID.', 'insert-headers-and-footers' ) ) );
}
$user_id = get_current_user_id();
// For SCSS, store both the compiled CSS (for preview) and source code (for saving).
if ( 'scss' === $code_type ) {
// Store compiled CSS for preview frame.
$compiled_transient_key = "wpcode_preview_css_{$user_id}_{$snippet_id}";
set_transient( $compiled_transient_key, $css, HOUR_IN_SECONDS );
// Store source SCSS for saving later.
$source_transient_key = "wpcode_preview_scss_source_{$user_id}_{$snippet_id}";
set_transient( $source_transient_key, $source_code, HOUR_IN_SECONDS );
} else {
// Store the CSS in the same transient used by the preview frame.
$transient_key = "wpcode_preview_css_{$user_id}_{$snippet_id}";
set_transient( $transient_key, $css, HOUR_IN_SECONDS );
}
wp_send_json_success( array( 'message' => __( 'Preview CSS stored.', 'insert-headers-and-footers' ) ) );
}
/**
* AJAX: install a pack.
*
* @return void
*/
function wpcode_ajax_install_pack() {
check_ajax_referer( 'wpcode_packs', 'nonce' );
if ( ! current_user_can( 'wpcode_edit_snippets' ) ) {
wp_send_json_error( array( 'message' => __( 'Insufficient permissions.', 'insert-headers-and-footers' ) ), 403 );
}
if ( ! wpcode()->library_auth->has_auth() ) {
wp_send_json_error(
array(
'message' => __( 'Please connect to the WPCode Library to install packs.', 'insert-headers-and-footers' ),
'code' => 'not_connected',
),
403
);
}
$slug = isset( $_POST['slug'] ) ? sanitize_key( wp_unslash( $_POST['slug'] ) ) : '';
if ( '' === $slug ) {
wp_send_json_error( array( 'message' => __( 'Pack slug is required.', 'insert-headers-and-footers' ) ), 400 );
}
$result = WPCode_Packs::get_instance()->install_pack( $slug );
if ( ! $result['success'] ) {
wp_send_json_error(
array(
'message' => __( 'Pack install failed.', 'insert-headers-and-footers' ),
),
500
);
}
wp_send_json_success(
array(
'result' => $result,
'redirect_url' => add_query_arg(
array(
'page' => 'wpcode-snippet-manager',
'tab' => 'packs',
'pack' => $slug,
),
admin_url( 'admin.php' )
),
)
);
}
/**
* AJAX: toggle a pack option.
*
* @return void
*/
function wpcode_ajax_toggle_pack_option() {
check_ajax_referer( 'wpcode_packs', 'nonce' );
if ( ! current_user_can( 'wpcode_activate_snippets' ) ) {
wp_send_json_error( array( 'message' => __( 'Insufficient permissions.', 'insert-headers-and-footers' ) ), 403 );
}
$slug = isset( $_POST['slug'] ) ? sanitize_key( wp_unslash( $_POST['slug'] ) ) : '';
$library_id = isset( $_POST['library_id'] ) ? (int) $_POST['library_id'] : 0;
$active = isset( $_POST['active'] ) && '1' === $_POST['active'];
if ( '' === $slug || $library_id <= 0 ) {
wp_send_json_error( array( 'message' => __( 'Invalid request.', 'insert-headers-and-footers' ) ), 400 );
}
$state = WPCode_Packs::get_instance()->toggle_option( $slug, $library_id, $active );
if ( null === $state ) {
wp_send_json_error( array( 'message' => __( 'Option not found.', 'insert-headers-and-footers' ) ), 404 );
}
// Return the real resulting state — activation can be refused if the snippet
// errors, in which case it stays inactive.
wp_send_json_success(
array(
'active' => $state,
'activation_refused' => $active && ! $state,
)
);
}
/**
* AJAX: remove a pack.
*
* @return void
*/
function wpcode_ajax_remove_pack() {
check_ajax_referer( 'wpcode_packs', 'nonce' );
if ( ! current_user_can( 'wpcode_edit_snippets' ) ) {
wp_send_json_error( array( 'message' => __( 'Insufficient permissions.', 'insert-headers-and-footers' ) ), 403 );
}
$slug = isset( $_POST['slug'] ) ? sanitize_key( wp_unslash( $_POST['slug'] ) ) : '';
if ( '' === $slug ) {
wp_send_json_error( array( 'message' => __( 'Pack slug is required.', 'insert-headers-and-footers' ) ), 400 );
}
$deleted = WPCode_Packs::get_instance()->remove_pack( $slug );
wp_send_json_success(
array(
'deleted_count' => $deleted,
'redirect_url' => add_query_arg(
array(
'page' => 'wpcode-snippet-manager',
'tab' => 'packs',
),
admin_url( 'admin.php' )
),
)
);
}
/**
* AJAX: add a single pack option.
*
* @return void
*/
function wpcode_ajax_add_pack_option() {
check_ajax_referer( 'wpcode_packs', 'nonce' );
if ( ! current_user_can( 'wpcode_edit_snippets' ) ) {
wp_send_json_error( array( 'message' => __( 'Insufficient permissions.', 'insert-headers-and-footers' ) ), 403 );
}
if ( ! wpcode()->library_auth->has_auth() ) {
wp_send_json_error(
array(
'message' => __( 'Please connect to the WPCode Library to add pack snippets.', 'insert-headers-and-footers' ),
'code' => 'not_connected',
),
403
);
}
$slug = isset( $_POST['slug'] ) ? sanitize_key( wp_unslash( $_POST['slug'] ) ) : '';
$library_id = isset( $_POST['library_id'] ) ? (int) $_POST['library_id'] : 0;
if ( '' === $slug || $library_id <= 0 ) {
wp_send_json_error( array( 'message' => __( 'Invalid request.', 'insert-headers-and-footers' ) ), 400 );
}
$packs = WPCode_Packs::get_instance();
$created = $packs->add_option( $slug, $library_id );
if ( ! $created ) {
// The most common reason for failure is the snippet already being present
// (e.g. another pack installed it, or a concurrent add). Say so clearly
// and let the UI refresh to the installed state instead of erroring.
if ( $packs->find_local_snippet_by_library_id( $library_id ) ) {
wp_send_json_error(
array(
'message' => __( 'This snippet is already installed.', 'insert-headers-and-footers' ),
'code' => 'already_installed',
),
409
);
}
wp_send_json_error( array( 'message' => __( 'Could not add option.', 'insert-headers-and-footers' ) ), 500 );
}
wp_send_json_success( array( 'snippet_id' => $created->get_id() ) );
}
@@ -0,0 +1,157 @@
<?php
/**
* Load scripts for the admin area.
*
* @package WPCode
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
add_action( 'admin_enqueue_scripts', 'wpcode_admin_scripts' );
add_filter( 'admin_body_class', 'wpcode_admin_body_class' );
/**
* Load admin scripts here.
*
* @return void
*/
function wpcode_admin_scripts() {
$current_screen = get_current_screen();
if ( ! isset( $current_screen->id ) || false === strpos( $current_screen->id, 'wpcode' ) ) {
return;
}
$admin_asset_file = WPCODE_PLUGIN_PATH . 'build/admin.asset.php';
if ( ! file_exists( $admin_asset_file ) ) {
return;
}
$asset = require $admin_asset_file;
wp_enqueue_style( 'wpcode-admin-css', WPCODE_PLUGIN_URL . 'build/admin.css', null, $asset['version'] );
wp_enqueue_script( 'wpcode-admin-js', WPCODE_PLUGIN_URL . 'build/admin.js', $asset['dependencies'], $asset['version'], true );
wp_localize_script(
'wpcode-admin-js',
'wpcode',
apply_filters(
'wpcode_admin_js_data',
array(
'nonce' => wp_create_nonce( 'wpcode_admin' ),
'code_type_options' => wpcode()->execute->get_code_type_options(),
'please_wait' => __( 'Please wait.', 'insert-headers-and-footers' ),
'ok' => __( 'OK', 'insert-headers-and-footers' ),
'live_preview_save_title' => __( 'Save Snippet First', 'insert-headers-and-footers' ),
'live_preview_save_text' => __( 'Please save your CSS snippet first before using Live Preview.', 'insert-headers-and-footers' ),
'live_preview_block_title' => __( 'Live Preview Unavailable', 'insert-headers-and-footers' ),
'live_preview_block_text' => __( 'Live Preview can only be used for snippets with "Site Wide Header", "Site Wide Footer" and "Site Wide Body" insert locations.', 'insert-headers-and-footers' ),
'purchased' => __( 'Already Purchased?', 'insert-headers-and-footers' ),
'upgrade_link' => wpcode_utm_url( 'https://wpcode.com/docs/how-to-upgrade-your-wpcode-license/', 'upsell-alert', $current_screen->id ),
'bonus' => __( 'Bonus', 'insert-headers-and-footers' ),
'price' => __( '$50 off', 'insert-headers-and-footers' ),
'regular_price' => __( 'regular price, automatically applied at checkout.', 'insert-headers-and-footers' ),
'wpcode_lite_users' => __( 'WPCode Lite users get', 'insert-headers-and-footers' ),
'upgrade_button' => __( 'Upgrade to PRO', 'insert-headers-and-footers' ),
'smart_tags_upgrade_title' => __( 'Smart Tags are a Premium feature', 'insert-headers-and-footers' ),
'smart_tags_upgrade_text' => __( 'Upgrade to PRO today and simplify the way you write advanced snippets using smart tags without having to write any PHP code.', 'insert-headers-and-footers' ),
'testing_mode' => array(
'title' => __( 'Testing Mode is a Premium Feature', 'insert-headers-and-footers' ),
'text' => __( 'Upgrade to PRO today and make changes to your snippets, Header & Footer scripts or Page Scripts without affecting your live site. You choose when and what to publish to your visitors.', 'insert-headers-and-footers' ),
'button_text' => __( 'Upgrade to PRO', 'insert-headers-and-footers' ),
'link' => wpcode_utm_url( 'https://wpcode.com/lite/', 'testing-mode', $current_screen->id ),
'learn_more_text' => __( 'Learn more about Testing Mode', 'insert-headers-and-footers' ),
'learn_more_link' => wpcode_utm_url( 'https://wpcode.com/docs/testing-mode/', 'testing-mode-learn-more', $current_screen->id ),
),
'file_based_loading' => array(
'title' => __( 'File-Based Loading is a Premium Feature', 'insert-headers-and-footers' ),
'text' => __( 'Upgrade to PRO today and load your snippets from files instead of the database. This improves performance and allows for easier version control of your code snippets.', 'insert-headers-and-footers' ),
'button_text' => __( 'Upgrade to PRO', 'insert-headers-and-footers' ),
'link' => wpcode_utm_url( 'https://wpcode.com/lite/', 'settings', 'tab-general', 'file-based-loading' ),
),
'auth_needed_title_sync' => __( 'Connect with WPCode Library to Sync Snippets', 'insert-headers-and-footers' ),
'auth_needed_text_sync' => __( 'Before syncing your snippets, you must connect to WPCode Library, so we can securely access and update them.', 'insert-headers-and-footers' ),
'auth_needed_confirm' => __( 'Connect with WPCode Library', 'insert-headers-and-footers' ),
'confirm_sync_title' => __( 'Confirm Update', 'insert-headers-and-footers' ),
'confirm_sync_text' => __( 'Updating this snippet will overwrite your current local changes with the latest version from the library.', 'insert-headers-and-footers' ),
'confirm_sync_button' => __( 'Yes, Update Now', 'insert-headers-and-footers' ),
'cancel' => __( 'Cancel', 'insert-headers-and-footers' ),
'check_for_updates_title' => __( 'The Private Snippet Library is a Premium Feature', 'insert-headers-and-footers' ),
'check_for_updates_text' => __( 'Upgrade today and get access to a private snippet library that you can use to manage snippets on multiple sites.', 'insert-headers-and-footers' ),
'learn_more_text' => __( 'Learn more about WPCode Pro', 'insert-headers-and-footers' ),
'learn_more_link' => wpcode_utm_url( 'https://wpcode.com/docs/wpcode-pro-features/', 'check-updates-learn-more', $current_screen->id ),
'upgrade_url' => wpcode_utm_url( 'https://wpcode.com/lite/', 'check-updates', $current_screen->id ),
'multisite' => false,
'connect_url' => wpcode()->library_auth->auth_url(),
'your_version' => __( 'Your version:', 'insert-headers-and-footers' ),
'library_version' => __( 'Library version:', 'insert-headers-and-footers' ),
'old_version' => __( 'Old version:', 'insert-headers-and-footers' ),
'new_version' => __( 'New version:', 'insert-headers-and-footers' ),
'ok_button' => __( 'OK', 'insert-headers-and-footers' ),
)
)
);
// Dequeue debug bar console styles on WPCode pages.
wp_dequeue_style( 'debug-bar-codemirror' );
wp_dequeue_style( 'debug-bar-console' );
}
/**
* Scripts needed outside the WPCode admin area (e.g. metabox).
*
* @param string $version The version of the scripts to load. Default is 'lite'.
*
* @return void
*/
function wpcode_admin_scripts_global( $version = 'lite' ) {
// Load "globally" but still only on certain screens.
$current_screen = get_current_screen();
$dont_load = ! isset( $current_screen->base ) || 'post' !== $current_screen->base;
// Allow other plugins to modify the screens where the global scripts are loaded.
if ( apply_filters( 'wpcode_load_global_scripts', $dont_load ) ) {
return;
}
$admin_asset_file = WPCODE_PLUGIN_PATH . "build/admin-global-{$version}.asset.php";
if ( ! file_exists( $admin_asset_file ) ) {
return;
}
$asset = require $admin_asset_file;
wp_enqueue_style( 'wpcode-admin-global-css', WPCODE_PLUGIN_URL . "build/admin-global-{$version}.css", null, $asset['version'] );
wp_enqueue_script( 'wpcode-admin-global-js', WPCODE_PLUGIN_URL . "build/admin-global-{$version}.js", $asset['dependencies'], $asset['version'], true );
}
/**
* Add stable body class that doesn't change with the translation.
*
* @param string $classes The body classes.
*
* @return string
*/
function wpcode_admin_body_class( $classes ) {
$page_parent = get_admin_page_parent();
if ( 'wpcode' === $page_parent ) {
$classes .= ' wpcode-admin-page';
if ( ! empty( wpcode()->settings->get_option( 'dark_mode' ) ) ) {
$classes .= ' wpcode-dark-mode';
}
}
return $classes;
}
@@ -0,0 +1,366 @@
<?php
class WPCode_Notice {
/**
* Not dismissible.
*
* Constant attended to use as the value of the $args['dismiss'] argument.
* DISMISS_NONE means that the notice is not dismissible.
*
*/
const DISMISS_NONE = 0;
/**
* Dismissible global.
*
* Constant attended to use as the value of the $args['dismiss'] argument.
* DISMISS_GLOBAL means that the notice will have the dismiss button, and after clicking this button, the notice will be dismissed for all users.
*
*/
const DISMISS_GLOBAL = 1;
/**
* Dismissible per user.
*
* Constant attended to use as the value of the $args['dismiss'] argument.
* DISMISS_USER means that the notice will have the dismiss button, and after clicking this button, the notice will be dismissed only for the current user..
*
*/
const DISMISS_USER = 2;
/**
* Added notices.
*
* @var array
*/
public $notices = array();
/**
* Top notices, displayed separately.
*
* @var array
*/
public $notices_top = array();
/**
* Init.
*
*/
public function __construct() {
$this->hooks();
}
/**
* Hooks.
*
*/
public function hooks() {
add_action( 'admin_notices', array( $this, 'display' ), 999000 );
// Hook for our specific pages where we hide all other admin notices.
add_action( 'wpcode_admin_notices', array( $this, 'display' ), 10 );
add_action( 'wp_ajax_wpcode_notice_dismiss', array( $this, 'dismiss_ajax' ) );
// Display notices above the header.
add_action( 'wpcode_admin_page', array( $this, 'display_top' ), 5 );
}
/**
* Enqueue assets.
*/
public function enqueues() {
wp_enqueue_script(
'wpcode-admin-notices',
WPCODE_PLUGIN_URL . 'build/notices.js',
array( 'jquery' ),
WPCODE_VERSION,
true
);
wp_localize_script(
'wpcode-admin-notices',
'wpcode_admin_notices',
array(
'ajax_url' => admin_url( 'admin-ajax.php' ),
'nonce' => wp_create_nonce( 'wpcode-admin' ),
)
);
}
/**
* Display the notices.
*/
public function display() {
$dismissed_notices = get_user_meta( get_current_user_id(), 'wpcode_admin_notices', true );
$dismissed_notices = is_array( $dismissed_notices ) ? $dismissed_notices : array();
$dismissed_notices = array_merge( $dismissed_notices, (array) get_option( 'wpcode_admin_notices', array() ) );
foreach ( $this->notices as $slug => $notice ) {
if ( isset( $dismissed_notices[ $slug ] ) && ! empty( $dismissed_notices[ $slug ]['dismissed'] ) ) {
unset( $this->notices[ $slug ] );
}
}
$output = implode( '', $this->notices );
echo $output; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
// Enqueue script only when it's needed.
if ( strpos( $output, 'is-dismissible' ) !== false ) {
$this->enqueues();
}
}
/**
* Display the notices at the top of the WPC pages.
*/
public function display_top() {
$dismissed_notices = get_user_meta( get_current_user_id(), 'wpcode_admin_notices', true );
$dismissed_notices = is_array( $dismissed_notices ) ? $dismissed_notices : array();
$dismissed_notices = array_merge( $dismissed_notices, (array) get_option( 'wpcode_admin_notices', array() ) );
foreach ( $this->notices_top as $slug => $notice ) {
if ( isset( $dismissed_notices[ $slug ] ) && ! empty( $dismissed_notices[ $slug ]['dismissed'] ) ) {
unset( $this->notices_top[ $slug ] );
}
}
$output = implode( '', $this->notices_top );
if ( ! empty( $output ) ) {
echo '<div class="wpcode-notice-top-area">';
echo $output; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
echo '</div>';
}
// Enqueue script only when it's needed.
if ( strpos( $output, 'is-dismissible' ) !== false ) {
$this->enqueues();
}
}
/**
* Add notice to the registry.
*
*
* @param string $message Message to display.
* @param string $type Type of the notice. Can be [ '' (default) | 'info' | 'error' | 'success' | 'warning' ].
* @param array $args The array of additional arguments. Please see the $defaults array below.
*/
public static function add( $message, $type = '', $args = [] ) {
static $uniq_id = 0;
$defaults = [
'dismiss' => self::DISMISS_NONE,
// Dismissible level: one of the self::DISMISS_* const. By default notice is not dismissible.
'slug' => '',
// Slug. Should be unique if dismissible is not equal self::DISMISS_NONE.
'autop' => true,
// `false` if not needed to pass message through wpautop().
'class' => '',
// Additional CSS class.
];
$args = wp_parse_args( $args, $defaults );
$dismissible = (int) $args['dismiss'];
$dismissible = $dismissible > self::DISMISS_USER ? self::DISMISS_USER : $dismissible;
$class = $dismissible > self::DISMISS_NONE ? ' is-dismissible' : '';
$global = ( $dismissible === self::DISMISS_GLOBAL ) ? 'global-' : '';
$slug = sanitize_key( $args['slug'] );
++ $uniq_id;
$uniq_id += ( $uniq_id === (int) $slug ) ? 1 : 0;
$id = 'wpcode-notice-' . $global;
$id .= empty( $slug ) ? $uniq_id : $slug;
$type_class = ! empty( $type ) ? 'notice-' . esc_attr( sanitize_key( $type ) ) : '';
$class = empty( $args['class'] ) ? $class : $class . ' ' . esc_attr( sanitize_key( $args['class'] ) );
$message = $args['autop'] ? wpautop( $message ) : $message;
$notice = sprintf(
'<div class="notice wpcode-notice %s%s" id="%s">%s</div>',
esc_attr( $type_class ),
esc_attr( $class ),
esc_attr( $id ),
$message
);
if ( 'top' === $type ) {
if ( empty( $slug ) ) {
wpcode()->notice->notices_top[] = $notice;
} else {
wpcode()->notice->notices_top[ $slug ] = $notice;
}
return; // Don't mix top notices.
}
if ( empty( $slug ) ) {
wpcode()->notice->notices[] = $notice;
} else {
wpcode()->notice->notices[ $slug ] = $notice;
}
}
/**
* Add info notice.
*
*
* @param string $message Message to display.
* @param array $args Array of additional arguments. Details in the self::add() method.
*/
public static function info( $message, $args = [] ) {
self::add( $message, 'info', $args );
}
/**
* Add top notice (displayed before the header on wpcode pages only).
*
*
* @param string $message Message to display.
* @param array $args Array of additional arguments. Details in the self::add() method.
*/
public static function top( $message, $args = [] ) {
self::add( $message, 'top', $args );
}
/**
* Add error notice.
*
*
* @param string $message Message to display.
* @param array $args Array of additional arguments. Details in the self::add() method.
*/
public static function error( $message, $args = [] ) {
self::add( $message, 'error', $args );
}
/**
* Add success notice.
*
*
* @param string $message Message to display.
* @param array $args Array of additional arguments. Details in the self::add() method.
*/
public static function success( $message, $args = [] ) {
self::add( $message, 'success', $args );
}
/**
* Add warning notice.
*
*
* @param string $message Message to display.
* @param array $args Array of additional arguments. Details in the self::add() method.
*/
public static function warning( $message, $args = [] ) {
self::add( $message, 'warning', $args );
}
/**
* AJAX routine that updates dismissed notices meta data.
*
*/
public function dismiss_ajax() {
// Run a security check.
check_ajax_referer( 'wpcode-admin' );
// Sanitize POST data.
$post = array_map( 'sanitize_key', wp_unslash( $_POST ) );
// Update notices meta data.
if ( strpos( $post['id'], 'global-' ) !== false ) {
// Check for permissions.
if ( ! current_user_can( 'wpcode_edit_snippets' ) ) {
wp_send_json_error();
}
$notices = $this->dismiss_global( $post['id'] );
$level = self::DISMISS_GLOBAL;
} else {
$notices = $this->dismiss_user( $post['id'] );
$level = self::DISMISS_USER;
}
/**
* Allows developers to apply additional logic to the dismissing notice process.
* Executes after updating option or user meta (according to the notice level).
*
*
* @param string $notice_id Notice ID (slug).
* @param integer $level Notice level.
* @param array $notices Dismissed notices.
*/
do_action( 'wpcode_admin_notice_dismiss_ajax', $post['id'], $level, $notices );
wp_send_json_success();
}
/**
* AJAX sub-routine that updates dismissed notices option.
*
*
* @param string $id Notice Id.
*
* @return array Notices.
*/
private function dismiss_global( $id ) {
$id = str_replace( 'global-', '', $id );
$notices = get_option( 'wpcode_admin_notices', array() );
$notices[ $id ] = array(
'time' => time(),
'dismissed' => true,
);
update_option( 'wpcode_admin_notices', $notices, true );
// If this is a multisite, and they dismissed the review-request let's keep a note in the user's meta.
if ( is_multisite() && is_super_admin() && 'review_request' === $id ) {
update_user_meta( get_current_user_id(), 'wpcode_dismissed_review_request', true );
}
return $notices;
}
/**
* AJAX sub-routine that updates dismissed notices user meta.
*
*
* @param string $id Notice Id.
*
* @return array Notices.
*/
private function dismiss_user( $id ) {
$user_id = get_current_user_id();
$notices = get_user_meta( $user_id, 'wpcode_admin_notices', true );
$notices = ! is_array( $notices ) ? array() : $notices;
$notices[ $id ] = array(
'time' => time(),
'dismissed' => true,
);
update_user_meta( $user_id, 'wpcode_admin_notices', $notices );
return $notices;
}
}
@@ -0,0 +1,281 @@
<?php
/**
* Class used to load admin pages allowing child classes
* to replace or add pages by changing the classes used.
*
* @package WPCode
*/
/**
* Class WPCode admin page loader.
*/
class WPCode_Admin_Page_Loader {
/**
* Array of admin pages to load.
*
* @var array
*/
public $pages = array();
/**
* Slugs of pages that should not be visible in the submenu.
*
* @var array
*/
public $hidden_pages = array();
/**
* Constructor.
*/
public function __construct() {
$this->require_files();
$this->hooks();
}
/**
* Hooks.
*
* @return void
*/
public function hooks() {
add_action( 'admin_menu', array( $this, 'register_admin_menu' ), 9 );
add_filter( 'plugin_action_links_' . WPCODE_PLUGIN_BASENAME, array( $this, 'add_plugin_action_links' ) );
// Hide submenus.
add_filter( 'parent_file', array( $this, 'hide_menus' ), 1020 );
// Save Screen options.
add_filter( 'set-screen-option', array( $this, 'screen_options_set' ), 10, 3 );
add_filter( 'set_screen_option_wpcode_snippets_per_page', array( $this, 'screen_options_set' ), 10, 3 );
}
/**
* Load required files for the admin pages.
*
* @return void
*/
public function require_files() {
require_once WPCODE_PLUGIN_PATH . 'includes/admin/pages/trait-wpcode-revisions-display.php';
require_once WPCODE_PLUGIN_PATH . 'includes/admin/pages/trait-wpcode-my-library-markup.php';
require_once WPCODE_PLUGIN_PATH . 'includes/admin/pages/trait-wpcode-wpconsent-notice.php';
require_once WPCODE_PLUGIN_PATH . 'includes/admin/pages/class-wpcode-admin-page.php';
require_once WPCODE_PLUGIN_PATH . 'includes/admin/pages/class-wpcode-admin-page-headers-footers.php';
require_once WPCODE_PLUGIN_PATH . 'includes/admin/pages/class-wpcode-admin-page-code-snippets.php';
require_once WPCODE_PLUGIN_PATH . 'includes/admin/pages/class-wpcode-admin-page-snippet-manager.php';
require_once WPCODE_PLUGIN_PATH . 'includes/admin/pages/class-wpcode-admin-page-library.php';
require_once WPCODE_PLUGIN_PATH . 'includes/admin/pages/class-wpcode-admin-page-generator.php';
require_once WPCODE_PLUGIN_PATH . 'includes/admin/pages/class-wpcode-admin-page-tools.php';
require_once WPCODE_PLUGIN_PATH . 'includes/admin/pages/class-wpcode-admin-page-settings.php';
require_once WPCODE_PLUGIN_PATH . 'includes/admin/pages/class-wpcode-admin-page-click.php';
require_once WPCODE_PLUGIN_PATH . 'includes/admin/pages/class-wpcode-admin-page-pixel.php';
require_once WPCODE_PLUGIN_PATH . 'includes/admin/pages/class-wpcode-admin-page-file-editor.php';
require_once WPCODE_PLUGIN_PATH . 'includes/admin/pages/class-wpcode-admin-page-search-replace.php';
require_once WPCODE_PLUGIN_PATH . 'includes/admin/pages/class-wpcode-admin-page-duplicator.php';
require_once WPCODE_PLUGIN_PATH . 'includes/admin/pages/class-wpcode-admin-page-live-preview.php';
}
/**
* Load the pages classes allowing child classes to replace.
*
* @return void
*/
public function prepare_pages() {
if ( $this->is_headers_footers_mode() ) {
$this->pages['headers_footers'] = 'WPCode_Admin_Page_Headers_Footers';
return;
}
$this->pages['code_snippets'] = 'WPCode_Admin_Page_Code_Snippets';
$this->pages['snippet_manager'] = 'WPCode_Admin_Page_Snippet_Manager';
$this->pages['headers_footers'] = 'WPCode_Admin_Page_Headers_Footers';
$this->pages['pixel'] = 'WPCode_Admin_Page_Pixel';
$this->pages['library'] = 'WPCode_Admin_Page_Library';
$this->pages['generator'] = 'WPCode_Admin_Page_Generator';
$this->pages['file_editor'] = 'WPCode_Admin_Page_File_Editor';
$this->pages['search-replace'] = 'WPCode_Admin_Page_Search_Replace';
$this->pages['duplicator'] = 'WPCode_Admin_Page_Duplicator';
$this->pages['tools'] = 'WPCode_Admin_Page_Tools';
$this->pages['settings'] = 'WPCode_Admin_Page_Settings';
$this->pages['click'] = 'WPCode_Admin_Page_Click';
$this->pages['live_preview'] = 'WPCode_Admin_Page_Live_Preview';
}
/**
* Load the pages using their specific classes.
*
* @return void
*/
public function load_pages() {
$this->prepare_pages();
do_action( 'wpcode_before_admin_pages_loaded', $this->pages );
foreach ( $this->pages as $slug => $page_class ) {
if ( ! class_exists( $page_class ) ) {
continue;
}
/**
* @var WPCode_Admin_Page $new_page
*/
$this->pages[ $slug ] = new $page_class();
if ( $this->pages[ $slug ]->hide_menu ) {
$this->hidden_pages[] = $this->pages[ $slug ]->page_slug;
}
}
}
/**
* Add the main menu item used for all the other admin pages.
*
* @return void
*/
public function add_main_menu_item() {
$svg = get_wpcode_icon( 'logo', 36, 34, '-10 -6 80 80' );
$wpcode_icon = 'data:image/svg+xml;base64,' . base64_encode( $svg ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
add_menu_page(
__( 'Code Snippets', 'insert-headers-and-footers' ),
__( 'Code Snippets', 'insert-headers-and-footers' ),
'wpcode_edit_snippets',
'wpcode',
array(
$this,
'admin_menu_page',
),
$wpcode_icon,
'81.45687234432916'
);
}
/**
* Handler for registering the admin menu & loading pages.
*
* @return void
*/
public function register_admin_menu() {
if ( ! $this->is_headers_footers_mode() ) {
$this->add_main_menu_item();
}
$this->load_pages();
}
/**
* Check if the site is in headers & footers only mode.
*
* @return mixed
*/
public function is_headers_footers_mode() {
return wpcode()->settings->get_option( 'headers_footers_mode' );
}
/**
* Generic handler for the wpcode pages.
*
* @return void
*/
public function admin_menu_page() {
do_action( 'wpcode_admin_page' );
}
/**
* Add a link to the code snippets list in the plugins list view.
*
* @param array $links The links specific to our plugin.
*
* @return array
*/
public function add_plugin_action_links( $links ) {
$url = add_query_arg(
array(
'page' => 'wpcode',
),
admin_url( 'admin.php' )
);
$text = esc_html__( 'Code Snippets', 'insert-headers-and-footers' );
if ( wpcode()->settings->get_option( 'headers_footers_mode' ) ) {
$url = add_query_arg(
array(
'page' => 'wpcode-headers-footers',
),
admin_url( 'options-general.php' )
);
$text = esc_html__( 'Settings', 'insert-headers-and-footers' );
}
$custom = array();
$custom['wpcodepro'] = sprintf(
'<a href="%1$s" aria-label="%2$s" target="_blank" rel="noopener noreferrer"
style="color: #00a32a; font-weight: 700;"
onmouseover="this.style.color=\'#008a20\';"
onmouseout="this.style.color=\'#00a32a\';"
>%3$s</a>',
wpcode_utm_url(
'https://wpcode.com/lite/',
'all-plugins',
'get-wpcode-pro'
),
esc_attr__( 'Upgrade to WPCode Pro', 'insert-headers-and-footers' ),
esc_html__( 'Get WPCode Pro', 'insert-headers-and-footers' )
);
$custom['settings'] = sprintf(
'<a href="%1$s">%2$s</a>',
$url,
$text
);
return array_merge( $custom, $links );
}
/**
* Hide menu items for pages that should be hidden.
* We're using the parent_file filter to improve compatibility with admin-menu-editor.
*
* @param string $parent_file The parent file.
*
* @return string
*/
public function hide_menus( $parent_file ) {
foreach ( $this->hidden_pages as $page ) {
remove_submenu_page( 'wpcode', $page );
}
return $parent_file;
}
/**
* Set the per page option for the snippets list screen.
*
* @param $status
* @param $option
* @param $value
*
* @return mixed
*/
public function screen_options_set( $status, $option, $value ) {
if ( isset( $_POST['wpcode_screen_order_by'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification
$order_by = sanitize_text_field( wp_unslash( $_POST['wpcode_screen_order_by'] ) ); // phpcs:ignore WordPress.Security.NonceVerification
update_user_option( get_current_user_id(), 'wpcode_snippets_order_by', $order_by );
}
if ( isset( $_POST['wpcode_screen_order'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification
$order_by = sanitize_text_field( wp_unslash( $_POST['wpcode_screen_order'] ) ); // phpcs:ignore WordPress.Security.NonceVerification
update_user_option( get_current_user_id(), 'wpcode_snippets_order', $order_by );
}
if ( 'wpcode_snippets_per_page' === $option ) {
return absint( $value );
}
return $status;
}
}
@@ -0,0 +1,175 @@
<?php
/**
* Central place to load the Code Editor used throughout the plugin with
* similar settings.
*
* @package WPCode
*/
/**
* Class WPCode_Code_Editor.
*/
class WPCode_Code_Editor {
/**
* Array of settings used to instantiate the editor.
*
* @var array
*/
private $settings;
/**
* Array of ids of textareas to init as code editors.
*
* @var array
*/
private $editors;
/**
* WPCode_Code_Editor Constructor.
*
* @param string $code_type The code type that will be converted to the mime type for the editor.
*/
public function __construct( $code_type = 'html' ) {
$this->load_code_mirror( $code_type );
}
/**
* If called, this loads CodeMirror on the current admin page with checks.
*
* @param string $code_type The code type that will be converted to the mime type for the editor.
*
* @return array|false
*/
public function load_code_mirror( $code_type ) {
if ( ! function_exists( 'wp_enqueue_code_editor' ) ) {
return false;
}
$editor_args = array(
'type' => wpcode()->execute->get_mime_for_code_type( $code_type ),
'showHint' => true,
'codemirror' => array(
'matchBrackets' => true,
'gutters' => array( 'CodeMirror-lint-markers', 'CodeMirror-foldgutter' ),
'foldGutter' => true,
'autoCloseBrackets' => true,
'highlightSelectionMatches' => true,
),
);
if ( ! current_user_can( 'wpcode_edit_snippets' ) ) {
$editor_args['codemirror']['readOnly'] = true;
}
// Check if the DISALLOW_UNFILTERED_HTML is defined and print the warning message
if ( defined( 'DISALLOW_UNFILTERED_HTML' ) && DISALLOW_UNFILTERED_HTML ) {
WPCode_Notice::warning(
esc_html__( 'The PHP constant DISALLOW_UNFILTERED_HTML is currently defined, which is preventing WPCode from saving code accurately. Please contact your webmaster for assistance in disabling this restriction.', 'insert-headers-and-footers' )
);
}
// Allow filtering of the editor args.
$editor_args = apply_filters( 'wpcode_editor_config', $editor_args );
// Add filter to override the current user meta for syntax highlighting.
add_filter( 'get_user_metadata', array( $this, 'override_user_meta' ), 10, 4 );
// Enqueue code editor and settings for manipulating HTML.
$this->settings = wp_enqueue_code_editor( $editor_args );
// Remove the filter.
remove_filter( 'get_user_metadata', array( $this, 'override_user_meta' ) );
return $this->settings;
}
/**
* When using the WPCode editor always load syntax highlighting.
*
* @param mixed $value The meta value.
* @param int $object_id The user ID.
* @param string $meta_key The meta key being looked up.
* @param bool $single True if only the first value should be returned.
*
* @return bool|mixed
*/
public function override_user_meta( $value, $object_id, $meta_key, $single ) {
if ( 'syntax_highlighting' !== $meta_key || ! apply_filters( 'wpcode_override_syntax_highlighting', true ) ) {
return $value;
}
return true;
}
/**
* Load hint scripts if needed.
*
* @return void
*/
public function load_hint_scripts() {
wp_enqueue_script( 'htmlhint' );
wp_enqueue_script( 'csslint' );
wp_enqueue_script( 'jshint' );
}
/**
* Update a setting for the editor instance.
*
* @param string $key Key of setting to update.
* @param mixed $value Value to set the setting to, can be string, integer, array.
*
* @return void
*/
public function set_setting( $key, $value ) {
if ( ! isset( $this->settings ) ) {
return;
}
if ( ! isset( $this->settings['codemirror'] ) ) {
$this->settings['codemirror'] = array();
}
$this->settings['codemirror'][ $key ] = $value;
}
/**
* Load the inline script needed to initiate the code editor using the current settings.
*
* @param string $id The textarea ID to init the editor for.
*
* @return void
*/
public function register_editor( $id ) {
$this->editors[] = $id;
}
/**
* Load the inline script needed to initiate the code editor using the current settings.
*
* @return void
*/
public function init_editor() {
wp_add_inline_script(
'code-editor',
sprintf(
'
jQuery( function() {
window.wpcode_editor = window.wpcode_editor ? window.wpcode_editor : {};
var ids = %1$s;
var settings = %2$s;
for ( var i in ids ) {
window.wpcode_editor[ids[i]] = wp.codeEditor.initialize( ids[i], settings );
}
} );',
wp_json_encode( $this->editors ),
wp_json_encode( $this->get_settings() )
)
);
}
/**
* Get the settings.
*
* @return array
*/
public function get_settings() {
return $this->settings;
}
}
@@ -0,0 +1,177 @@
<?php
/**
* Load docs data from the server and store it
* in local file cache in the uplaods folder.
*
* @package WPCode
*/
/**
* The class to load docs data from the server.
*/
class WPCode_Docs {
/**
* The URL from which to grab docs.
*
* @var string
*/
public $url = 'https://cdn.wpcode.com/wp-content/docs.json';
/**
* The categories.
*
* @var array
*/
private $categories;
/**
* The docs data.
*
* @var array
*/
private $docs;
/**
* Load docs data from cache or from the server.
*
* @return void
*/
public function load_docs_data() {
$docs_data = wpcode()->file_cache->get( 'docs', DAY_IN_SECONDS );
if ( false === $docs_data ) {
$docs_data = $this->load_from_server();
wpcode()->file_cache->set( 'docs', $docs_data );
}
$this->categories = isset( $docs_data['categories'] ) ? $docs_data['categories'] : array();
$this->docs = isset( $docs_data['docs'] ) ? $docs_data['docs'] : array();
}
/**
* Get the docs.
*
* @return array
*/
public function get_docs() {
if ( ! isset( $this->docs ) ) {
$this->load_docs_data();
}
return $this->docs;
}
/**
* Get the docs categories.
*
* @return array
*/
public function get_categories() {
if ( ! isset( $this->categories ) ) {
$this->load_docs_data();
}
return $this->categories;
}
/**
* Load the docs data from the server.
*
* @return array
*/
public function load_from_server() {
$request = wp_remote_get( $this->url );
if ( wp_remote_retrieve_response_code( $request ) > 299 ) {
return array();
}
return json_decode( wp_remote_retrieve_body( $request ), true );
}
/**
* Go through all the docs and retrieve just those for this category.
*
* @param string $slug The category slug.
*
* @return array
*/
public function get_docs_for_category( $slug ) {
$docs = $this->get_docs();
ksort( $docs );
$category_docs = array();
// Until we drop PHP 5.2 support to use closure.
foreach ( $docs as $doc ) {
if ( ! in_array( $slug, $doc['categories'], true ) ) {
continue;
}
$category_docs[] = $doc;
}
return $category_docs;
}
/**
* Output the docs categories markup.
*
* @return void
*/
public function get_categories_accordion() {
?>
<div id="wpcode-help-categories" style="transition: opacity 300ms ease-in 0s; opacity: 1;">
<ul class="wpcode-help-categories-toggle">
<?php
$ci = 0;
$categories = $this->get_categories();
foreach ( $categories as $slug => $category_title ) {
$style = 0 === $ci ? 'display:block' : '';
$class = 0 === $ci ? 'wpcode-help-category open' : 'wpcode-help-category';
$ci ++;
$docs = $this->get_docs_for_category( $slug );
$i = 0;
?>
<li class="<?php echo esc_attr( $class ); ?>">
<header>
<?php wpcode_icon( 'folder', 28, 22 ); ?>
<span><?php echo esc_html( $category_title ); ?></span>
<?php wpcode_icon( 'arrow', 10, 16 ); ?>
</header>
<ul class="wpcode-help-docs" style="<?php echo esc_attr( $style ); ?>">
<?php
foreach ( $docs as $doc ) {
$i ++;
?>
<li>
<?php wpcode_icon( 'file-text', 16, 16 ); ?>
<a href="<?php echo esc_url( wpcode_utm_url( $doc['url'], 'help-overlay', 'view-doc', esc_attr( $doc['title'] ) ) ); ?>" rel="noopener noreferrer" target="_blank">
<?php echo esc_html( $doc['title'] ); ?>
</a>
</li>
<?php
if ( 5 === $i && count( $docs ) > 5 ) {
echo '<div style="display: none;">';
}
}
if ( count( $docs ) > 5 ) {
echo '</div>' // Hidden div for the rest of the elements.
?>
<button class="wpcode-button wpcode-button-secondary viewall" type="button">
<?php
printf(
// Translators: Placeholder for the category name.
esc_html__( 'View All %s Docs', 'insert-headers-and-footers' ),
esc_html( $category_title )
);
?>
</button>
<?php } ?>
</ul>
</li>
<?php } ?>
</ul>
</div>
<?php
}
}
@@ -0,0 +1,250 @@
<?php
/**
* Feature notices to highlight certain features in key areas of the plugin.
*
* @package WPCode
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Class WPCode_Features_Notices
*/
class WPCode_Features_Notices {
/**
* WPCode_Features_Notices constructor.
*/
public function __construct() {
$this->hooks();
}
/**
* Hooks for the class.
*/
public function hooks() {
add_action( 'admin_init', array( $this, 'maybe_show_notices' ) );
}
/**
* Get all notices that we might display.
*
* The 'pages' key in each notice can be structured in multiple ways:
* 1. Legacy format: array( 'page-id-1', 'page-id-2' ) - Shows on all tabs of these pages
* 2. Page with specific tabs: array( 'page-id' => array( 'tab-1', 'tab-2' ) ) - Shows only when one of the specified tabs is active
* 3. Page with all tabs: array( 'page-id' => true ) - Shows on all tabs of this page
* 4. Multiple pages with different tabs: array( 'page-1' => array( 'tab-1' ), 'page-2' => array( 'tab-2', 'tab-3' ) )
*
* @return array
*/
public static function get_all_notices() {
$notices = array(
// Original example using the legacy format (still supported)
'snippets_library_feature' => array(
'pages' => array(
'wpcode-tools' => array(
'export',
)
),
'message' => sprintf(
// translators: %1$s and %2$s are strong HTML tags, %3$s and %4$s are links.
esc_html__( '%1$sPro Tip:%2$s Did you know all WPCode premium plans include access to a private snippet library? Moving snippets from one site to another has never been easier. %3$sUpgrade today with a special discount%4$s.', 'insert-headers-and-footers' ),
'<strong>',
'</strong>',
'<a href="' . esc_url( wpcode_utm_url( 'https://wpcode.com/lite/', 'features-notices', 'tools-library', 'upgrade-now' ) ) . '" target="_blank" rel="noopener noreferrer">', '</a>'
),
'type' => 'info',
'dismissible' => true,
'class' => 'wpcode-feature-notice-library',
),
);
return $notices;
}
/**
* Check if we should show notices and add the action to display them.
*/
public function maybe_show_notices() {
// Only show notices to users who can edit snippets.
if ( ! current_user_can( 'wpcode_edit_snippets' ) ) {
return;
}
add_action( 'admin_notices', array( $this, 'display_notices' ) );
add_action( 'wpcode_admin_notices', array( $this, 'display_notices' ) );
}
/**
* Display the notices.
*
* This method checks the current page and tab against the notices configuration
* and displays the appropriate notices. It supports both the legacy format
* (simple array of page IDs) and the new format (associative array of page IDs
* with tabs as values).
*
* Notices with specified tabs will only be displayed when one of those tabs is active.
* This ensures that tab-specific notices are not shown when no tab is specified.
*
* @since 1.x.x Updated to support tabs for pages
* @since 1.x.y Updated to ensure notices with tabs are only shown when a matching tab is active
*/
public function display_notices() {
// Get the current screen to check if we should display notices.
$screen = get_current_screen();
if ( ! $screen ) {
return;
}
// Get the current page ID.
$page_id = $this->get_current_page_id( $screen );
if ( empty( $page_id ) ) {
return;
}
// Get the current tab.
$current_tab = $this->get_current_tab();
// Get all notices.
$notices = self::get_all_notices();
// Get dismissed notices.
$dismissed_notices = $this->get_dismissed_notices();
foreach ( $notices as $id => $notice ) {
// Skip if this notice has been dismissed.
if ( isset( $dismissed_notices[ $id ] ) && ! empty( $dismissed_notices[ $id ]['dismissed'] ) ) {
continue;
}
// Skip if no pages are defined for this notice.
if ( empty( $notice['pages'] ) ) {
continue;
}
$show_notice = false;
// Check if the notice should be displayed on the current page and tab.
foreach ( $notice['pages'] as $notice_page => $notice_tabs ) {
// Handle the legacy format where pages is a simple array of page IDs.
if ( is_int( $notice_page ) && is_string( $notice_tabs ) ) {
if ( $notice_tabs === $page_id ) {
$show_notice = true;
break;
}
continue;
}
// Skip if not on the current page.
if ( $notice_page !== $page_id ) {
continue;
}
// If tabs are specified for this page.
if ( is_array( $notice_tabs ) ) {
// Only show if the current tab is in the list of tabs for this notice.
// This ensures notices with tabs are not shown when no tab is specified.
if ( ! empty( $current_tab ) && in_array( $current_tab, $notice_tabs, true ) ) {
$show_notice = true;
break;
}
} elseif ( true === $notice_tabs ) {
// If tabs is set to true, show on all tabs of this page.
$show_notice = true;
break;
} else {
// For any other value, show on all tabs of this page (backward compatibility).
$show_notice = true;
break;
}
}
if ( ! $show_notice ) {
continue;
}
// Display the notice.
$this->display_notice( $id, $notice );
}
}
/**
* Display a single notice.
*
* @param string $id The notice ID.
* @param array $notice The notice data.
*/
public function display_notice( $id, $notice ) {
$dismiss_type = $notice['dismissible'] ? WPCode_Notice::DISMISS_GLOBAL : WPCode_Notice::DISMISS_NONE;
$args = array(
'dismiss' => $dismiss_type,
'slug' => $id,
'autop' => true,
'class' => ! empty( $notice['class'] ) ? $notice['class'] : 'wpcode-feature-notice',
);
// Use the add method with the notice type.
WPCode_Notice::add( $notice['message'], $notice['type'], $args );
}
/**
* Get the current page ID based on the screen.
*
* @param WP_Screen $screen The current screen.
*
* @return string The page ID or empty string if not on a WPCode page.
*/
public function get_current_page_id( $screen ) {
// Check if we're on a WPCode page.
if ( strpos( $screen->id, 'wpcode' ) === false ) {
return '';
}
// Extract the page ID from the screen ID.
$page_id = str_replace( 'toplevel_page_', '', $screen->id );
// Handle sub-pages.
if ( strpos( $screen->id, 'code-snippets_page_' ) !== false ) {
$page_id = str_replace( 'code-snippets_page_', '', $screen->id );
}
return $page_id;
}
/**
* Get the current tab from the URL parameters.
*
* This method retrieves the 'tab' parameter from the URL query string.
* It's used to determine which tab is currently active on a page,
* which is then used to decide whether to display certain notices.
*
* @return string The current tab or empty string if no tab is specified.
* @since 1.x.x
*
*/
public function get_current_tab() {
// phpcs:ignore WordPress.Security.NonceVerification.Recommended
return isset( $_GET['view'] ) ? sanitize_text_field( wp_unslash( $_GET['view'] ) ) : '';
}
/**
* Get dismissed notices.
*
* @return array
*/
public function get_dismissed_notices() {
$user_dismissed = get_user_meta( get_current_user_id(), 'wpcode_admin_notices', true );
$user_dismissed = is_array( $user_dismissed ) ? $user_dismissed : array();
$global_dismissed = get_option( 'wpcode_admin_notices', array() );
$global_dismissed = is_array( $global_dismissed ) ? $global_dismissed : array();
return array_merge( $user_dismissed, $global_dismissed );
}
}
// Initialize the class.
new WPCode_Features_Notices();
@@ -0,0 +1,76 @@
<?php
/**
* Load classes used for importing data from other plugins.
*
* @package WPCode
*/
/**
* WPCode_Importers class.
*/
class WPCode_Importers {
/**
* Available importers.
*
* @var WPCode_Importer_Type[]
*/
public $importers = array();
/**
* Constructor.
*/
public function __construct() {
$this->require_files();
$this->load_importers();
}
/**
* Require the importer classes.
*
* @return void
*/
private function require_files() {
require_once WPCODE_PLUGIN_PATH . 'includes/admin/importers/class-wpcode-importer-type.php';
require_once WPCODE_PLUGIN_PATH . 'includes/admin/importers/class-wpcode-importer-code-snippets.php';
require_once WPCODE_PLUGIN_PATH . 'includes/admin/importers/class-wpcode-importer-code-snippets-premium.php';
require_once WPCODE_PLUGIN_PATH . 'includes/admin/importers/class-wpcode-importer-woody.php';
require_once WPCODE_PLUGIN_PATH . 'includes/admin/importers/class-wpcode-importer-simple-custom-css-and-js.php';
require_once WPCODE_PLUGIN_PATH . 'includes/admin/importers/class-wpcode-importer-header-footer-code-manager.php';
require_once WPCODE_PLUGIN_PATH . 'includes/admin/importers/class-wpcode-importer-post-snippets.php';
}
/**
* Load the available importers instances.
*
* @return void
*/
private function load_importers() {
if ( empty( $this->importers ) ) {
$this->importers = array(
'code-snippets' => new WPCode_Importer_Code_Snippets(),
'code-snippets-pro' => new WPCode_Importer_Code_Snippets_Pro(),
'woody' => new WPCode_Importer_Woody(),
'simple-custom-css-js' => new WPCode_Importer_Simple_Custom_CSS_and_JS(),
'header-footer-code-manager' => new WPCode_Importer_Header_Footer_Code_Manager(),
'post-snippets' => new WPCode_Importer_Post_Snippets(),
);
}
}
/**
* Get the importers with registered data.
*
* @return array
*/
public function get_importers() {
$importers = array();
foreach ( $this->importers as $importer ) {
$importers = $importer->register( $importers );
}
return $importers;
}
}
@@ -0,0 +1,287 @@
<?php
/**
* Base class for the WPCode snippets metabox.
*
* @package WPCode
*/
/**
* WPCode metabox snippets.
*/
abstract class WPCode_Metabox_Snippets {
/**
* Id used for registering the metabox using add_meta_box.
*
* @var string
*/
public $id = 'wpcode-metabox-snippets';
/**
* Title of the metabox.
*
* @var string
*/
public $title;
/**
* Tabs for this metabox.
*
* @var array
*/
public $tabs;
/**
* If true, the metabox will scroll into view when the page loads.
*
* @var bool
*/
protected $scroll_into_view = false;
/**
* Register the metabox.
*/
public function __construct() {
$this->hooks();
}
/**
* Load the translatable strings.
*
* @return void
*/
public function load_strings() {
$this->title = __( 'WPCode Page Scripts', 'insert-headers-and-footers' );
$this->tabs = array(
'header' => __( 'Header', 'insert-headers-and-footers' ),
'footer' => __( 'Footer', 'insert-headers-and-footers' ),
);
$body_supported = function_exists( 'wp_body_open' ) && version_compare( get_bloginfo( 'version' ), '5.2', '>=' );
if ( $body_supported ) {
$this->tabs['body'] = __( 'Body', 'insert-headers-and-footers' );
}
$this->tabs['code'] = __( 'Custom Code Snippet', 'insert-headers-and-footers' );
$this->tabs['revisions'] = __( 'Revisions', 'insert-headers-and-footers' );
}
/**
* Add hooks.
*
* @return void
*/
public function hooks() {
add_action( 'admin_init', array( $this, 'load_strings' ) );
add_action( 'add_meta_boxes', array( $this, 'register_metabox' ) );
add_action( 'admin_head', array( $this, 'close_metabox_for_current_screen' ) );
}
/**
* Make sure the metabox is closed by default.
*
* @return void
*/
public function close_metabox_for_current_screen() {
// Close the metabox by default.
$screen = get_current_screen();
if ( ! isset( $screen->id ) ) {
return;
}
if ( apply_filters( 'wpcode_metabox_scripts_force_collapse', true, $screen ) ) {
add_filter(
'get_user_option_closedpostboxes_' . $screen->id,
array(
$this,
'add_metabox_to_user_closed',
)
);
}
}
/**
* Add our metabox id to the array of closed metaboxes when the page loads.
*
* @param mixed $closed The array of closed metaboxes.
*
* @return array
*/
public function add_metabox_to_user_closed( $closed ) {
// Make sure it's an array.
if ( ! is_array( $closed ) ) {
$closed = array();
}
$closed[] = $this->id;
return $closed;
}
/**
* Use `add_meta_box` to register the metabox for this class.
*
* @param string $post_type The post type of the screen where metaboxes are loaded.
*
* @return void
*/
public function register_metabox( $post_type ) {
// Don't show the metabox to users who aren't allowed to manage snippets.
if ( ! current_user_can( 'wpcode_edit_html_snippets' ) ) {
return;
}
if ( wpcode()->settings->get_option( 'headers_footers_mode' ) ) {
// Don't load the metabox when headers & footers mode is enabled.
return;
}
$post_type_details = get_post_type_object( $post_type );
// Add metabox only on public post types.
if ( empty( $post_type_details->public ) ) {
return;
}
add_meta_box(
$this->id,
$this->title,
array(
$this,
'output_metabox_content',
),
$post_type,
'normal',
apply_filters( 'wpcode_post_metabox_priority', 'default' )
);
}
/**
* Metabox content output callback.
*
* @param WP_Post $post The post object.
*
* @return void
*/
public function output_metabox_content( $post ) {
$this->metabox_start();
echo '<div class="wpcode-content">';
$this->tabs_navigation();
$this->tabs_content( $post );
echo '</div>';
$this->metabox_end();
}
/**
* Output the menu for switching between tabs.
*
* @return void
*/
public function tabs_navigation() {
if ( empty( $this->tabs ) ) {
return;
}
?>
<div class="wpcode-admin-tabs-navigation">
<ul class="wpcode-admin-tabs">
<?php
$class = '';
foreach ( $this->tabs as $tab_id => $tab_name ) {
if ( $this->get_active_tab() === $tab_id ) {
$class = 'active';
}
?>
<li>
<button type="button" data-target="<?php echo esc_attr( $this->get_tab_html_id( $tab_id ) ); ?>" class="<?php echo esc_attr( $class ); ?>"><?php echo esc_html( $tab_name ); ?></button>
</li>
<?php
$class = '';
}
do_action( 'wpcode_metabox_admin_tabs' )
?>
</ul>
</div>
<?php
}
/**
* Output the tabs content using tab-specific methods by their ids.
*
* @param WP_Post $post The post object.
*
* @return void
*/
public function tabs_content( $post ) {
$tab_ids = array_keys( $this->tabs );
foreach ( $tab_ids as $tab_id ) {
$class = 'wpcode-admin-tab-content';
$class .= $this->get_active_tab() === $tab_id ? ' active' : '';
printf(
'<div class="%1$s" id="%2$s">',
esc_attr( $class ),
esc_attr( $this->get_tab_html_id( $tab_id ) )
);
if ( method_exists( $this, 'output_tab_' . $tab_id ) ) {
call_user_func( array( $this, 'output_tab_' . $tab_id ), $post );
} else {
$this->output_tab( $tab_id, $post );
}
echo '</div>';
}
}
/**
* Generic tab content output method.
*
* @param string $tab_id The tab id.
* @param WP_Post $post The post object.
*
* @return void
*/
public function output_tab( $tab_id, $post ) {
}
/**
* Get the active tab id.
*
* @return string
*/
public function get_active_tab() {
$active_tab = 'header';
if ( isset( $_GET['wpcode-show'] ) && array_key_exists( sanitize_key( $_GET['wpcode-show'] ), $this->tabs ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
$active_tab = sanitize_key( $_GET['wpcode-show'] ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended
$this->scroll_into_view = true;
}
return $active_tab;
}
/**
* Get a standard tab id from the array key.
*
* @param string $tab_id The tab id.
*
* @return string
*/
public function get_tab_html_id( $tab_id ) {
return 'wpcode-tab-' . $tab_id;
}
/**
* Method for running logic at the start of the metabox.
*
* @return void
*/
public function metabox_start() {
}
/**
* Method for running logic at the end of the metabox, loading scripts, for example.
*
* @return void
*/
public function metabox_end() {
}
}
@@ -0,0 +1,510 @@
<?php
/**
* Notifications from remote source.
*
* @package WPCode
*/
/**
* Notifications.
*/
class WPCode_Notifications {
/**
* Source of notifications content.
*
* @var string
*/
const SOURCE_URL = 'https://plugin.wpcode.com/wp-content/notifications.json';
/**
* Option value.
*
* @var bool|array
*/
public $option = false;
/**
* The name of the option used to store the data.
*
* @var string
*/
public static $option_name = 'wpcode_notifications';
/**
* WPCode_Notifications constructor.
*/
public function __construct() {
$this->init();
}
/**
* Initialize class.
*/
public function init() {
$this->hooks();
}
/**
* Register hooks.
*/
public function hooks() {
add_action( 'wp_ajax_wpcode_notification_dismiss', array( $this, 'dismiss' ) );
add_action( 'wpcode_admin_notifications_update', array( $this, 'update' ) );
}
/**
* Check if user has access and is enabled.
*
* @return bool
*/
public function has_access() {
return apply_filters( 'wpcode_admin_notifications_has_access', ! wpcode()->settings->get_option( 'hide_am_notices', false ) );
}
/**
* Get option value.
*
* @param bool $cache Reference property cache if available.
*
* @return array
*/
public function get_option( $cache = true ) {
if ( $this->option && $cache ) {
return $this->option;
}
$option = get_option( self::$option_name, array() );
$this->option = array(
'update' => ! empty( $option['update'] ) ? $option['update'] : 0,
'events' => ! empty( $option['events'] ) ? $option['events'] : array(),
'feed' => ! empty( $option['feed'] ) ? $option['feed'] : array(),
'dismissed' => ! empty( $option['dismissed'] ) ? $option['dismissed'] : array(),
);
return $this->option;
}
/**
* Fetch notifications from feed.
*
* @return array
*/
public function fetch_feed() {
$res = wp_remote_get( self::SOURCE_URL );
if ( is_wp_error( $res ) ) {
return array();
}
$body = wp_remote_retrieve_body( $res );
if ( empty( $body ) ) {
return array();
}
return $this->verify( json_decode( $body, true ) );
}
/**
* Verify notification data before it is saved.
*
* @param array $notifications Array of notifications items to verify.
*
* @return array
* @since {VERSION}
*/
public function verify( $notifications ) {
$data = array();
if ( ! is_array( $notifications ) || empty( $notifications ) ) {
return $data;
}
$option = $this->get_option();
foreach ( $notifications as $notification ) {
// The message and license should never be empty, if they are, ignore.
if ( empty( $notification['content'] ) || empty( $notification['type'] ) ) {
continue;
}
// Ignore if notification is not ready to display(based on start time).
if ( ! empty( $notification['start'] ) && time() < strtotime( $notification['start'] ) ) {
continue;
}
// Ignore if expired.
if ( ! empty( $notification['end'] ) && time() > strtotime( $notification['end'] ) ) {
continue;
}
// Check that the license type matches.
if ( ! in_array( $this->get_license_type(), (array) $notification['type'], true ) ) {
continue;
}
// Ignore if notification has already been dismissed.
$notification_already_dismissed = false;
if ( is_array( $option['dismissed'] ) && ! empty( $option['dismissed'] ) ) {
foreach ( $option['dismissed'] as $dismiss_notification ) {
if ( $notification['id'] === $dismiss_notification['id'] ) {
$notification_already_dismissed = true;
break;
}
}
}
if ( true === $notification_already_dismissed ) {
continue;
}
// Ignore if notification existed before installing WPCode.
// Prevents bombarding the user with notifications after activation.
$activated = get_option( 'ihaf_activated', array() );
if (
! empty( $activated['wpcode'] ) &&
! empty( $notification['start'] ) &&
$activated['wpcode'] > strtotime( $notification['start'] )
) {
continue;
}
$data[] = $notification;
}
return $data;
}
/**
* Verify saved notification data for active notifications.
*
* @param array $notifications Array of notifications items to verify.
*
* @return array
*/
public function verify_active( $notifications ) {
if ( ! is_array( $notifications ) || empty( $notifications ) ) {
return array();
}
// Remove notifications that are not active, or if the license type not exists.
foreach ( $notifications as $key => $notification ) {
if (
( ! empty( $notification['start'] ) && time() < strtotime( $notification['start'] ) ) ||
( ! empty( $notification['end'] ) && time() > strtotime( $notification['end'] ) )
) {
unset( $notifications[ $key ] );
}
}
return $notifications;
}
/**
* Get notification data.
*
* @return array
*/
public function get() {
if ( ! $this->has_access() ) {
return array();
}
$option = $this->get_option();
// Update notifications using async task.
if ( empty( $option['update'] ) || time() > $option['update'] + DAY_IN_SECONDS ) {
if ( false === wp_next_scheduled( 'wpcode_admin_notifications_update' ) ) {
wp_schedule_single_event( time(), 'wpcode_admin_notifications_update' );
}
}
$events = ! empty( $option['events'] ) ? $this->verify_active( $option['events'] ) : array();
$feed = ! empty( $option['feed'] ) ? $this->verify_active( $option['feed'] ) : array();
$notifications = array();
$notifications['active'] = array_merge( $events, $feed );
$notifications['active'] = $this->get_notifications_with_human_readeable_start_time( $notifications['active'] );
$notifications['active'] = $this->get_notifications_with_formatted_content( $notifications['active'] );
$notifications['dismissed'] = ! empty( $option['dismissed'] ) ? $option['dismissed'] : array();
$notifications['dismissed'] = $this->get_notifications_with_human_readeable_start_time( $notifications['dismissed'] );
$notifications['dismissed'] = $this->get_notifications_with_formatted_content( $notifications['dismissed'] );
return $notifications;
}
/**
* Improve format of the content of notifications before display. By default, it just runs wpautop.
*
* @param array $notifications The notifications to be parsed.
*
* @return array
*/
public function get_notifications_with_formatted_content( $notifications ) {
if ( ! is_array( $notifications ) || empty( $notifications ) ) {
return $notifications;
}
foreach ( $notifications as $key => $notification ) {
if ( ! empty( $notification['content'] ) ) {
$notifications[ $key ]['content'] = wpautop( $notification['content'] );
$notifications[ $key ]['content'] = apply_filters( 'wpcode_notification_content_display', $notifications[ $key ]['content'] );
}
}
return $notifications;
}
/**
* Get notifications start time with human time difference
*
* @param array $notifications The array of notifications to convert.
*
* @return array
*/
public function get_notifications_with_human_readeable_start_time( $notifications ) {
if ( ! is_array( $notifications ) || empty( $notifications ) ) {
return array();
}
foreach ( $notifications as $key => $notification ) {
if ( empty( $notification['start'] ) ) {
continue;
}
// Translators: Human-Readable time to display.
$modified_start_time = sprintf( __( '%1$s ago', 'insert-headers-and-footers' ), human_time_diff( strtotime( $notification['start'] ), time() ) );
$notifications[ $key ]['start'] = $modified_start_time;
}
return $notifications;
}
/**
* Get active notifications.
*
* @return array $notifications['active'] active notifications
*/
public function get_active_notifications() {
$notifications = $this->get();
// Show only 5 active notifications plus any that has a priority of 1.
$all_active = isset( $notifications['active'] ) ? $notifications['active'] : array();
$displayed = array();
foreach ( $all_active as $notification ) {
if ( ( isset( $notification['priority'] ) && 1 === $notification['priority'] ) || count( $displayed ) < 5 ) {
$displayed[] = $notification;
}
}
return $displayed;
}
/**
* Get dismissed notifications.
*
* @return array $notifications['dismissed'] dismissed notifications
*/
public function get_dismissed_notifications() {
$notifications = $this->get();
return isset( $notifications['dismissed'] ) ? $notifications['dismissed'] : array();
}
/**
* Get notification count.
*
* @return int
*/
public function get_count() {
return count( $this->get_active_notifications() );
}
/**
* Get the dismissed notifications count.
*
* @return int
*/
public function get_dismissed_count() {
return count( $this->get_dismissed_notifications() );
}
/**
* Check if a notification has been dismissed before
*
* @param array $notification The notification to check if is dismissed.
*
* @return bool
*/
public function is_dismissed( $notification ) {
if ( empty( $notification['id'] ) ) {
return true;
}
$option = $this->get_option();
foreach ( $option['dismissed'] as $item ) {
if ( $item['id'] === $notification['id'] ) {
return true;
}
}
return false;
}
/**
* Add a manual notification event.
*
* @param array $notification Notification data.
*/
public function add( $notification ) {
if ( empty( $notification['id'] ) || $this->is_dismissed( $notification ) ) {
return false;
}
$option = $this->get_option();
$current_notifications = $option['events'];
foreach ( $current_notifications as $item ) {
if ( $item['id'] === $notification['id'] ) {
return false;
}
}
$notification = $this->verify( array( $notification ) );
$notifications = array_merge( $notification, $current_notifications );
// Sort notifications by priority.
usort(
$notifications,
function ( $a, $b ) {
if ( ! isset( $a['priority'] ) || ! isset( $b['priority'] ) ) {
return 0;
}
if ( $a['priority'] === $b['priority'] ) {
return 0;
}
return $a['priority'] < $b['priority'] ? - 1 : 1;
}
);
update_option(
self::$option_name,
array(
'update' => $option['update'],
'feed' => $option['feed'],
'events' => $notifications,
'dismissed' => $option['dismissed'],
),
false
);
return true;
}
/**
* Update notification data from feed.
*
* @since {VERSION}
*/
public function update() {
$feed = $this->fetch_feed();
$option = $this->get_option();
update_option(
self::$option_name,
array(
'update' => time(),
'feed' => $feed,
'events' => $option['events'],
'dismissed' => array_slice( $option['dismissed'], 0, 30 ), // Limit dismissed notifications to last 30.
),
false
);
}
/**
* Dismiss notification via AJAX.
*/
public function dismiss() {
// Run a security check.
check_ajax_referer( 'wpcode_admin', 'nonce' );
// Check for access and required param.
if ( ! $this->has_access() || empty( $_POST['id'] ) ) {
wp_send_json_error();
}
$id = sanitize_text_field( wp_unslash( $_POST['id'] ) );
$option = $this->get_option();
// Dismiss all notifications and add them to dissmiss array.
if ( 'all' === $id ) {
if ( is_array( $option['feed'] ) && ! empty( $option['feed'] ) ) {
foreach ( $option['feed'] as $key => $notification ) {
array_unshift( $option['dismissed'], $notification );
unset( $option['feed'][ $key ] );
}
}
if ( is_array( $option['events'] ) && ! empty( $option['events'] ) ) {
foreach ( $option['events'] as $key => $notification ) {
array_unshift( $option['dismissed'], $notification );
unset( $option['events'][ $key ] );
}
}
}
$type = is_numeric( $id ) ? 'feed' : 'events';
// Remove notification and add in dismissed array.
if ( is_array( $option[ $type ] ) && ! empty( $option[ $type ] ) ) {
foreach ( $option[ $type ] as $key => $notification ) {
if ( $notification['id'] == $id ) { // phpcs:ignore WordPress.PHP.StrictComparisons
// Add notification to dismissed array.
array_unshift( $option['dismissed'], $notification );
// Remove notification from feed or events.
unset( $option[ $type ][ $key ] );
break;
}
}
}
update_option( self::$option_name, $option, false );
wp_send_json_success();
}
/**
* Delete the notification options.
*/
public static function delete_notifications_data() {
delete_option( self::$option_name );
}
/**
* Get the license type for the current plugin.
*
* @return string
*/
public function get_license_type() {
return 'lite';
}
}
@@ -0,0 +1,560 @@
<?php
/**
* Renderer for the Packs tab inside the Snippet Manager admin page.
*
* Pure rendering — no menu / page registration. Instantiate and call
* render_tab_content() to emit the markup for the Packs tab (browse + detail
* + install modal template).
*
* @package WPCode
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Class WPCode_Packs_View.
*/
class WPCode_Packs_View {
/**
* The active pack slug (from ?pack= query param), if any.
*
* @var string
*/
protected $current_pack_slug = '';
/**
* Fallback dashicon used when a pack has no `pack_icon` set on the
* library. Not a per-pack mapping — just a neutral default so the card
* never renders without an icon.
*/
const DEFAULT_ICON = 'dashicons-archive';
/**
* Constructor — picks up the pack slug from the query string.
*/
public function __construct() {
// phpcs:disable WordPress.Security.NonceVerification.Recommended
if ( isset( $_GET['pack'] ) ) {
$this->current_pack_slug = sanitize_key( wp_unslash( $_GET['pack'] ) );
}
// phpcs:enable
}
/**
* Emit the content for the Packs tab — browse + detail + modal template.
*
* @return void
*/
public function render_tab_content() {
if ( '' !== $this->current_pack_slug ) {
$this->render_detail();
} else {
$this->render_browse();
}
$this->render_install_modal_template();
}
/**
* Whether the Packs tab is the active one based on the request.
*
* @return bool
*/
public function is_active_tab() {
// phpcs:disable WordPress.Security.NonceVerification.Recommended
if ( '' !== $this->current_pack_slug ) {
return true;
}
if ( isset( $_GET['tab'] ) && 'packs' === sanitize_key( wp_unslash( $_GET['tab'] ) ) ) {
return true;
}
// phpcs:enable
return false;
}
/**
* Browse view — uses the stock wpcode-items-metabox pattern so the
* sidebar + search + category filter are wired by the existing
* items-list.js (no custom JS needed for those).
*
* @return void
*/
protected function render_browse() {
$packs = WPCode_Packs::get_instance()->get_packs();
$counts = array();
foreach ( $packs as $r ) {
$cat_slug = $this->group_slug( $r );
if ( ! isset( $counts[ $cat_slug ] ) ) {
$counts[ $cat_slug ] = array(
'count' => 0,
'name' => $this->group_name( $r ),
);
}
$counts[ $cat_slug ]['count']++;
}
$installed_count = 0;
foreach ( $packs as $r ) {
if ( $r['installed'] ) {
$installed_count++;
}
}
?>
<div class="wpcode-add-snippet-description">
<?php esc_html_e( 'Install a curated bundle of snippets that solves a single outcome. After install, manage each snippet individually or remove the whole pack.', 'insert-headers-and-footers' ); ?>
</div>
<div class="wpcode-items-metabox wpcode-metabox">
<div class="wpcode-items-sidebar">
<div class="wpcode-items-search">
<label for="wpcode-items-search">
<span class="screen-reader-text"><?php esc_html_e( 'Search Packs', 'insert-headers-and-footers' ); ?></span>
<?php wpcode_icon( 'search', 16, 16 ); ?>
</label>
<input type="search" class="wpcode-items-search-input" placeholder="<?php esc_attr_e( 'Search Packs', 'insert-headers-and-footers' ); ?>" />
</div>
<ul class="wpcode-items-categories-list wpcode-items-filters">
<li>
<button type="button" data-category="*" class="wpcode-active">
<?php esc_html_e( 'All Packs', 'insert-headers-and-footers' ); ?>
<span class="wpcode-items-count"><?php echo (int) count( $packs ); ?></span>
</button>
</li>
<?php if ( $installed_count > 0 ) : ?>
<li>
<button type="button" data-category="installed">
<?php esc_html_e( 'Installed', 'insert-headers-and-footers' ); ?>
<span class="wpcode-items-count"><?php echo (int) $installed_count; ?></span>
</button>
</li>
<?php endif; ?>
<?php foreach ( $counts as $cat_slug => $info ) : ?>
<li>
<button type="button" data-category="<?php echo esc_attr( $cat_slug ); ?>">
<?php echo esc_html( $info['name'] ); ?>
<span class="wpcode-items-count"><?php echo (int) $info['count']; ?></span>
</button>
</li>
<?php endforeach; ?>
</ul>
</div>
<div class="wpcode-items-list">
<?php if ( empty( $packs ) ) : ?>
<p style="padding: 40px 20px; text-align: center; color: var(--wpcode-text-color-paragraph);">
<?php esc_html_e( 'No packs available yet. Connect to the library to populate packs.', 'insert-headers-and-footers' ); ?>
</p>
<?php else : ?>
<ul class="wpcode-items-list-category">
<?php foreach ( $packs as $pack ) {
$this->render_pack_card( $pack );
} ?>
</ul>
<?php endif; ?>
</div>
</div>
<?php
}
/**
* Render a single pack card using the stock wpcode-list-item pattern.
*
* @param array $pack Pack data.
*
* @return void
*/
protected function render_pack_card( $pack ) {
$category_slug = $this->group_slug( $pack );
$group_name = $this->group_name( $pack );
$icon = $this->pack_icon( $pack );
$detail_url = add_query_arg(
array(
'page' => 'wpcode-snippet-manager',
'tab' => 'packs',
'pack' => $pack['slug'],
),
admin_url( 'admin.php' )
);
$categories = array( $category_slug );
if ( $pack['installed'] ) {
$categories[] = 'installed';
}
$snippet_count = count( $pack['snippets'] );
$description = ! empty( $pack['description'] )
? $pack['description']
: sprintf(
/* translators: %d snippet count. */
_n( '%d snippet bundled into this pack.', '%d snippets bundled into this pack.', $snippet_count, 'insert-headers-and-footers' ),
$snippet_count
);
$max_visible_chips = 2;
$visible_chips = array_slice( $pack['snippets'], 0, $max_visible_chips );
$remaining_chips = $snippet_count - count( $visible_chips );
?>
<li class="wpcode-list-item wpcode-pack-list-item"
data-id="<?php echo esc_attr( $pack['slug'] ); ?>"
data-categories='<?php echo wp_json_encode( $categories ); ?>'
data-pack-slug="<?php echo esc_attr( $pack['slug'] ); ?>"
data-installed="<?php echo $pack['installed'] ? '1' : '0'; ?>">
<div class="wpcode-pack-head">
<div class="wpcode-pack-icon">
<span class="dashicons <?php echo esc_attr( $icon ); ?>"></span>
</div>
<div class="wpcode-pack-head-text">
<h3 title="<?php echo esc_attr( $pack['name'] ); ?>"><?php echo esc_html( $pack['name'] ); ?></h3>
<span class="cat-badge"><?php echo esc_html( $group_name ); ?></span>
</div>
</div>
<p class="wpcode-pack-desc"><?php echo esc_html( $description ); ?></p>
<div class="wpcode-pack-foot">
<div class="wpcode-pack-snippets">
<?php foreach ( $visible_chips as $snippet ) : ?>
<span class="wpcode-pack-snippet-chip" title="<?php echo esc_attr( $snippet['title'] ); ?>"><?php echo esc_html( $snippet['title'] ); ?></span>
<?php endforeach; ?>
<?php if ( $remaining_chips > 0 ) : ?>
<span class="wpcode-pack-snippet-chip wpcode-pack-snippet-chip-more">
<?php
printf(
/* translators: %d more snippets count. */
esc_html__( '+%d more', 'insert-headers-and-footers' ),
(int) $remaining_chips
);
?>
</span>
<?php endif; ?>
</div>
<div class="wpcode-pack-actions">
<?php if ( $pack['installed'] ) : ?>
<a href="<?php echo esc_url( $detail_url ); ?>" class="wpcode-button wpcode-button-secondary"><?php esc_html_e( 'Manage', 'insert-headers-and-footers' ); ?></a>
<?php elseif ( 0 === $snippet_count ) : ?>
<button type="button" class="wpcode-button wpcode-button-secondary" disabled><?php esc_html_e( 'Coming soon', 'insert-headers-and-footers' ); ?></button>
<?php elseif ( ! WPCode_Packs::get_instance()->is_library_connected() ) : ?>
<button type="button" class="wpcode-button wpcode-start-auth"><?php esc_html_e( 'Connect to Library', 'insert-headers-and-footers' ); ?></button>
<?php else : ?>
<button type="button" class="wpcode-button js-wpcode-open-install"><?php esc_html_e( 'Install', 'insert-headers-and-footers' ); ?></button>
<?php endif; ?>
</div>
</div>
</li>
<?php
}
/**
* Render the detail view.
*
* @return void
*/
protected function render_detail() {
$pack = WPCode_Packs::get_instance()->find_pack( $this->current_pack_slug );
if ( null === $pack ) {
echo '<p>' . esc_html__( 'Pack not found.', 'insert-headers-and-footers' ) . '</p>';
return;
}
$group_name = $this->group_name( $pack );
$icon = $this->pack_icon( $pack );
$packs_helper = WPCode_Packs::get_instance();
// Resolve every option's local snippet in a single query instead of one
// query per row.
$library_ids = wp_list_pluck( $pack['snippets'], 'library_id' );
$installed = $packs_helper->find_local_snippets_by_library_ids( $library_ids );
// Map every library snippet to the packs that include it, so we can tell
// the user when an option is shared across packs. The same underlying
// snippet is shared — so the note appears on *every* pack that lists it,
// not just the ones installed after the first.
$shared_pack_names = array();
foreach ( $packs_helper->get_packs() as $other_pack ) {
if ( $other_pack['slug'] === $pack['slug'] ) {
continue;
}
foreach ( $other_pack['snippets'] as $other_option ) {
$shared_pack_names[ (int) $other_option['library_id'] ][ $other_pack['slug'] ] = $other_pack['name'];
}
}
$rows = array();
foreach ( $pack['snippets'] as $option ) {
$lib_id = (int) $option['library_id'];
$local = isset( $installed[ $lib_id ] ) ? $installed[ $lib_id ] : null;
$is_installed = (bool) $local;
// WPCode encodes active state in post_status (publish = active, draft = inactive).
$active = $is_installed && 'publish' === $local->post_status;
$edit_url = $is_installed ? admin_url( 'admin.php?page=wpcode-snippet-manager&snippet_id=' . $local->ID ) : '';
// Other packs that also include this snippet (deduped by slug).
$shared_with = isset( $shared_pack_names[ $lib_id ] ) ? array_values( $shared_pack_names[ $lib_id ] ) : array();
$rows[] = array(
'option' => $option,
'is_installed' => $is_installed,
'active' => $active,
'edit_url' => $edit_url,
'shared_with' => $shared_with,
);
}
$active_count = 0;
foreach ( $rows as $row ) {
if ( $row['active'] ) {
$active_count++;
}
}
$back_url = add_query_arg(
array(
'page' => 'wpcode-snippet-manager',
'tab' => 'packs',
),
admin_url( 'admin.php' )
);
?>
<div class="wpcode-pack-detail"
data-pack-slug="<?php echo esc_attr( $pack['slug'] ); ?>"
data-nonce="<?php echo esc_attr( wp_create_nonce( 'wpcode_packs' ) ); ?>">
<a href="<?php echo esc_url( $back_url ); ?>" class="wpcode-pack-detail-back">
&larr; <?php esc_html_e( 'All packs', 'insert-headers-and-footers' ); ?>
</a>
<div class="wpcode-detail-head">
<div class="wpcode-pack-icon wpcode-pack-icon-lg">
<span class="dashicons <?php echo esc_attr( $icon ); ?>"></span>
</div>
<div class="info">
<h2><?php echo esc_html( $pack['name'] ); ?></h2>
<div class="meta-row">
<span class="cat-badge"><?php echo esc_html( $group_name ); ?></span>
<span class="dot"></span>
<span>
<?php
printf(
/* translators: %d snippet count. */
esc_html( _n( '%d snippet', '%d snippets', count( $pack['snippets'] ), 'insert-headers-and-footers' ) ),
count( $pack['snippets'] )
);
?>
</span>
<?php if ( $pack['installed_at'] > 0 ) : ?>
<span class="dot"></span>
<span>
<?php
printf(
/* translators: %s install date. */
esc_html__( 'Installed %s', 'insert-headers-and-footers' ),
esc_html( date_i18n( get_option( 'date_format' ), $pack['installed_at'] ) )
);
?>
</span>
<?php endif; ?>
</div>
</div>
</div>
<?php if ( ! empty( $pack['description'] ) ) : ?>
<p class="wpcode-detail-desc"><?php echo esc_html( $pack['description'] ); ?></p>
<?php endif; ?>
<div class="wpcode-snippets-card">
<div class="head">
<h3><?php esc_html_e( 'Snippets in this pack', 'insert-headers-and-footers' ); ?></h3>
<div class="meta">
<?php
printf(
/* translators: %1$d active, %2$d total. */
esc_html__( '%1$d of %2$d active', 'insert-headers-and-footers' ),
(int) $active_count,
count( $pack['snippets'] )
);
?>
</div>
</div>
<?php foreach ( $rows as $row ) :
$option = $row['option'];
?>
<?php
// A shared snippet is a single underlying snippet that several
// packs include — it's still toggleable from here, and toggling
// it affects every pack that lists it. Note that wherever it's
// shared so the user understands the link.
$shared_with = $row['shared_with'];
?>
<div class="wpcode-snippet-row <?php echo $row['active'] ? '' : 'is-inactive'; ?>"
data-library-id="<?php echo (int) $option['library_id']; ?>">
<div class="toggle-wrap">
<?php if ( $row['is_installed'] ) : ?>
<div class="wpcode-toggle <?php echo $row['active'] ? 'is-on' : ''; ?> js-wpcode-toggle-option"
role="switch"
aria-checked="<?php echo $row['active'] ? 'true' : 'false'; ?>"
tabindex="0"></div>
<?php else : ?>
<button type="button" class="wpcode-button wpcode-button-secondary js-wpcode-add-option"><?php esc_html_e( 'Add', 'insert-headers-and-footers' ); ?></button>
<?php endif; ?>
</div>
<div class="snippet-info">
<h5><?php echo esc_html( $option['title'] ); ?></h5>
<?php if ( ! empty( $option['needs_personalization'] ) ) : ?>
<span class="wpcode-snippet-personalize-note">
<span class="dashicons dashicons-edit" aria-hidden="true"></span>
<?php esc_html_e( 'Edit this snippet to personalize its values.', 'insert-headers-and-footers' ); ?>
</span>
<?php endif; ?>
<?php if ( ! empty( $shared_with ) ) : ?>
<span class="wpcode-snippet-shared-note">
<?php
printf(
/* translators: %s: comma-separated list of other packs that also include this snippet. */
esc_html__( 'Shared with %s', 'insert-headers-and-footers' ),
esc_html( implode( ', ', $shared_with ) )
);
?>
</span>
<?php endif; ?>
</div>
<div class="actions">
<?php if ( $row['is_installed'] ) : ?>
<a href="<?php echo esc_url( $row['edit_url'] ); ?>" class="wpcode-button wpcode-button-secondary"><?php esc_html_e( 'Edit snippet', 'insert-headers-and-footers' ); ?></a>
<?php endif; ?>
</div>
</div>
<?php endforeach; ?>
</div>
<?php if ( $pack['installed'] ) : ?>
<div class="wpcode-detail-actions">
<button type="button" class="wpcode-button wpcode-button-secondary wpcode-button-danger js-wpcode-remove-pack"><?php esc_html_e( 'Remove pack', 'insert-headers-and-footers' ); ?></button>
</div>
<?php endif; ?>
</div>
<?php
}
/**
* Output the hidden install-modal template + JSON payload.
*
* @return void
*/
protected function render_install_modal_template() {
$packs = WPCode_Packs::get_instance()->get_packs();
$payload = array();
foreach ( $packs as $pack ) {
$payload[ $pack['slug'] ] = array(
'name' => $pack['name'],
'icon' => $this->pack_icon( $pack ),
'category' => $this->group_name( $pack ),
'snippets' => wp_list_pluck( $pack['snippets'], 'title' ),
);
}
?>
<script type="application/json" id="wpcode-packs-payload"><?php
echo wp_json_encode(
array(
'packs' => $payload,
'nonce' => wp_create_nonce( 'wpcode_packs' ),
'i18n' => array(
'install_title' => __( 'Install %s?', 'insert-headers-and-footers' ),
'installing_title' => __( 'Installing %s…', 'insert-headers-and-footers' ),
'installed_title' => __( '%s installed', 'insert-headers-and-footers' ),
'snippets_subtitle' => __( '%1$d snippets · %2$s · Free in Lite', 'insert-headers-and-footers' ),
'confirm_lead' => __( 'These snippets will be added to your library and activated. You can toggle or remove any of them after installation.', 'insert-headers-and-footers' ),
'creating_snippets' => __( 'Creating snippets in your library…', 'insert-headers-and-footers' ),
'success_heading' => __( 'All %d snippets activated', 'insert-headers-and-footers' ),
'success_body' => __( "They're live now. Edit any of them in your library, or open the pack dashboard to toggle individual snippets.", 'insert-headers-and-footers' ),
/* translators: %1$d: number activated, %2$d: total in the pack. */
'success_heading_partial' => __( '%1$d of %2$d snippets activated', 'insert-headers-and-footers' ),
'success_body_partial' => __( 'Some snippets need attention — open the pack dashboard to review the ones that could not be activated.', 'insert-headers-and-footers' ),
'cancel' => __( 'Cancel', 'insert-headers-and-footers' ),
'install_button' => __( 'Install pack', 'insert-headers-and-footers' ),
'installing_button' => __( 'Installing…', 'insert-headers-and-footers' ),
'back_to_packs' => __( 'Back to packs', 'insert-headers-and-footers' ),
'open_dashboard' => __( 'Open pack dashboard', 'insert-headers-and-footers' ),
'confirm_remove' => __( 'Remove %1$s? This will delete all %2$d snippets it created.', 'insert-headers-and-footers' ),
'remove_title' => __( 'Remove pack?', 'insert-headers-and-footers' ),
'remove_confirm_button' => __( 'Remove pack', 'insert-headers-and-footers' ),
'activation_refused' => __( "This snippet couldn't be activated — it may contain an error. Edit the snippet to review it.", 'insert-headers-and-footers' ),
),
)
);
?></script>
<template id="wpcode-packs-install-modal">
<div class="wpcode-rmodal-backdrop">
<div class="wpcode-rmodal">
<div class="wpcode-rmodal-head">
<h3 class="js-wpcode-rmodal-title"></h3>
<div class="sub js-wpcode-rmodal-sub"><span></span></div>
</div>
<div class="wpcode-rmodal-body">
<p class="js-wpcode-rmodal-lead"></p>
<ul class="wpcode-checklist"></ul>
<div class="wpcode-progress-track" hidden>
<div class="wpcode-progress-fill"></div>
</div>
<div class="wpcode-progress-label" hidden>
<span class="js-wpcode-progress-text"></span>
<span class="js-wpcode-progress-percent"></span>
</div>
<div class="wpcode-success-state" hidden>
<svg xmlns="http://www.w3.org/2000/svg" class="wpcode-icon wpcode-icon-checkmark path circle" width="64" height="64" viewBox="0 0 130.2 130.2" aria-hidden="true">
<circle fill="none" stroke="#73AF55" stroke-width="6" cx="65.1" cy="65.1" r="62.1"></circle>
<polyline fill="none" stroke="#73AF55" stroke-width="6" stroke-linecap="round" stroke-miterlimit="10" points="100.2,40.2 51.5,88.8 29.8,67.5 "></polyline>
</svg>
<h4 class="js-wpcode-success-heading"></h4>
<p class="js-wpcode-success-body"></p>
</div>
</div>
<div class="wpcode-rmodal-foot">
<button type="button" class="wpcode-button wpcode-button-secondary js-wpcode-rmodal-cancel"></button>
<button type="button" class="wpcode-button js-wpcode-rmodal-primary"><span></span></button>
</div>
</div>
</div>
</template>
<?php
}
/**
* The pack's group label, as authored on the library (e.g. "Performance").
* Used as the badge and as the sidebar grouping label.
*
* @param array $pack Pack data.
*
* @return string
*/
protected function group_name( $pack ) {
$group = isset( $pack['group'] ) ? trim( (string) $pack['group'] ) : '';
return '' !== $group ? $group : __( 'Other', 'insert-headers-and-footers' );
}
/**
* A slug form of the group label, used for the sidebar filter buttons and
* the card's data-categories attribute.
*
* @param array $pack Pack data.
*
* @return string
*/
protected function group_slug( $pack ) {
return sanitize_title( $this->group_name( $pack ) );
}
/**
* The dashicon to render for a pack. Driven entirely by the library's
* pack_icon field; a leading "dashicons-" is added if the editor left it
* off, and a neutral default is used when no icon is set.
*
* @param array $pack Pack data.
*
* @return string
*/
protected function pack_icon( $pack ) {
$icon = isset( $pack['icon'] ) ? trim( (string) $pack['icon'] ) : '';
if ( '' === $icon ) {
return self::DEFAULT_ICON;
}
if ( 0 !== strpos( $icon, 'dashicons-' ) ) {
$icon = 'dashicons-' . $icon;
}
return $icon;
}
}
@@ -0,0 +1,157 @@
<?php
/**
* Preview Frame Handler for Live CSS Preview.
*
* This class handles the front-end preview mode when viewing a snippet in the live preview.
*
* @package WPCode
*/
/**
* Class WPCode_Preview_Frame
*/
class WPCode_Preview_Frame {
/**
* The snippet ID being previewed.
*
* @var int
*/
private $snippet_id;
/**
* Constructor.
*/
public function __construct() {
add_action( 'template_redirect', array( $this, 'maybe_load_preview' ) );
}
/**
* Check if we're in preview mode and load the necessary scripts.
*
* @return void
*/
public function maybe_load_preview() {
if ( ! is_user_logged_in() ) {
return;
}
// Check if the current user can edit snippets.
if ( ! current_user_can( 'wpcode_edit_snippets' ) ) { // phpcs:ignore
return;
}
// phpcs:disable WordPress.Security.NonceVerification.Recommended
if ( ! isset( $_GET['wpcode_preview'] ) || '1' !== $_GET['wpcode_preview'] ) {
return;
}
if ( ! isset( $_GET['snippet_id'] ) ) {
return;
}
// phpcs:enable WordPress.Security.NonceVerification.Recommended
$this->snippet_id = absint( $_GET['snippet_id'] ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended
// Hide the WP admin bar in preview iframe.
add_filter( 'show_admin_bar', '__return_false' );
// During preview, ensure CSS/SCSS for this snippet is output inline (even if normally loaded as file).
$force_inline_callback = function ( $code, $snippet ) {
if ( $snippet && method_exists( $snippet, 'get_id' ) && $snippet->get_id() === $this->snippet_id ) {
$snippet->load_as_file = false;
}
return $code;
};
add_filter( 'wpcode_snippet_output_css', $force_inline_callback, 1, 2 );
add_filter( 'wpcode_snippet_output_scss', $force_inline_callback, 1, 2 );
// Ensure the snippet is considered by the auto-insert flow during preview without hardcoding locations.
add_filter( 'wpcode_get_snippets_for_location', array( $this, 'maybe_force_include_snippet' ), 10, 2 );
// Enqueue the preview iframe script and then localize data for it.
add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_preview_script' ), 10 );
add_action( 'wp_enqueue_scripts', array( $this, 'localize_preview_data' ), 11 );
}
/**
* Enqueue the preview iframe script so it can communicate via postMessage.
*
* @return void
*/
public function enqueue_preview_script() {
$handle = 'wpcode-preview-frame';
$src = WPCODE_PLUGIN_URL . 'build/css-live-preview.js';
$deps = array( 'jquery' );
$version = defined( 'WPCODE_VERSION' ) ? WPCODE_VERSION : false;
$in_footer = true;
wp_register_script( $handle, $src, $deps, $version, $in_footer );
wp_enqueue_script( $handle );
}
/**
* Localize preview data for the JavaScript.
*
* @return void
*/
public function localize_preview_data() {
$snippet = wpcode_get_snippet( $this->snippet_id );
$code_type = $snippet ? $snippet->get_code_type() : 'css';
wp_localize_script(
'wpcode-preview-frame',
'wpcodePreviewFrame',
array(
'adminUrl' => admin_url(),
'snippetId' => $this->snippet_id,
'codeType' => $code_type,
)
);
}
/**
* During preview, force-include the current CSS snippet into its configured location
* while honoring conditional logic and avoiding duplicates.
*
* @param WPCode_Snippet[] $snippets The snippets already queued for the location.
* @param string $location The location slug currently being processed.
*
* @return WPCode_Snippet[]
*/
public function maybe_force_include_snippet( $snippets, $location ) {
if ( empty( $this->snippet_id ) ) {
return $snippets;
}
$snippet = wpcode_get_snippet( $this->snippet_id );
if ( ! $snippet || ! in_array( $snippet->get_code_type(), array( 'css', 'scss' ), true ) ) {
return $snippets;
}
// Only add to the snippet's configured location.
if ( $snippet->get_location() !== $location ) {
return $snippets;
}
// Avoid duplicates if already present (e.g., active snippet).
foreach ( $snippets as $s ) {
if ( $s->get_id() === $snippet->get_id() ) {
return $snippets;
}
}
// Honor conditional logic. If not met on this page, don't include.
if ( $snippet->conditional_rules_enabled() && ! wpcode()->conditional_logic->are_snippet_rules_met( $snippet ) ) {
return $snippets;
}
$snippets[] = $snippet;
return $snippets;
}
}
new WPCode_Preview_Frame();
@@ -0,0 +1,213 @@
<?php
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Ask for some love.
*
*
*/
class WPCode_Review {
/**
* Primary class constructor.
*
*
*/
public function __construct() {
// Admin notice requesting review.
add_action( 'admin_init', array( $this, 'review_request' ) );
// Admin footer text.
add_filter( 'admin_footer_text', array( $this, 'admin_footer' ), 1, 2 );
}
/**
* Add admin notices as needed for reviews.
*/
public function review_request() {
// Only consider showing the review request to admin users.
if ( ! is_super_admin() ) {
return;
}
// Don't show notice to headers & footers mode users.
if ( wpcode()->settings->get_option( 'headers_footers_mode' ) ) {
return;
}
// If this is a multisite and the user is a super admin let's see if they already dismissed this on other sites.
if ( is_multisite() && is_super_admin() ) {
$dismissed = get_user_meta( get_current_user_id(), 'wpcode_dismissed_review_request', true );
if ( ! empty( $dismissed ) ) {
return;
}
}
// Verify that we can do a check for reviews.
$notices = get_option( 'wpcode_admin_notices', array() );
$time = time();
$load = false;
if ( empty( $notices['review_request'] ) ) {
$notices['review_request'] = array(
'time' => $time,
'dismissed' => false,
);
update_option( 'wpcode_admin_notices', $notices );
return;
}
// Check if it has been dismissed or not.
if (
( isset( $notices['review_request']['dismissed'] ) &&
! $notices['review_request']['dismissed'] ) &&
(
isset( $notices['review_request']['time'] ) &&
( ( $notices['review_request']['time'] + DAY_IN_SECONDS ) <= $time )
)
) {
$load = true;
}
// If we cannot load, return early.
if ( ! $load ) {
return;
}
$this->review();
}
/**
* Maybe show Lite review request.
*/
public function review() {
// Fetch when plugin was initially installed.
$activated = get_option( 'ihaf_activated', array() );
if ( ! empty( $activated['wpcode'] ) ) {
// Only continue if plugin has been installed for at least 14 days.
if ( ( $activated['wpcode'] + ( DAY_IN_SECONDS * 14 ) ) > time() ) {
return;
}
} else {
$activated['wpcode'] = time();
update_option( 'ihaf_activated', $activated );
return;
}
// Only proceed with displaying if the user is using an active snippet.
$snippet_count = wp_count_posts( 'wpcode' );
if ( empty( $snippet_count->publish ) ) {
return;
}
$feedback_url = add_query_arg( array(
'siteurl' => untrailingslashit( home_url() ),
'plugin' => class_exists( 'WPCode_Premium') ? 'pro' : 'lite',
'version' => WPCODE_VERSION,
), 'https://www.wpcode.com/plugin-feedback/' );
$feedback_url = wpcode_utm_url( $feedback_url, 'review-notice', 'feedback' );
ob_start();
// We have a candidate! Output a review message.
?>
<div class="wpcode-review-step wpcode-review-step-1">
<p><?php esc_html_e( 'Are you enjoying WPCode?', 'insert-headers-and-footers' ); ?></p>
<p>
<a href="#" class="wpcode-review-switch-step" data-step="3"><?php esc_html_e( 'Yes', 'insert-headers-and-footers' ); ?></a>&nbsp;&bull;&nbsp;<a href="#" class="wpcode-review-switch-step" data-step="2"><?php esc_html_e( 'Not Really', 'insert-headers-and-footers' ); ?></a>
</p>
</div>
<div class="wpcode-review-step wpcode-review-step-2" style="display: none">
<p><?php esc_html_e( 'We\'re sorry to hear you aren\'t enjoying WPCode. We would love a chance to improve. Could you take a minute and let us know what we can do better?', 'insert-headers-and-footers' ); ?></p>
<p>
<a href="<?php echo esc_url( $feedback_url ); ?>" class="wpcode-notice-dismiss" target="_blank"><?php esc_html_e( 'Give Feedback', 'insert-headers-and-footers' ); ?></a>&nbsp;&bull;&nbsp;<a href="#" class="wpcode-notice-dismiss" rel="noopener noreferrer"><?php esc_html_e( 'No thanks', 'insert-headers-and-footers' ); ?></a>
</p>
</div>
<div class="wpcode-review-step wpcode-review-step-3" style="display: none">
<p><?php esc_html_e( 'That\'s awesome! Could you please do us a BIG favor and give it a 5-star rating on WordPress to help us spread the word and boost our motivation?', 'insert-headers-and-footers' ); ?></p>
<p>
<a href="https://wordpress.org/support/plugin/insert-headers-and-footers/reviews/?filter=5#new-post" class="wpcode-notice-dismiss wpcode-review-out" target="_blank" rel="noopener noreferrer"><?php esc_html_e( 'Give Feedback', 'insert-headers-and-footers' ); ?></a>&nbsp;&bull;&nbsp;<a href="#" class="wpcode-notice-dismiss" rel="noopener noreferrer"><?php esc_html_e( 'No thanks', 'insert-headers-and-footers' ); ?></a><br>
</p>
</div>
<script type="text/javascript">
jQuery(document).ready(function ($) {
$(document).on('click', '.wpcode-review-switch-step', function (e) {
e.preventDefault();
var target = $(this).attr('data-step');
if (target) {
var notice = $(this).closest('.wpcode-review-notice');
var review_step = notice.find('.wpcode-review-step-' + target);
if (review_step.length > 0) {
notice.find('.wpcode-review-step:visible').fadeOut(function () {
review_step.fadeIn();
});
}
}
})
});
</script>
<?php
WPCode_Notice::info(
ob_get_clean(),
array(
'dismiss' => WPCode_Notice::DISMISS_GLOBAL,
'slug' => 'review_request',
'autop' => false,
'class' => 'wpcode-review-notice',
)
);
}
/**
* When user is on a WPCode related admin page, display footer text
* that graciously asks them to rate us.
*
* @param string $text Footer text.
*
* @return string
*
*
*/
public function admin_footer( $text ) {
global $current_screen;
if ( ! empty( $current_screen->id ) && strpos( $current_screen->id, 'wpcode' ) !== false ) {
$url = 'https://wordpress.org/support/plugin/insert-headers-and-footers/reviews/?filter=5#new-post';
$text = sprintf(
wp_kses( /* translators: $1$s - WPCode plugin name; $2$s - WP.org review link; $3$s - WP.org review link. */
__( 'Please rate %1$s <a href="%2$s" target="_blank" rel="noopener noreferrer">&#9733;&#9733;&#9733;&#9733;&#9733;</a> on <a href="%3$s" target="_blank" rel="noopener">WordPress.org</a> to help us spread the word. Thank you from the WPCode team!', 'insert-headers-and-footers' ),
array(
'a' => array(
'href' => array(),
'target' => array(),
'rel' => array(),
),
)
),
'<strong>WPCode</strong>',
$url,
$url
);
}
return $text;
}
}
new WPCode_Review();
@@ -0,0 +1,130 @@
<?php
/**
* Legacy Skin class used for older versions of WordPress.
*
* @since 2.0.7
*
* @package WPCode
*/
// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
class WPCode_Skin extends WP_Upgrader_Skin {
/**
* Primary class constructor.
*
* @param array $args Empty array of args (we will use defaults).
*
* @since 2.0.7
*
*/
public function __construct( $args = array() ) {
parent::__construct();
}
/**
* Set the upgrader object and store it as a property in the parent class.
*
* @param object $upgrader The upgrader object (passed by reference).
*
* @since 2.0.7
*
*/
public function set_upgrader( &$upgrader ) {
if ( is_object( $upgrader ) ) {
$this->upgrader =& $upgrader;
}
}
/**
* Set the upgrader result and store it as a property in the parent class.
*
* @param object $result The result of the install process.
*
* @since 2.0.7
*
*/
public function set_result( $result ) {
$this->result = $result;
}
/**
* Empty out the header of its HTML content and only check to see if it has
* been performed or not.
*
* @since 2.0.7
*/
public function header() {
}
/**
* Empty out the footer of its HTML contents.
*
* @since 2.0.7
*/
function footer() {
}
/**
* Instead of outputting HTML for errors, json_encode the errors and send them
* back to the Ajax script for processing.
*
* @param array $errors Array of errors with the install process.
*
* @since 2.0.7
*
*/
function error( $errors ) {
if ( ! empty( $errors ) ) {
$error_message = sprintf(
// Translators: Support link tag starts with url and Support link tag ends.
esc_html__( 'There was an error installing the addon. Please try again. If you are still having issues, please %1$scontact our support%2$s team.', 'insert-headers-and-footers' ),
'<a target="_blank" href="' . wpcode_utm_url( 'https://library.wpcode.com/account/support/', 'notice', 'error-installing-addons' ) . '">',
'</a>'
);
if ( is_wp_error( $errors ) ) {
/**
* @var WP_Error $errors
*/
$message = $errors->get_error_message();
if ( ! empty( $message ) ) {
$error_message = sprintf(
// Translators: The name of the addon that can't be installed, Support link tag starts with url and Support link tag ends.
esc_html__( 'There was an error installing the addon, %1$s. Please try again. If you are still having issues, please %2$scontact our support%3$s team. ', 'insert-headers-and-footers' ),
esc_html( $message ),
'<a target="_blank" href="' . wpcode_utm_url( 'https://library.wpcode.com/account/support/', 'notice', 'error-installing-addons' ) . '">',
'</a>'
);
}
}
wp_send_json( array( 'error' => $error_message ) );
}
}
/**
* Empty out the feedback method to prevent outputting HTML strings as the install
* is progressing.
*
* @param string $string The feedback string.
*
* @since 2.0.7
*
*/
function feedback( $string ) {
}
}
@@ -0,0 +1,132 @@
<?php
/**
* Skin class.
*
* @since 2.0.7
*
* @package WPCode
*/
// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
class WPCode_Skin extends WP_Upgrader_Skin {
/**
* Primary class constructor.
*
* @param array $args Empty array of args (we will use defaults).
*
* @since 2.0.7
*
*/
public function __construct( $args = array() ) {
parent::__construct();
}
/**
* Set the upgrader object and store it as a property in the parent class.
*
* @param object $upgrader The upgrader object (passed by reference).
*
* @since 2.0.7
*
*/
public function set_upgrader( &$upgrader ) {
if ( is_object( $upgrader ) ) {
$this->upgrader =& $upgrader;
}
}
/**
* Set the upgrader result and store it as a property in the parent class.
*
* @param object $result The result of the install process.
*
* @since 2.0.7
*
*/
public function set_result( $result ) {
$this->result = $result;
}
/**
* Empty out the header of its HTML content and only check to see if it has
* been performed or not.
*
* @since 2.0.7
*/
public function header() {
}
/**
* Empty out the footer of its HTML contents.
*
* @since 2.0.7
*/
function footer() {
}
/**
* Instead of outputting HTML for errors, json_encode the errors and send them
* back to the Ajax script for processing.
*
* @param array $errors Array of errors with the install process.
*
* @since 2.0.7
*
*/
function error( $errors ) {
if ( ! empty( $errors ) ) {
$error_message = sprintf(
// Translators: Support link tag starts with url and Support link tag ends.
esc_html__( 'There was an error installing the addon. Please try again. If you are still having issues, please %1$scontact our support%2$s team.', 'insert-headers-and-footers' ),
'<a target="_blank" href="' . wpcode_utm_url( 'https://library.wpcode.com/account/support/', 'notice', 'error-installing-addons' ) . '">',
'</a>'
);
if ( is_wp_error( $errors ) ) {
/**
* @var WP_Error $errors
*/
$message = $errors->get_error_message();
if ( ! empty( $message ) ) {
// Translators: The name of the addon that can't be installed, Support link tag starts with url and Support link tag ends.
$error_message = sprintf(
// Translators: The name of the addon that can't be installed, Support link tag starts with url and Support link tag ends.
esc_html__( 'There was an error installing the addon, %1$s. Please try again. If you are still having issues, please %2$scontact our support%3$s team. ', 'insert-headers-and-footers' ),
esc_html( $message ),
'<a target="_blank" href="' . wpcode_utm_url( 'https://library.wpcode.com/account/support/', 'notice', 'error-installing-addons' ) . '">',
'</a>'
);
}
}
wp_send_json( array( 'error' => $error_message ) );
}
}
/**
* Empty out the feedback method to prevent outputting HTML strings as the install
* is progressing.
*
* @param string $string The feedback string.
*
* @since 2.0.7
*
*/
function feedback( $string, ...$args ) {
}
}
@@ -0,0 +1,397 @@
<?php
/**
* Suggest other relevant free plugins to our users.
*
* @package WPCode
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Class WPCode_Suggested_Plugins
*/
class WPCode_Suggested_Plugins {
/**
* WPCode_Suggested_Plugins constructor.
*/
public function __construct() {
$this->hooks();
}
/**
* Hooks for the class.
*/
public function hooks() {
add_action( 'wp_ajax_wpcode_install_plugin', array( $this, 'install_plugin' ) );
// Maybe suggest plugins to the current user.
add_action( 'admin_init', array( $this, 'maybe_suggest_plugins' ) );
}
/**
* Get all plugins that we suggest.
*
* @return array
*/
public static function all_plugins() {
$plugins = array(
'wpconsent' => array(
'name' => 'WPConsent',
'description' => esc_html__( 'Custom cookie banner with automatic script blocking, advanced scanner and more.', 'insert-headers-and-footers' ),
'url' => 'https://downloads.wordpress.org/plugin/wpconsent-cookies-banner-privacy-suite.zip',
'slug' => 'wpconsent-cookies-banner-privacy-suite/wpconsent.php',
'pro_slug' => 'wpconsent-premium/wpconsent-premium.php',
'icon' => 'icon-wpconsent.png',
'suggested' => true,
'library' => false,
),
'duplicator' => array(
'name' => 'Duplicator',
'description' => esc_html__( 'Easy, Fast and Secure WordPress and Website Migration.', 'insert-headers-and-footers' ),
'url' => 'https://downloads.wordpress.org/plugin/duplicator.zip',
'slug' => 'duplicator/duplicator.php',
'pro_slug' => 'duplicator-pro/duplicator-pro.php',
'icon' => 'icon-duplicator.png',
'suggested' => true,
'library' => false,
),
'search-replace-wpcode' => array(
'name' => 'Search & Replace Everything',
'description' => esc_html__( 'Replace text across your database or media uploads in a single plugin.', 'insert-headers-and-footers' ),
'url' => 'https://downloads.wordpress.org/plugin/search-replace-wpcode.zip',
'slug' => 'search-replace-wpcode/wsrw.php',
'pro_slug' => 'search-replace-wpcode-pro/wsrw-premium.php',
'icon' => 'icon-search-replace-wpcode.png',
'suggested' => true,
'library' => false,
),
'wp-mail-smtp' => array(
'name' => 'WP Mail SMTP',
'description' => esc_html__( 'Making Email Deliverability Easy for WordPress', 'insert-headers-and-footers' ),
'url' => 'https://downloads.wordpress.org/plugin/wp-mail-smtp.zip',
'slug' => 'wp-mail-smtp/wp_mail_smtp.php',
'pro_slug' => 'wp-mail-smtp-pro/wp_mail_smtp_pro.php',
'icon' => 'icon-wp-mail-smtp.png',
'suggested' => true,
'library' => false,
),
'all-in-one-seo-pack' => array(
'name' => 'All in One SEO Pack',
'description' => esc_html__( 'Powerful SEO Plugin to Boost SEO Rankings & Increase Traffic.', 'insert-headers-and-footers' ),
'url' => 'https://downloads.wordpress.org/plugin/all-in-one-seo-pack.zip',
'slug' => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
'pro_slug' => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
'icon' => 'icon-all-in-one-seo-pack.png',
'suggested' => true,
'library' => true,
),
'wpforms' => array(
'name' => 'WPForms',
'description' => esc_html__( 'The Best Drag & Drop WordPress Form Builder.', 'insert-headers-and-footers' ),
'url' => 'https://downloads.wordpress.org/plugin/wpforms-lite.zip',
'slug' => 'wpforms-lite/wpforms.php',
'pro_slug' => 'wpforms/wpforms.php',
'icon' => 'icon-wpforms.png',
'suggested' => true,
'library' => true,
),
'uncanny-automator' => array(
'name' => 'Uncanny Automator',
'description' => esc_html__( 'Connect your WordPress plugins together and create automated workflows.', 'insert-headers-and-footers' ),
'url' => 'https://downloads.wordpress.org/plugin/uncanny-automator.zip',
'slug' => 'uncanny-automator/uncanny-automator.php',
'pro_slug' => 'uncanny-automator-pro/uncanny-automator-pro.php',
'icon' => 'icon-uncanny-automator.png',
'suggested' => true,
'library' => false,
),
'easy-digital-downloads' => array(
'name' => 'Easy Digital Downloads',
'description' => esc_html__( 'The easiest way to sell digital products with WordPress.', 'insert-headers-and-footers' ),
'url' => 'https://downloads.wordpress.org/plugin/easy-digital-downloads.zip',
'slug' => 'easy-digital-downloads/easy-digital-downloads.php',
'pro_slug' => 'easy-digital-downloads-pro/easy-digital-downloads.php',
'icon' => 'icon-edd.png',
'suggested' => false,
'library' => true,
),
'charitable' => array(
'name' => 'Charitable',
'description' => esc_html__( 'Raise more money for your cause with the most powerful WordPress donation and fundraising plugin.', 'insert-headers-and-footers' ),
'url' => 'https://downloads.wordpress.org/plugin/charitable.zip',
'slug' => 'charitable/charitable.php',
'pro_slug' => 'charitable/charitable.php',
'icon' => 'icon-charitable.jpg',
'suggested' => false,
'library' => true,
),
'wp-simple-pay' => array(
'name' => 'WP Simple Pay',
'description' => esc_html__( 'Start accepting one-time and recurring payments on your WordPress site without setting up a shopping cart.', 'insert-headers-and-footers' ),
'url' => 'https://downloads.wordpress.org/plugin/stripe.zip',
'slug' => 'stripe/stripe-checkout.php',
'pro_slug' => 'wp-simple-pay-pro-3/simple-pay.php',
'icon' => 'icon-wp-simple-pay.png',
'suggested' => false,
'library' => true,
),
);
return $plugins;
}
/**
* Get a list of plugins to suggest.
*
* @param int $count How many plugins to suggest.
*
* @return array
*/
public function get_suggested_plugins( $count = 3 ) {
$plugins = self::all_plugins();
// Let's loop through all the plugins and see which are installed already and only suggest the ones that are not. We should check for the pro version for each one.
$suggested_plugins = array();
foreach ( $plugins as $slug => $plugin ) {
if ( $count <= count( $suggested_plugins ) ) {
break;
}
if ( ! $plugin['suggested'] ) {
continue;
}
if ( ! $this->is_plugin_installed( $plugin['slug'] ) && ! $this->is_plugin_installed( $plugin['pro_slug'] ) ) {
$suggested_plugins[ $slug ] = $plugin;
}
}
return $suggested_plugins;
}
/**
* Get a list of plugins that have a library integration so we can show them in the plugin snippets page.
*
* @return array
*/
public static function get_library_plugins() {
$plugins = self::all_plugins();
// Filter out just the plugins that have "library" true.
return array_filter(
$plugins,
function ( $plugin ) {
return $plugin['library'];
}
);
}
/**
* Check if a plugin is installed.
*
* @param string $slug The plugin slug.
*
* @return bool
*/
public function is_plugin_installed( $slug ) {
$installed_plugins = array_keys( get_plugins() );
return in_array( $slug, $installed_plugins, true );
}
/**
* AJAX callback to install a plugin.
*
* @return void
*/
public function install_plugin() {
check_ajax_referer( 'wpcode_admin' );
// If the current user can't install plugins they should not be trying this.
if ( ! current_user_can( 'install_plugins' ) ) {
wp_send_json_error();
}
require_once ABSPATH . 'wp-admin/includes/file.php';
require_once ABSPATH . 'wp-admin/includes/template.php';
require_once ABSPATH . 'wp-admin/includes/class-wp-screen.php';
require_once ABSPATH . 'wp-admin/includes/screen.php';
$allowed_plugins = self::all_plugins();
$slug = isset( $_POST['slug'] ) ? sanitize_text_field( wp_unslash( $_POST['slug'] ) ) : '';
if ( ! array_key_exists( $slug, $allowed_plugins ) ) {
wp_send_json_error();
}
$plugin_info = $allowed_plugins[ $slug ];
// Set the current screen to avoid undefined notices.
set_current_screen( 'toplevel_page_wpcode' );
// Do not allow WordPress to search/download translations, as this will break JS output.
remove_action( 'upgrader_process_complete', array( 'Language_Pack_Upgrader', 'async_upgrade' ), 20 );
// Let's check if the plugin is already installed.
if ( is_plugin_active( $plugin_info['slug'] ) ) {
wp_send_json_success(
array(
'msg' => esc_html__( 'Plugin already installed and activated.', 'insert-headers-and-footers' ),
)
);
}
// Check if the Pro plugin is available first.
if ( $this->is_plugin_installed( $plugin_info['pro_slug'] ) ) {
activate_plugin( $plugin_info['pro_slug'] );
wp_send_json_success(
array(
'msg' => esc_html__( 'Plugin activated.', 'insert-headers-and-footers' ),
)
);
}
if ( $this->is_plugin_installed( $plugin_info['slug'] ) ) {
activate_plugin( $plugin_info['slug'] );
wp_send_json_success(
array(
'msg' => esc_html__( 'Plugin activated.', 'insert-headers-and-footers' ),
)
);
}
wpcode_require_upgrader();
// Create the plugin upgrader with our custom skin.
$installer = new Plugin_Upgrader( new WPCode_Skin() );
$installer->install( $allowed_plugins[ $slug ]['url'] );
// Flush the cache and return the newly installed plugin basename.
wp_cache_flush();
$plugin_basename = $installer->plugin_info();
if ( ! $plugin_basename ) {
wp_send_json_error();
}
// Activate the plugin silently.
$activated = activate_plugin( $plugin_basename );
if ( is_wp_error( $activated ) ) {
wp_send_json_error();
}
wp_send_json_success(
array(
'message' => esc_html__( 'Plugin installed and activated.', 'insert-headers-and-footers' ),
)
);
}
/**
* Maybe suggest plugins to the current user.
*/
public function maybe_suggest_plugins() {
if ( ! is_super_admin() || ! current_user_can( 'install_plugins' ) ) {
return;
}
// Verify that we can do a check to suggest plugins.
$notices = get_option( 'wpcode_admin_notices', array() );
$time = time();
$load = false;
if ( empty( $notices['suggest_plugins'] ) ) {
$notices['suggest_plugins'] = array(
'time' => $time,
'dismissed' => false,
);
update_option( 'wpcode_admin_notices', $notices );
return;
}
// Check if it has been dismissed or not.
if (
( isset( $notices['suggest_plugins']['dismissed'] ) &&
! $notices['suggest_plugins']['dismissed'] ) &&
(
isset( $notices['suggest_plugins']['time'] ) &&
( ( $notices['suggest_plugins']['time'] + DAY_IN_SECONDS ) <= $time )
)
) {
$load = true;
}
// If we cannot load, return early.
if ( ! $load ) {
return;
}
add_action( 'admin_head', array( $this, 'suggest_plugins' ) );
}
/**
* Suggest plugins to the current user.
*/
public function suggest_plugins() {
// Let's make sure we are on a wpcode screen using get_current_screen.
$screen = get_current_screen();
if ( ! $screen || 'toplevel_page_wpcode' !== $screen->id ) {
return;
}
// Fetch when plugin was initially installed.
$activated = get_option( 'ihaf_activated', array() );
if ( ! empty( $activated['wpcode'] ) ) {
// Only continue if plugin has been installed for at least 21 days.
if ( ( $activated['wpcode'] + ( DAY_IN_SECONDS * 21 ) ) > time() ) {
return;
}
} else {
$activated['wpcode'] = time();
update_option( 'ihaf_activated', $activated );
return;
}
$suggested_plugins = $this->get_suggested_plugins();
if ( empty( $suggested_plugins ) ) {
return;
}
ob_start();
?>
<p class="wpcode-suggestions-title"><?php esc_html_e( 'Enjoying WPCode? Check out some of our other top-rated FREE plugins:', 'insert-headers-and-footers' ); ?></p>
<div class="wpcode-plugin-suggestions">
<?php foreach ( $suggested_plugins as $slug => $plugin ) { ?>
<div class="wpcode-plugin-suggestion-plugin">
<div class="wpcode-plugin-suggestion-plugin-icon">
<img width="72" src="<?php echo esc_url( add_query_arg( 'v', WPCODE_VERSION, WPCODE_PLUGIN_URL . 'admin/images/' . $plugin['icon'] ) ); ?>" alt="<?php echo esc_attr( $plugin['name'] ); // phpcs:ignore PluginCheck.CodeAnalysis.ImageFunctions.NonEnqueuedImage ?>"/>
</div>
<div class="wpcode-plugin-suggesion-plugin-text">
<h3><?php echo esc_html( $plugin['name'] ); ?></h3>
<p><?php echo esc_html( $plugin['description'] ); ?></p>
<button type=" button" class="wpcode-button wpcode-button-secondary wpcode-button-install-plugin" data-slug="<?php echo esc_attr( $slug ); ?>"><?php esc_html_e( 'Install Plugin', 'insert-headers-and-footers' ); ?></button>
</div>
</div>
<?php } ?>
</div>
<?php
WPCode_Notice::info(
ob_get_clean(),
array(
'dismiss' => WPCode_Notice::DISMISS_GLOBAL,
'slug' => 'suggest_plugins',
'autop' => false,
'class' => 'wpcode-suggest-plugins-notice',
)
);
}
}
@@ -0,0 +1,285 @@
<?php
/**
* Class WPCode_Usage_Tracking - The abstract class for the usage tracking.
*
* @package WPCode
*/
/**
* The abstract class for the usage tracking.
*/
abstract class WPCode_Usage_Tracking {
/**
* Returns the current plugin version type ("lite" or "pro").
*
* @return string The version type.
* @since 2.0.10
*/
abstract public function get_type();
/**
* Is the usage tracking enabled?
*
* @return bool
* @since 2.0.10
*/
abstract public function is_enabled();
/**
* Usage Tracking endpoint.
*
* @since 2.0.10
*
* @var string
*/
private $url = 'https://wpcodeusage.com/v1/track';
/**
* Option name to store the timestamp of the last run.
*
* @since 2.0.10
*/
const LAST_RUN = 'wpcode_send_usage_last_run';
/**
* Class Constructor.
*
* @since 2.0.10
*/
public function __construct() {
add_action( 'init', array( $this, 'init' ), 2 );
add_action( 'wpcode_usage_tracking_cron', array( $this, 'process' ) );
add_action( 'wpcode_library_api_auth_connected', array( $this, 'usage_tracking_auth' ) );
}
/**
* Initiate the usage tracking cron.
*
* @return void
* @since 2.0.10
*/
public function init() {
if ( ! wp_next_scheduled( 'wpcode_usage_tracking_cron' ) ) {
$tracking = array();
$tracking['day'] = wp_rand( 0, 6 );
$tracking['hour'] = wp_rand( 0, 23 );
$tracking['minute'] = wp_rand( 0, 59 );
$tracking['second'] = wp_rand( 0, 59 );
$tracking['offset'] = ( $tracking['day'] * DAY_IN_SECONDS ) + ( $tracking['hour'] * HOUR_IN_SECONDS ) + ( $tracking['minute'] * MINUTE_IN_SECONDS ) + $tracking['second'];
$tracking['initsend'] = strtotime( 'next sunday' ) + $tracking['offset'];
wp_schedule_event( $tracking['initsend'], 'weekly', 'wpcode_usage_tracking_cron' );
update_option( 'wpcode_usage_tracking_config', $tracking, false );
}
}
/**
* Processes the usage tracking.
*
* @return void
* @since 2.0.10
*/
public function process() {
if ( ! $this->is_enabled() ) {
return;
}
$last_run = get_option( self::LAST_RUN );
// Make sure we do not run it more than once a day.
if ( false !== $last_run && ( time() - $last_run ) < DAY_IN_SECONDS ) {
return;
}
wp_remote_post(
$this->get_url(),
array(
'timeout' => 10,
'headers' => array(
'Content-Type' => 'application/json; charset=utf-8',
),
'user-agent' => $this->get_user_agent(),
'body' => wp_json_encode( $this->get_data() ),
)
);
// If we have completed successfully, recheck in 1 week.
update_option( self::LAST_RUN, time() );
}
/**
* Gets the URL for the notifications api.
*
* @return string The URL to use for the api requests.
* @since 2.0.10
*/
private function get_url() {
if ( defined( 'WPCODE_USAGE_TRACKING_URL' ) ) {
return WPCODE_USAGE_TRACKING_URL;
}
return $this->url;
}
/**
* Rtrieve the data to send to the usage tracking api.
*
* @return array
* @since 2.0.10
*/
public function get_data() {
global $wpdb;
$theme_data = wp_get_theme();
$activated = get_option( 'ihaf_activated', array() );
$installed_date = isset( $activated['wpcode'] ) ? $activated['wpcode'] : null;
$data = array(
// Generic data (environment).
'url' => home_url(),
'php_version' => PHP_MAJOR_VERSION . '.' . PHP_MINOR_VERSION,
'wp_version' => get_bloginfo( 'version' ),
'mysql_version' => $wpdb->db_version(),
'server_version' => isset( $_SERVER['SERVER_SOFTWARE'] ) ? sanitize_text_field( wp_unslash( $_SERVER['SERVER_SOFTWARE'] ) ) : '',
'is_ssl' => is_ssl(),
'is_multisite' => is_multisite(),
'sites_count' => function_exists( 'get_blog_count' ) ? (int) get_blog_count() : 1,
'active_plugins' => $this->get_active_plugins(),
'theme_name' => $theme_data->name,
'theme_version' => $theme_data->version,
'user_count' => function_exists( 'get_user_count' ) ? get_user_count() : null,
'locale' => get_locale(),
'timezone_offset' => wpcode_wp_timezone_string(),
// WPCode specific data.
'wpcode_version' => WPCODE_VERSION,
'wpcode_license_key' => null,
'wpcode_license_type' => null,
'wpcode_is_pro' => false,
'wpcode_lite_installed_date' => $installed_date,
'wpcode_settings' => $this->get_settings(),
);
// Add snippets data.
$data = array_merge( $data, $this->get_snippets_data() );
// Add installed packs (slugs only, no personal data).
if ( class_exists( 'WPCode_Packs' ) ) {
$data['wpcode_installed_packs'] = array_keys( WPCode_Packs::get_instance()->get_installed_state() );
}
return $data;
}
/**
* Return a list of active plugins.
*
* @return array An array of active plugin data.
* @since 2.0.10
*/
private function get_active_plugins() {
if ( ! function_exists( 'get_plugins' ) ) {
include ABSPATH . '/wp-admin/includes/plugin.php';
}
$active = get_option( 'active_plugins', array() );
$plugins = array_intersect_key( get_plugins(), array_flip( $active ) );
return array_map(
static function ( $plugin ) {
if ( isset( $plugin['Version'] ) ) {
return $plugin['Version'];
}
return 'Not Set';
},
$plugins
);
}
/**
* Get the User Agent string that will be sent to the API.
*
* @return string
* @since 2.0.10
*/
public function get_user_agent() {
return 'WPCode/' . WPCODE_VERSION . '; ' . get_bloginfo( 'url' );
}
/**
* Get the WPCode settings but anonymize some data.
*
* @return array
*/
public function get_settings() {
$settings = wpcode()->settings->get_options();
// By default, don't send the API tokens.
$settings_to_ignore = apply_filters(
'wpcode_usage_tracking_excluded_settings',
array(
'facebook_pixel_api_token',
'pinterest_conversion_token',
'tiktok_access_token',
)
);
foreach ( $settings_to_ignore as $setting ) {
if ( isset( $settings[ $setting ] ) ) {
$settings[ $setting ] = '***';
}
}
return $settings;
}
/**
* After the user has successfully authenticated with the API, we can start sending data.
*
* @return void
*/
public function usage_tracking_auth() {
// If already enabled, don't do anything.
if ( $this->is_enabled() ) {
return;
}
wpcode()->settings->update_option( 'usage_tracking', true );
}
/**
* Track snippet-specific data.
*
* @return array
*/
public function get_snippets_data() {
$counts = wp_count_posts( 'wpcode' );
$snippets_data = array(
'wpcode_total_snippets' => array_sum( array( $counts->publish, $counts->draft ) ),
'wpcode_active_snippets' => $counts->publish,
'wpcode_trashed_snippets' => $counts->trash,
'wpcode_generated_snippets' => 0,
'wpcode_generators' => array(),
);
if ( empty( $snippets_data['wpcode_total_snippets'] ) ) {
// If there are no snippets to look at then we can return early.
return $snippets_data;
}
// Let's see how many snippets were generated with a WPCode Generator.
$generated_snippets = get_posts(
array(
'post_type' => 'wpcode',
'meta_key' => '_wpcode_generator', // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key
'fields' => 'ids',
)
);
if ( ! empty( $generated_snippets ) ) {
$snippets_data['wpcode_generated_snippets'] = count( $generated_snippets );
foreach ( $generated_snippets as $snippet_id ) {
$snippets_data['wpcode_generators'][] = get_post_meta( $snippet_id, '_wpcode_generator', true );
}
}
return $snippets_data;
}
}
@@ -0,0 +1,33 @@
<?php
/**
* Importer for Code Snippets Pro.
*
* @package WPCode.
*/
/**
* Class WPCode_Importer_Code_Snippets_Pro.
*/
class WPCode_Importer_Code_Snippets_Pro extends WPCode_Importer_Code_Snippets {
/**
* The plugin name.
*
* @var string
*/
public $name = 'Code Snippets Pro';
/**
* Importer slug.
*
* @var string
*/
public $slug = 'code-snippets-pro';
/**
* Plugin path.
*
* @var string
*/
public $path = 'code-snippets-pro/code-snippets.php';
}
@@ -0,0 +1,194 @@
<?php
/**
* Importer for Code Snippets.
*
* @package WPCode.
*/
/**
* Class WPCode_Importer_Code_Snippets.
*/
class WPCode_Importer_Code_Snippets extends WPCode_Importer_Type {
/**
* The plugin name.
*
* @var string
*/
public $name = 'Code Snippets';
/**
* Importer slug.
*
* @var string
*/
public $slug = 'code-snippets';
/**
* Plugin path.
*
* @var string
*/
public $path = 'code-snippets/code-snippets.php';
/**
* Get an array of snippets for this plugin.
*
* @return array
*/
public function get_snippets() {
$snippets = array();
if ( ! $this->is_active() ) {
return $snippets;
}
if ( ! function_exists( '\Code_Snippets\get_snippets' ) ) {
return $snippets;
}
$code_snippets = \Code_Snippets\get_snippets();
foreach ( $code_snippets as $code_snippet ) {
/**
* The Code Snippets Snippet object.
*
* @var \Code_Snippets\Snippet $code_snippet
*/
if ( '' === $code_snippet->name ) {
$code_snippet->name = '(no title)';
}
$snippets[ $code_snippet->id ] = $code_snippet->name;
}
return $snippets;
}
/**
* Import the snippet data.
*
* @return void
*/
public function import_snippet() {
// Run a security check.
check_ajax_referer( 'wpcode_admin' );
if ( ! current_user_can( 'wpcode_edit_snippets' ) ) {
wp_send_json_error();
}
if ( ! function_exists( '\Code_Snippets\get_snippets' ) ) {
wp_send_json_error();
}
$id = isset( $_POST['snippet_id'] ) ? absint( $_POST['snippet_id'] ) : 0;
// Grab a snippet from Code Snippets.
$snippets = \Code_Snippets\get_snippets( array( $id ) );
if ( empty( $snippets ) || empty( $snippets[0] ) ) {
wp_send_json_error(
array(
'error' => true,
'name' => esc_html__( 'Unknown Snippet', 'insert-headers-and-footers' ),
'msg' => esc_html__( 'The snippet you are trying to import does not exist.', 'insert-headers-and-footers' ),
)
);
}
// If we got so far we have a snippet to process.
$snippet = $snippets[0];
// Create a new snippet from the snippet data array.
$new_snippet = new WPCode_Snippet( $this->get_snippet_data( $snippet ) );
$new_snippet->save();
if ( ! empty( $new_snippet->get_id() ) ) {
$title = $new_snippet->get_title();
wp_send_json_success(
array(
'name' => '' !== $title ? $title : '(no title)',
'edit' => esc_url_raw(
add_query_arg(
array(
'page' => 'wpcode-snippet-manager',
'snippet_id' => $new_snippet->get_id(),
),
admin_url( 'admin.php' )
)
),
)
);
}
}
/**
* Convert a "Code Snippets" snippet to the format for a WPCode snippet.
*
* @param \Code_Snippets\Snippet $snippet The snippet object.
*
* @return array
*/
public function get_snippet_data( $snippet ) {
$code_type = $this->get_snippet_type( $snippet );
$auto_insert = 1;
switch ( $snippet->scope ) {
case 'admin':
$location = 'admin_only';
break;
case 'front-end':
$location = 'frontend_only';
break;
default:
$location = 'everywhere';
}
if ( 'php' !== $code_type ) {
$location = '';
$auto_insert = 0;
}
$tags = is_array( $snippet->tags ) ? $snippet->tags : explode( ',', $snippet->tags );
$tags[] = $this->add_imported_tag();
return array(
'code' => wp_slash( $snippet->code ),
'note' => $snippet->desc,
'title' => $snippet->name,
'tags' => implode( ',', $tags ), // Combine all tags into a single string.
'code_type' => $code_type,
'priority' => $snippet->priority,
'location' => $location,
'auto_insert' => $auto_insert,
);
}
/**
* Get the snippet type from the scope as the method in \Code_Snippets\Snippet is private.
*
* @param \Code_Snippets\Snippet $snippet The snippet to check the scope for.
*
* @return string
*/
public function get_snippet_type( $snippet ) {
if ( ! isset( $snippet->scope ) ) {
return 'php';
}
if ( '-css' === substr( $snippet->scope, - 4 ) ) {
return 'css';
}
if ( '-js' === substr( $snippet->scope, - 3 ) ) {
return 'js';
}
if ( 'content' === substr( $snippet->scope, - 7 ) ) {
return 'universal';
}
return 'php';
}
}
@@ -0,0 +1,391 @@
<?php
/**
* Importer for Header Footer Code Manager.
*
* @package WPCode
*/
/**
* Class WPCode_Importer_Header_Footer_Code_Manager
*/
class WPCode_Importer_Header_Footer_Code_Manager extends WPCode_Importer_Type {
/**
* The plugin name.
*
* @var string
*/
public $name = 'Header Footer Code Manager';
/**
* Importer slug.
*
* @var string
*/
public $slug = 'header-footer-code-manager';
/**
* Plugin path.
*
* @var string
*/
public $path = 'header-footer-code-manager/99robots-header-footer-code-manager.php';
/**
* Get an array of snippets from the Header Footer Code Manager table.
*
* Returns an associative array where keys are snippet IDs and values are snippet labels.
*
* @return array
*/
public function get_snippets() {
$snippets = array();
if ( ! class_exists( 'Hfcm_Snippets_List' ) ) {
return $snippets;
}
$results = Hfcm_Snippets_List::get_snippets();
if ( $results ) {
foreach ( $results as $snippet ) {
$label = ! empty( $snippet['name'] ) ? $snippet['name'] : __( '(no title)', 'insert-headers-and-footers' );
$snippets[ $snippet['script_id'] ] = $label;
}
}
return $snippets;
}
/**
* Import the selected snippet.
*
* Expects a POST parameter 'snippet_id' that contains the HFCM snippet ID.
*
* @return void
*/
public function import_snippet() {
// Verify AJAX nonce.
check_ajax_referer( 'wpcode_admin' );
if ( ! current_user_can( 'wpcode_edit_snippets' ) ) {
wp_send_json_error();
}
$id = isset( $_POST['snippet_id'] ) ? absint( $_POST['snippet_id'] ) : 0;
if ( ! $id ) {
wp_send_json_error(
array(
'error' => true,
'msg' => __( 'Invalid snippet ID.', 'insert-headers-and-footers' ),
)
);
}
global $wpdb;
$table_name = $wpdb->prefix . 'hfcm_scripts';
$snippet = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$table_name} WHERE script_id = %d", $id ) ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.DirectQuery
if ( ! $snippet ) {
wp_send_json_error(
array(
'error' => true,
'msg' => __( 'Snippet not found.', 'insert-headers-and-footers' ),
)
);
}
// Convert the HFCM snippet data into the WPCode snippet format.
$snippet_data = $this->get_snippet_data( $snippet );
// Create a new snippet (assumes WPCode_Snippet is defined in your codebase).
$new_snippet = new WPCode_Snippet( $snippet_data );
$new_snippet->save();
if ( $new_snippet->get_id() ) {
$title = $new_snippet->get_title();
wp_send_json_success(
array(
'name' => '' !== $title ? $title : '(no title)',
'edit' => esc_url_raw(
add_query_arg(
array(
'page' => 'wpcode-snippet-manager',
'snippet_id' => $new_snippet->get_id(),
),
admin_url( 'admin.php' )
)
),
)
);
} else {
wp_send_json_error(
array(
'error' => true,
'msg' => __( 'Failed to import snippet.', 'insert-headers-and-footers' ),
)
);
}
}
/**
* Convert a Header Footer Code Manager snippet into a WPCode snippet data array.
*
* @param object $snippet The snippet row from the HFCM table.
* @return array The snippet data array.
*/
public function get_snippet_data( $snippet ) {
// Decode snippet content that is stored with HTML entities.
$code = html_entity_decode( $snippet->snippet );
$title = $snippet->name;
$device_type = $snippet->device_type;
if ( 'both' === $device_type ) {
$device_type = 'any';
}
// Determine code type (default is 'html').
$code_type = 'html';
if ( 'js' === $snippet->snippet_type ) {
$code_type = 'javascript';
} elseif ( 'css' === $snippet->snippet_type ) {
$code_type = 'css';
}
$location = '';
if ( isset( $snippet->location ) ) {
switch ( $snippet->location ) {
case 'header':
$location = 'site_wide_header';
break;
case 'footer':
$location = 'site_wide_footer';
break;
case 'before_content':
case 'after_content':
$location = $snippet->location;
break;
default:
$location = 'site_wide_header';
}
}
// Prepare the snippet data array.
$snippet_data = array(
'code' => wp_slash( $code ),
'title' => $title,
'code_type' => $code_type,
'location' => $location,
'device_type' => $device_type,
'tags' => $this->add_imported_tag(),
'auto_insert' => 1,
'priority' => 10,
);
$display_on = isset( $snippet->display_on ) ? $snippet->display_on : 'All';
switch ( $display_on ) {
case 's_pages':
$pages = json_decode( $snippet->s_pages, true );
if ( is_array( $pages ) && ! empty( $pages ) ) {
$conditional_rules = array(
'show' => 'show',
'groups' => array(
array(
array(
'type' => 'page',
'option' => 'post_id',
'relation' => '=',
'value' => $pages,
),
),
),
);
}
break;
case 's_posts':
$posts = json_decode( $snippet->s_posts, true );
if ( is_array( $posts ) && ! empty( $posts ) ) {
$conditional_rules = array(
'show' => 'show',
'groups' => array(
array(
array(
'type' => 'page',
'option' => 'post_id',
'relation' => '=',
'value' => $posts,
),
),
),
);
}
break;
case 's_categories':
$cats = json_decode( $snippet->s_categories, true );
if ( is_array( $cats ) && ! empty( $cats ) ) {
$conditional_rules = array(
'show' => 'show',
'groups' => array(
array(
array(
'type' => 'page',
'option' => 'taxonomy_term',
'relation' => 'in',
'value' => $cats,
),
),
),
);
}
break;
case 's_custom_posts':
$custom = json_decode( $snippet->s_custom_posts, true );
if ( is_array( $custom ) && ! empty( $custom ) ) {
$groups = array();
foreach ( $custom as $custom_post_type_value ) {
$groups[] = array(
'type' => 'page',
'option' => 'post_type',
'relation' => '=',
'value' => $custom_post_type_value,
);
}
$conditional_rules = array(
'show' => 'show',
'groups' => array( $groups ),
);
}
break;
case 's_tags':
$tags = json_decode( $snippet->s_tags, true );
if ( is_array( $tags ) && ! empty( $tags ) ) {
$conditional_rules = array(
'show' => 'show',
'groups' => array(
array(
array(
'type' => 'page',
'option' => 'taxonomy_term',
'relation' => 'in',
'value' => $tags,
),
),
),
);
}
break;
case 's_is_home':
$conditional_rules = array(
'show' => 'show',
'groups' => array(
array(
array(
'type' => 'page',
'option' => 'type_of_page',
'relation' => '=',
'value' => 'is_front_page',
),
),
),
);
break;
case 's_is_search':
$conditional_rules = array(
'show' => 'show',
'groups' => array(
array(
array(
'type' => 'page',
'option' => 'type_of_page',
'relation' => '=',
'value' => 'is_search',
),
),
),
);
break;
case 's_is_archive':
$conditional_rules = array(
'show' => 'show',
'groups' => array(
array(
array(
'type' => 'page',
'option' => 'type_of_page',
'relation' => '=',
'value' => 'is_archive',
),
),
),
);
break;
case 'latest_posts':
$conditional_rules = array(
'show' => 'show',
'groups' => array(
array(
array(
'type' => 'page',
'option' => 'type_of_page',
'relation' => '=',
'value' => 'is_single',
),
),
),
);
break;
case 'manual':
$conditional_rules = null;
$snippet_data['auto_insert'] = 0;
break;
case 'All':
default:
$ex_pages = json_decode( $snippet->s_pages, true );
$ex_posts = json_decode( $snippet->s_posts, true );
$exclude = array();
if ( is_array( $ex_pages ) && ! empty( $ex_pages ) ) {
$exclude = array_merge( $exclude, $ex_pages );
}
if ( is_array( $ex_posts ) && ! empty( $ex_posts ) ) {
$exclude = array_merge( $exclude, $ex_posts );
}
if ( ! empty( $exclude ) ) {
$conditional_rules = array(
'show' => 'hide',
'groups' => array(
array(
array(
'type' => 'page',
'option' => 'post_id',
'relation' => '=',
'value' => $exclude,
),
),
),
);
} else {
$conditional_rules = null;
}
break;
}
if ( ! empty( $conditional_rules ) ) {
$snippet_data['use_rules'] = true;
$snippet_data['rules'] = $conditional_rules;
}
return $snippet_data;
}
}
@@ -0,0 +1,259 @@
<?php
/**
* Importer for Post Snippets.
*
* @package WPCode
*/
/**
* Class WPCode_Importer_Post_Snippets
*/
class WPCode_Importer_Post_Snippets extends WPCode_Importer_Type {
/**
* The plugin name.
*
* @var string
*/
public $name = 'Post Snippets';
/**
* Importer slug.
*
* @var string
*/
public $slug = 'post-snippets';
/**
* Plugin path.
*
* @var string
*/
public $path = 'post-snippets/post-snippets.php';
/**
* Get an array of snippets from the Post Snippets plugin.
*
* @return array
*/
public function get_snippets() {
$snippets = array();
if ( ! $this->is_active() ) {
return $snippets;
}
global $wpdb;
$table_name = $wpdb->prefix . 'pspro_snippets';
// Check if the table exists.
if ( $wpdb->get_var( "SHOW TABLES LIKE '{$table_name}'" ) !== $table_name ) { // phpcs:ignore
return $snippets;
}
// Get all snippets.
$results = $wpdb->get_results( "SELECT * FROM {$table_name}", ARRAY_A ); // phpcs:ignore
if ( ! empty( $results ) ) {
foreach ( $results as $snippet ) {
$title = ! empty( $snippet['snippet_title'] ) ? $snippet['snippet_title'] : __( '(no title)', 'insert-headers-and-footers' );
$snippets[ $snippet['ID'] ] = $title;
}
}
return $snippets;
}
/**
* Import a single snippet.
*
* @return void
*/
public function import_snippet() {
// Run a security check.
check_ajax_referer( 'wpcode_admin' );
if ( ! current_user_can( 'wpcode_edit_snippets' ) ) { // phpcs:ignore
wp_send_json_error();
}
$id = isset( $_POST['snippet_id'] ) ? absint( $_POST['snippet_id'] ) : 0;
if ( ! $id ) {
wp_send_json_error(
array(
'error' => true,
'msg' => __( 'Invalid snippet ID.', 'insert-headers-and-footers' ),
)
);
}
global $wpdb;
$table_name = $wpdb->prefix . 'pspro_snippets';
$snippet = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$table_name} WHERE ID = %d", $id ), ARRAY_A ); // phpcs:ignore
if ( empty( $snippet ) ) {
wp_send_json_error(
array(
'error' => true,
'msg' => __( 'Snippet not found.', 'insert-headers-and-footers' ),
)
);
}
// Convert the Post Snippets data into the WPCode snippet format.
$snippet_data = $this->get_snippet_data( $snippet );
// Create a new snippet.
$new_snippet = new WPCode_Snippet( $snippet_data );
$new_snippet->save();
if ( ! empty( $new_snippet->get_id() ) ) {
$title = $new_snippet->get_title();
wp_send_json_success(
array(
'name' => '' !== $title ? $title : '(no title)',
'edit' => esc_url_raw(
add_query_arg(
array(
'page' => 'wpcode-snippet-manager',
'snippet_id' => $new_snippet->get_id(),
),
admin_url( 'admin.php' )
)
),
)
);
} else {
wp_send_json_error(
array(
'error' => true,
'msg' => __( 'Failed to import snippet.', 'insert-headers-and-footers' ),
)
);
}
}
/**
* Convert a Post Snippets snippet to the format for a WPCode snippet.
*
* @param array $snippet The snippet data from Post Snippets.
*
* @return array
*/
public function get_snippet_data( $snippet ) {
// Determine code type based on snippet_php value.
$code_type = 'html';
if ( isset( $snippet['snippet_php'] ) ) {
if ( '1' === $snippet['snippet_php'] ) {
$code_type = 'php';
} elseif ( '2' === $snippet['snippet_php'] ) {
$code_type = 'js';
} elseif ( '3' === $snippet['snippet_php'] ) {
$code_type = 'css';
}
}
// Get group names for tags.
$tags = array( $this->add_imported_tag() );
if ( ! empty( $snippet['snippet_group'] ) ) {
$group_ids = maybe_unserialize( $snippet['snippet_group'] );
if ( is_array( $group_ids ) ) {
global $wpdb;
$group_table = $wpdb->prefix . 'pspro_groups';
foreach ( $group_ids as $group_id ) {
$group_name = $wpdb->get_var( $wpdb->prepare( "SELECT group_name FROM {$group_table} WHERE ID = %d", $group_id ) ); // phpcs:ignore
if ( $group_name && __( 'ungrouped', 'insert-headers-and-footers' ) !== $group_name ) {
$tags[] = sanitize_title( $group_name );
}
}
}
}
// Determine if this is a shortcode.
$is_shortcode = ! empty( $snippet['snippet_shortcode'] ) && '1' === $snippet['snippet_shortcode'];
$auto_insert = $is_shortcode ? 0 : 1;
// Get custom shortcode name.
$custom_shortcode = '';
if ( $is_shortcode ) {
$custom_shortcode = sanitize_title( $snippet['snippet_title'] );
}
// Determine location for PHP, CSS and JS snippets.
$location = '';
if ( 'php' === $code_type && $auto_insert ) {
// For PHP snippets, set location to "run everywhere".
$location = 'everywhere';
} elseif ( ( 'css' === $code_type || 'js' === $code_type ) && $auto_insert ) {
// Default locations.
$location = 'site_wide_header';
// Check snippet_vars for location information.
if ( ! empty( $snippet['snippet_vars'] ) ) {
$vars = explode( ',', $snippet['snippet_vars'] );
// For JS snippets, check header/footer location (first variable).
if ( 'js' === $code_type && isset( $vars[1] ) ) {
$js_location = trim( $vars[1] );
// The site location is the third variable in the snippet_vars field.
$site_location = isset( $vars[2] ) ? trim( $vars[2] ) : 'frontend';
// Map to appropriate WPCode location.
if ( 'footer' === $js_location && 'admin' === $site_location ) {
$location = 'admin_footer';
} elseif ( 'header' === $js_location && 'admin' === $site_location ) {
$location = 'admin_head';
} elseif ( 'footer' === $js_location ) {
$location = 'site_wide_footer';
}
}
// For CSS snippets, check admin/frontend location.
elseif ( 'css' === $code_type && isset( $vars[2] ) && 'admin' === trim( $vars[2] ) ) {
$location = 'admin_head';
}
}
}
// Prepare the snippet data.
$snippet_data = array(
'title' => $snippet['snippet_title'],
'code' => $snippet['snippet_content'],
'code_type' => $code_type,
'tags' => implode( ',', $tags ),
'note' => $snippet['snippet_desc'],
'auto_insert' => $auto_insert,
'active' => false,
'custom_shortcode' => $custom_shortcode,
);
// Add location if set.
if ( ! empty( $location ) ) {
$snippet_data['location'] = $location;
}
// If there are variables in the snippet, add them as shortcode attributes.
if ( ! empty( $snippet['snippet_vars'] ) && $is_shortcode ) {
$variables = explode( ',', $snippet['snippet_vars'] );
$shortcode_attributes = array();
foreach ( $variables as $variable ) {
$variable = trim( $variable );
// Check if variable has a default value (format: var=default).
$parts = explode( '=', $variable, 2 );
$variable_name = $parts[0];
if ( ! empty( $variable_name ) ) {
$shortcode_attributes[] = $variable_name;
}
}
if ( ! empty( $shortcode_attributes ) ) {
$snippet_data['shortcode_attributes'] = $shortcode_attributes;
}
}
return $snippet_data;
}
}
@@ -0,0 +1,223 @@
<?php
/**
* Importer for Simple Custom CSS and JS.
*
* @package WPCode.
*/
/**
* Class WPCode_Importer_Simple_Custom_CSS_and_JS.
*/
class WPCode_Importer_Simple_Custom_CSS_and_JS extends WPCode_Importer_Type {
/**
* The plugin name.
*
* @var string
*/
public $name = 'Simple Custom CSS and JS';
/**
* Importer slug.
*
* @var string
*/
public $slug = 'simple-custom-css-js';
/**
* Plugin path.
*
* @var string
*/
public $path = 'custom-css-js/custom-css-js.php';
/**
* Get an array of snippets for this plugin.
*
* @return array
*/
public function get_snippets() {
$snippets = array();
if ( ! $this->is_active() ) {
return $snippets;
}
// Retrieve all 'custom-css-js' posts.
$args = array(
'post_type' => 'custom-css-js',
'posts_per_page' => -1,
'post_status' => array( 'publish', 'draft' ),
);
$posts = get_posts( $args );
foreach ( $posts as $post ) {
$status = $post->post_status;
$label = $post->post_title ? $post->post_title : '(no title)';
if ( 'publish' !== $status ) {
$label .= ' (' . $status . ')';
}
$snippets[ $post->ID ] = $label;
}
return $snippets;
}
/**
* Import the snippet data.
*
* @return void
*/
public function import_snippet() {
// Run a security check.
check_ajax_referer( 'wpcode_admin' );
if ( ! current_user_can( 'wpcode_edit_snippets' ) ) {
wp_send_json_error();
}
$id = isset( $_POST['snippet_id'] ) ? absint( $_POST['snippet_id'] ) : 0;
if ( ! $id ) {
wp_send_json_error(
array(
'error' => true,
'name' => esc_html__( 'Unknown Snippet', 'insert-headers-and-footers' ),
'msg' => esc_html__( 'The snippet you are trying to import does not exist.', 'insert-headers-and-footers' ),
)
);
}
$post = get_post( $id );
if ( ! $post || 'custom-css-js' !== $post->post_type ) {
wp_send_json_error(
array(
'error' => true,
'name' => esc_html__( 'Unknown Snippet', 'insert-headers-and-footers' ),
'msg' => esc_html__( 'The snippet you are trying to import does not exist.', 'insert-headers-and-footers' ),
)
);
}
// Now get the snippet data.
$snippet_data = $this->get_snippet_data( $post );
// Create new WPCode snippet.
$new_snippet = new WPCode_Snippet( $snippet_data );
// Save the snippet.
$new_snippet->save();
if ( ! empty( $new_snippet->get_id() ) ) {
$title = $new_snippet->get_title();
wp_send_json_success(
array(
'name' => '' !== $title ? $title : '(no title)',
'edit' => esc_url_raw(
add_query_arg(
array(
'page' => 'wpcode-snippet-manager',
'snippet_id' => $new_snippet->get_id(),
),
admin_url( 'admin.php' )
)
),
)
);
} else {
wp_send_json_error(
array(
'error' => true,
'name' => $post->post_title,
'msg' => esc_html__( 'Failed to import the snippet.', 'insert-headers-and-footers' ),
)
);
}
}
/**
* Convert a "Simple Custom CSS and JS" snippet to the format for a WPCode snippet.
*
* @param WP_Post $post The snippet post object.
*
* @return array
*/
public function get_snippet_data( $post ) {
// Prepare the data.
$code = $post->post_content;
$title = $post->post_title;
// Get the options array.
$options = get_post_meta( $post->ID, 'options', true );
$code_type = 'css';
if ( is_array( $options ) && isset( $options['language'] ) ) {
$language = $options['language'];
// Map language to code_type.
switch ( $language ) {
case 'js':
$code_type = 'javascript';
break;
case 'html':
$code_type = 'html';
break;
}
}
$type_location = isset( $options['type'] ) ? $options['type'] : '';
if ( 'header' === $type_location ) {
$location = 'site_wide_header';
} elseif ( 'footer' === $type_location ) {
$location = 'site_wide_footer';
} else {
$location = 'site_wide_body';
}
if ( ! empty( $options['side'] ) ) {
$site_locations = explode( ',', $options['side'] );
$site_locations = array_map( 'trim', $site_locations );
if ( in_array( 'admin', $site_locations, true ) && in_array( 'frontend', $site_locations, true ) ) {
$location = 'site_wide_header';
} elseif ( 'header' === $type_location && in_array( 'admin', $site_locations, true ) ) {
$location = 'admin_head';
} elseif ( 'footer' === $type_location && in_array( 'admin', $site_locations, true ) ) {
$location = 'admin_footer';
}
}
$priority = 10;
if ( is_array( $options ) && isset( $options['priority'] ) ) {
$priority = intval( $options['priority'] );
}
$load_as_file = false;
if ( is_array( $options ) && isset( $options['linking'] ) ) {
$linking = $options['linking'];
if ( 'external' === $linking ) {
$load_as_file = true;
}
}
// Prepare the data array.
$snippet_data = array(
'code' => wp_slash( $code ),
'title' => $title,
'code_type' => $code_type,
'location' => $location,
'auto_insert' => 1, // Set to 1 for auto-insert.
'priority' => $priority,
'tags' => $this->add_imported_tag(),
);
// Set 'load_as_file' if applicable.
if ( $load_as_file ) {
$snippet_data['load_as_file'] = true;
}
return $snippet_data;
}
}
@@ -0,0 +1,107 @@
<?php
/**
* Abstract class for importing data from other plugins.
*
* @package WPCode
*/
/**
* Abstract class WPCode_Importer_Type.
*/
abstract class WPCode_Importer_Type {
/**
* The plugin name.
*
* @var string
*/
public $name = '';
/**
* The plugin slug.
*
* @var string
*/
public $slug = '';
/**
* The plugin path.
*
* @var string
*/
public $path = '';
/**
* Constructor.
*/
public function __construct() {
add_action( "wp_ajax_wpcode_import_snippet_{$this->slug}", array( $this, 'import_snippet' ) );
}
/**
* Add to list of registered importers.
*
* @param array $importers List of supported importers.
*
* @return array
*/
public function register( $importers = array() ) {
$importers[ $this->slug ] = array(
'name' => $this->name,
'slug' => $this->slug,
'path' => $this->path,
'installed' => file_exists( trailingslashit( WP_PLUGIN_DIR ) . $this->path ),
'active' => $this->is_active(),
);
return $importers;
}
/**
* Get all the snippets for this plugin.
*
* @return array
*/
abstract public function get_snippets();
/**
* Check if the plugin is active.
*
* @return bool
*/
public function is_active() {
return is_plugin_active( $this->path );
}
/**
* After a snippet has been successfully imported we track it, so that in the
* future we can alert users if they try to import a snippet that has already
* been imported.
*
* @param int $source_id Imported plugin snippet ID.
* @param int $wpcode_id WPCode snippet ID.
*/
public function track_import( $source_id, $wpcode_id ) {
$imported = get_option( 'wpcode_imported', array() );
$imported[ $this->slug ][ $wpcode_id ] = $source_id;
update_option( 'wpcode_imported', $imported, false );
}
/**
* Get the imported tag for this plugin.
*
* @return string
*/
public function add_imported_tag(){
return 'imported-' . $this->slug;
}
/**
* Import a single snippet using AJAX.
*
* @return void
*/
abstract public function import_snippet();
}
@@ -0,0 +1,171 @@
<?php
/**
* Importer for Woody.
*
* @package WPCode.
*/
/**
* Class WPCode_Importer_Woody.
*/
class WPCode_Importer_Woody extends WPCode_Importer_Type {
/**
* The plugin name.
*
* @var string
*/
public $name = 'Woody Code Snippets';
/**
* Importer slug.
*
* @var string
*/
public $slug = 'woody';
/**
* Plugin path.
*
* @var string
*/
public $path = 'insert-php/insert_php.php';
/**
* Get an array of snippets for this plugin.
*
* @return array
*/
public function get_snippets() {
$snippets = array();
if ( ! $this->is_active() ) {
return $snippets;
}
$snippets_posts = get_posts(
array(
'post_type' => 'wbcr-snippets',
'posts_per_page' => - 1,
'post_status' => 'any',
)
);
foreach ( $snippets_posts as $post ) {
if ( '' === $post->post_title ) {
$post->post_title = '(no title)';
}
$snippets[ $post->ID ] = $post->post_title;
}
return $snippets;
}
/**
* Import the snippet data.
*
* @return void
*/
public function import_snippet() {
// Run a security check.
check_ajax_referer( 'wpcode_admin' );
if ( ! current_user_can( 'wpcode_edit_snippets' ) ) {
wp_send_json_error();
}
if ( ! class_exists( 'WINP_Helper' ) ) {
wp_send_json_error();
}
$id = isset( $_POST['snippet_id'] ) ? absint( $_POST['snippet_id'] ) : 0;
// Grab a snippet from Code Snippets.
$snippet = get_post( $id );
if ( null === $snippet ) {
wp_send_json_error(
array(
'error' => true,
'name' => esc_html__( 'Unknown Snippet', 'insert-headers-and-footers' ),
'msg' => esc_html__( 'The snippet you are trying to import does not exist.', 'insert-headers-and-footers' ),
)
);
}
// If we got so far we have a snippet to process.
// Create a new snippet from the snippet data array.
$new_snippet = new WPCode_Snippet( $this->get_snippet_data( $snippet ) );
$new_snippet->save();
if ( ! empty( $new_snippet->get_id() ) ) {
$title = $new_snippet->get_title();
wp_send_json_success(
array(
'name' => '' !== $title ? $title : '(no title)',
'edit' => esc_url_raw(
add_query_arg(
array(
'page' => 'wpcode-snippet-manager',
'snippet_id' => $new_snippet->get_id(),
),
admin_url( 'admin.php' )
)
),
)
);
}
}
/**
* Convert a "Woody" snippet to the format for a WPCode snippet.
*
* @param WP_Post $snippet The snippet post.
*
* @return array
*/
public function get_snippet_data( $snippet ) {
$snippet_location = WINP_Helper::getMetaOption( $snippet->ID, 'snippet_location', '' );
$scope = WINP_Helper::getMetaOption( $snippet->ID, 'snippet_scope', '' );
$auto_insert = in_array(
$scope,
array(
'auto',
'evrywhere',
),
true
) ? 1 : 0;
switch ( $snippet_location ) {
case 'header':
$location = 'site_wide_header';
break;
case 'footer':
$location = 'site_wide_footer';
break;
default:
$location = $snippet_location;
}
$existing_tags = wp_get_post_terms( $snippet->ID, WINP_SNIPPETS_TAXONOMY, array( 'fields' => 'slugs' ) );
$existing_tags[] = $this->add_imported_tag(); // Add the import tag.
$tags = ( is_array( $existing_tags ) ) ? implode( ',', $existing_tags ) : $existing_tags;
return array(
'code' => wp_slash( WINP_Helper::get_snippet_code( $snippet ) ),
'note' => WINP_Helper::getMetaOption( $snippet->ID, 'snippet_description', '' ),
'title' => $snippet->post_title,
'tags' => $tags,
'code_type' => WINP_Helper::get_snippet_type( $snippet->ID ),
'priority' => intval( WINP_Helper::getMetaOption( $snippet->ID, 'snippet_priority', '' ) ),
'location' => $location,
'auto_insert' => $auto_insert,
);
}
}
@@ -0,0 +1,309 @@
<?php
/**
* Admin page for handling 1-click install of public snippets in the WPCode library.
*
* @package WPCode
*/
/**
* Class for the 1-Click admin page.
*/
class WPCode_Admin_Page_Click extends WPCode_Admin_Page {
/**
* The page slug to be used when adding the submenu.
*
* @var string
*/
public $page_slug = 'wpcode-click';
/**
* The action used for the nonce.
*
* @var string
*/
protected $action = 'wpcode-click';
/**
* The nonce name field.
*
* @var string
*/
protected $nonce_name = 'wpcode-click_nonce';
/**
* Hide this page in the menu.
*
* @var bool
*/
public $hide_menu = true;
/**
* Call this just to set the page title translatable.
*/
public function __construct() {
$this->page_title = __( '1-Click', 'insert-headers-and-footers' );
parent::__construct();
}
/**
* Register hook on admin init just for this page.
*
* @return void
*/
public function page_hooks() {
add_action( 'admin_init', array( $this, 'submit_listener' ) );
}
/**
* Override to hide default header on this page.
*
* @return void
*/
public function output_header() {
}
/**
* Wrap this page in a form tag.
*
* @return void
*/
public function output() {
?>
<form action="<?php echo esc_url( $this->get_page_action_url() ); ?>" method="post">
<?php parent::output(); ?>
</form>
<?php
}
/**
* The page output.
*
* @return void
*/
public function output_content() {
?>
<div class="wpcode-modal-area">
<div class="wpcode-modal-header">
<?php $this->logo_image(); ?>
</div>
<?php
$snippet_hash = get_transient( 'wpcode_deploy_snippet_id' );
// Let's see if we're in the middle of a fresh installation from the library.
if ( isset( $_GET['message'] ) && 'wpcode-deploy' === $_GET['message'] ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
if ( ! wpcode()->library_auth->has_auth() ) {
?>
<h3><?php esc_html_e( 'Connect your site to the WPCode Library', 'insert-headers-and-footers' ); ?></h3>
<p><?php esc_html_e( 'You\'re almost there! To finish installing the snippet, you need to connect your site to your account on the WPCode Library. This will allow you to install snippets directly to your site in the future.', 'insert-headers-and-footers' ); ?></p>
<p><?php esc_html_e( 'You\'ll also get access to tens of free expert-curated snippets that can be installed with 1-click from inside the plugin.', 'insert-headers-and-footers' ); ?></p>
<div class="wpcode-buttons-row">
<button class="wpcode-button wpcode-button-large wpcode-start-auth">
<?php esc_html_e( 'Connect to Library', 'insert-headers-and-footers' ); ?>
</button>
</div>
<?php
} else {
// The site is connected to the library but it must mean it's connected to another account in which case they should connect to their own account.
?>
<h3><?php esc_html_e( 'Your site is already connected to the WPCode Library using another account', 'insert-headers-and-footers' ); ?></h3>
<p>
<?php esc_html_e( 'In order to continue installing the snippet from the WPCode library you have to either login to the Library with the same account used to connect this site to the WPCode library initially or disconnect this site from the WPCode library and connect using your own account.', 'insert-headers-and-footers' ); ?>
</p>
<div class="wpcode-buttons-row">
<button class="wpcode-button wpcode-delete-auth">
<?php esc_html_e( 'Disconnect Site From Library', 'insert-headers-and-footers' ); ?>
</button>
<a class="wpcode-button" href="<?php echo esc_url( wpcode()->library_auth->library_url ); ?>/account">
<?php esc_html_e( 'Login with another user on the WPCode Library', 'insert-headers-and-footers' ); ?>
</a>
</div>
<?php
}
} elseif ( false !== $snippet_hash && wpcode()->library_auth->has_auth() && ! isset( $_GET['snippet'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
// We have a snippet hash so let's continue the snippet install process.
$snippet_url = wpcode()->library_auth->library_url . '/snippet/' . $snippet_hash . '/?deploy=1';
?>
<h3><?php esc_html_e( 'Congratulations, your site is now connected!', 'insert-headers-and-footers' ); ?></h3>
<p><?php esc_html_e( 'Your site is now connected to the WPCode Library and you can install snippets directly from the library. Please click the button below to resume installing the snippet you were viewing.', 'insert-headers-and-footers' ); ?></p>
<div class="wpcode-buttons-row">
<a href="<?php echo esc_url( $snippet_url ); ?>" class="wpcode-button wpcode-button-large">
<?php esc_html_e( 'Resume Snippet Installation', 'insert-headers-and-footers' ); ?>
</a>
</div>
<?php
delete_transient( 'wpcode_deploy_snippet_id' );
} elseif ( ! wpcode()->library_auth->has_auth() ) { // Let's make sure the site is authenticated with the library.
?>
<h3><?php esc_html_e( 'Your site is not connected to the WPCode library.', 'insert-headers-and-footers' ); ?></h3>
<p><?php esc_html_e( 'Connect now to enable installing public snippets from the WPCode library with 1-click and also get access to tens of expert-curated snippets that you can install from inside the plugin.', 'insert-headers-and-footers' ); ?></p>
<div class="wpcode-buttons-row">
<button class="wpcode-button wpcode-button-large wpcode-start-auth">
<?php esc_html_e( 'Connect to Library', 'insert-headers-and-footers' ); ?>
</button>
</div>
<?php
// Let's check that we have a snippet hash to load.
} elseif ( empty( $_GET['snippet'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
?>
<div class="notice notice-error">
<p><?php esc_html_e( 'No snippet provided.', 'insert-headers-and-footers' ); ?></p>
</div>
<?php
// Let's check that the site is authenticated.
} elseif ( empty( $_GET['auth'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
?>
<div class="notice notice-error">
<p><?php esc_html_e( 'Missing authentication token, please click the link in the WPCode Library again.', 'insert-headers-and-footers' ); ?></p>
</div>
<?php
} else {
// Let's make sure they don't get redirect again if they reached this point.
delete_transient( 'wpcode_deploy_snippet_id' );
// Let's attempt to load the snippet data from the library.
$auth = sanitize_key( $_GET['auth'] ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended
$snippet_hash = sanitize_key( $_GET['snippet'] ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended
$snippet_request = wpcode()->library->get_public_snippet( $snippet_hash, $auth );
if ( ! isset( $snippet_request['status'] ) || 'success' !== $snippet_request['status'] ) {
// We have an error. Let's default to a generic message.
$error = __( 'We encountered an error loading your snippet, please try again in a few minutes', 'insert-headers-and-footers' );
if ( isset( $snippet_request['message'] ) ) {
// If there is a message, let's use that instead.
$error = sprintf(
/* translators: %s: The error message from the API. */
__( 'We encountered the following error loading your snippet: %s', 'insert-headers-and-footers' ),
$snippet_request['message']
);
}
$go_back_url = wpcode()->library_auth->library_url . '/snippet/' . $snippet_hash;
?>
<div class="notice notice-error">
<p><?php echo esc_html( $error ); ?></p>
</div>
<div class="wpcode-buttons-row">
<a href="<?php echo esc_url( $go_back_url ); ?>" class="wpcode-button"><?php esc_html_e( 'Go back to the library', 'insert-headers-and-footers' ); ?></a>
</div>
<?php
} else {
$snippet = $snippet_request['data'];
$snippet_types = wpcode()->execute->get_options();
// Let's show a preview of the snippet and ask the user to confirm.
?>
<h1><?php esc_html_e( 'Library Snippet Preview', 'insert-headers-and-footers' ); ?></h1>
<p><?php esc_html_e( 'Please review the snippet below and confirm that you would like to install it.', 'insert-headers-and-footers' ); ?></p>
<h3>
<?php
// Translators: %s: The snippet name.
printf( esc_html__( 'Snippet title: %s', 'insert-headers-and-footers' ), esc_html( $snippet['title'] ) );
?>
</h3>
<div class="wpcode-code-textarea">
<div class="wpcode-flex">
<div class="wpcode-column">
<h3><?php esc_html_e( 'Code preview', 'insert-headers-and-footers' ); ?></h3>
</div>
<div class="wpcode-column">
<div class="wpcode-input-select">
<label for="wpcode_snippet_type"><?php esc_html_e( 'Code Type', 'insert-headers-and-footers' ); ?></label>
<select disabled>
<?php
foreach ( $snippet_types as $key => $label ) {
if ( $key !== $snippet['code_type'] ) {
continue;
}
?>
<option selected><?php echo esc_html( $label ); ?></option>
<?php
}
?>
</select>
</div>
</div>
</div>
<textarea id="wpcode-code-preview"><?php echo esc_textarea( $snippet['code'] ); ?></textarea>
</div>
<div class="wpcode-buttons-row">
<input type="hidden" name="snippet" value="<?php echo esc_attr( $snippet['cloud_id'] ); ?>">
<input type="hidden" name="auth" value="<?php echo esc_attr( $auth ); ?>">
<button class="wpcode-button wpcode-button-large"><?php esc_html_e( 'Confirm & Install Snippet', 'insert-headers-and-footers' ); ?></button>
</div>
<?php
$editor = new WPCode_Code_Editor( esc_js( $snippet['code_type'] ) );
$editor->set_setting( 'readOnly', 'nocursor' );
$editor->register_editor( 'wpcode-code-preview' );
$editor->init_editor();
}
wp_nonce_field( $this->action, $this->nonce_name );
}
?>
</div>
<?php
}
/**
* For this page we output a title and the save button.
*
* @return void
*/
public function output_header_bottom() {
?>
<div class="wpcode-column">
<h1><?php esc_html_e( 'Confirm Snippet Installation', 'insert-headers-and-footers' ); ?></h1>
</div>
<?php
}
/**
* If the form is submitted attempt to save the values.
*
* @return void
*/
public function submit_listener() {
if ( ! isset( $_REQUEST[ $this->nonce_name ] ) || ! wp_verify_nonce( sanitize_key( $_REQUEST[ $this->nonce_name ] ), $this->action ) ) {
// Nonce is missing, so we're not even going to try.
return;
}
if ( ! current_user_can( 'wpcode_edit_snippets' ) ) {
// Should not be able to load this page at all without that permission but let's check anyway.
return;
}
$snippet_hash = isset( $_REQUEST['snippet'] ) ? sanitize_key( $_REQUEST['snippet'] ) : false;
$auth = isset( $_REQUEST['auth'] ) ? sanitize_key( $_REQUEST['auth'] ) : false;
// Let's load the data reliably again - it's saved in a transient so it should be fast.
$snippet_data = wpcode()->library->get_public_snippet( $snippet_hash, $auth );
// You should not be able to submit this form if the hash is invalid but let's check anyway.
if ( ! isset( $snippet_data['status'] ) || 'success' !== $snippet_data['status'] ) {
// This should not happen if you did not manually change the hash, so we can just return.
return;
}
// Drop cloud_id so we don't write My Library meta for a public-library install.
if ( isset( $snippet_data['data'] ) && is_array( $snippet_data['data'] ) ) {
unset( $snippet_data['data']['cloud_id'] );
}
// Let's create a new snippet.
$snippet = new WPCode_Snippet( $snippet_data['data'] );
// Let's save the snippet.
if ( $snippet->save() ) {
// If successfully saved let's redirect to the edit screen.
wp_safe_redirect(
add_query_arg(
array(
'page' => 'wpcode-snippet-manager',
'snippet_id' => $snippet->get_id(),
),
admin_url( 'admin.php' )
)
);
exit;
}
}
}
@@ -0,0 +1,579 @@
<?php
/**
* Code snippets admin main list page.
*
* @package WPCode
*/
/**
* Class for the code snippets page.
*/
class WPCode_Admin_Page_Code_Snippets extends WPCode_Admin_Page {
/**
* The page slug to be used when adding the submenu.
*
* @var string
*/
public $page_slug = 'wpcode';
/**
* Instance of the code snippets table.
*
* @see WP_List_Table
* @var WPCode_Code_Snippets_Table
*/
protected $snippets_table;
/**
* Call this just to set the page title translatable.
*/
public function __construct() {
$this->page_title = __( 'Code Snippets', 'insert-headers-and-footers' );
parent::__construct();
}
/**
* Page-specific hooks, init the custom WP_List_Table.
*
* @return void
*/
public function page_hooks() {
$this->process_message();
add_action( 'current_screen', array( $this, 'init_table' ) );
add_action( 'admin_init', array( $this, 'maybe_capture_filter' ) );
add_action( 'load-toplevel_page_wpcode', array( $this, 'maybe_process_bulk_action' ) );
add_action( 'wpcode_admin_notices', array( $this, 'maybe_show_deactivated_notice' ) );
// Register Screen options.
add_action( 'load-toplevel_page_wpcode', array( $this, 'add_per_page_option' ) );
// Hide some columns by default.
add_filter( 'default_hidden_columns', array( $this, 'hide_columns' ), 10, 2 );
add_filter( 'wpcode_admin_js_data', array( $this, 'prepare_admin_js_localization_data' ) );
add_filter( 'screen_settings', array( $this, 'add_custom_screen_option' ), 10, 2 );
// Hide the duplicated parameter from the URL.
add_filter( 'removable_query_args', array( $this, 'remove_query_arg_from_url' ) );
}
/**
* If the referer is set, remove and redirect.
*
* @return void
*/
public function maybe_capture_filter() {
if ( ! empty( $_REQUEST['_wp_http_referer'] ) && isset( $_SERVER['REQUEST_URI'] ) && isset( $_REQUEST['filter_action'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
wp_safe_redirect(
remove_query_arg(
array(
'_wp_http_referer',
'_wpnonce',
),
wp_unslash( $_SERVER['REQUEST_URI'] ) // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
)
);
exit;
}
if ( ! empty( $_REQUEST['_wp_http_referer'] ) && isset( $_SERVER['REQUEST_URI'] ) && isset( $_REQUEST['filter_clear'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
wp_safe_redirect(
add_query_arg(
'page',
'wpcode',
$this->admin_url( 'admin.php' )
)
);
exit;
}
}
/**
* Listener for bulk actions.
*
* @return void
*/
public function maybe_process_bulk_action() {
// phpcs:disable WordPress.Security.NonceVerification.Recommended
$ids = isset( $_GET['snippet_id'] ) ? array_map( 'absint', (array) $_GET['snippet_id'] ) : array();
$action = isset( $_REQUEST['action'] ) ? sanitize_key( $_REQUEST['action'] ) : false;
// phpcs:enable WordPress.Security.NonceVerification.Recommended
if ( empty( $ids ) || empty( $action ) ) {
return;
}
if ( empty( $_GET['_wpnonce'] ) ) {
return;
}
if (
! wp_verify_nonce( sanitize_key( $_GET['_wpnonce'] ), 'bulk-wpcode-snippets' ) &&
! wp_verify_nonce( sanitize_key( $_GET['_wpnonce'] ), 'wpcode_' . $action . '_nonce' )
) {
return;
}
// Only operate on wpcode snippets the current user is allowed to edit.
$ids = array_filter(
$ids,
function ( $id ) {
return 'wpcode' === get_post_type( $id ) && current_user_can( 'edit_post', $id );
}
);
if ( empty( $ids ) ) {
return;
}
$update_status_actions = array( 'trash', 'untrash' );
if ( in_array( $action, $update_status_actions, true ) ) {
$newstatus = 'trash' === $action ? 'trash' : 'draft';
foreach ( $ids as $id ) {
wp_update_post(
array(
'ID' => $id,
'post_status' => $newstatus,
)
);
}
// Clear errors when a snippet is trashed.
wpcode()->error->clear_snippets_errors();
}
if ( 'delete' === $action ) {
foreach ( $ids as $id ) {
wp_delete_post( $id );
}
// Clear errors when a snippet is deleted.
wpcode()->error->clear_snippets_errors();
}
$failed = 0;
if ( 'enable' === $action ) {
foreach ( $ids as $key => $id ) {
$snippet = wpcode_get_snippet( $id );
$snippet->activate();
if ( ! $snippet->active ) {
// If failed to activate don't count it.
unset( $ids[ $key ] );
++ $failed;
}
}
}
if ( 'disable' === $action ) {
foreach ( $ids as $id ) {
$snippet = wpcode_get_snippet( $id );
$snippet->deactivate();
}
}
$message = array(
rtrim( $action, 'e' ) . 'ed' => count( $ids ),
);
if ( $failed ) {
$message['error'] = $failed;
}
if ( 'duplicate' === $action ) {
foreach ( $ids as $id ) {
// Load all the snippet data in the object.
$snippet = wpcode_get_snippet( $id );
$snippet->duplicate();
}
}
wpcode()->cache->cache_all_loaded_snippets();
// Clear used library snippets.
delete_transient( 'wpcode_used_library_snippets' );
wp_safe_redirect(
add_query_arg(
$message,
remove_query_arg(
array(
'action',
'action2',
'_wpnonce',
'snippet_id',
'paged',
'_wp_http_referer',
)
)
)
);
exit;
}
/**
* Init the custom table for the snippets list.
*
* @return void
*/
public function init_table() {
require_once WPCODE_PLUGIN_PATH . 'includes/admin/pages/class-wpcode-code-snippets-table.php';
$this->snippets_table = new WPCode_Code_Snippets_Table();
}
/**
* Output the custom table and page content.
*
* @return void
*/
public function output_content() {
$this->snippets_table->prepare_items();
?>
<form id="wpcode-code-snippets-table" method="get" action="<?php echo esc_url( $this->admin_url( 'admin.php?page=wpcode' ) ); ?>">
<input type="hidden" name="page" value="wpcode"/>
<?php
$this->snippets_table->search_box( esc_html__( 'Search Snippets', 'insert-headers-and-footers' ), 'wpcode_snippet_search' );
$this->snippets_table->views();
$this->snippets_table->display();
?>
</form>
<?php
}
/**
* Custom Footer for this page.
*
* @return void
*/
public function output_footer() {
parent::output_footer();
?>
<div id="wpcode-loader">
<div class="wpcode-loader-overlay">
<img src="<?php echo esc_url( WPCODE_PLUGIN_URL ) . 'admin/images/spinner.svg'; // phpcs:ignore PluginCheck.CodeAnalysis.ImageFunctions.NonEnqueuedImage?>" alt="">
</div>
</div>
<?php
}
/**
* Get the snippet types for the filters in a normalized format.
*
* @return array
*/
public function get_snippet_types_for_filters() {
$types = wpcode()->execute->get_types();
$snippet_type = isset( $_GET['type'] ) ? sanitize_text_field( wp_unslash( $_GET['type'] ) ) : false; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
$type_buttons = array(
array(
'is_pro' => false,
'label' => esc_html__( 'All Snippets', 'insert-headers-and-footers' ),
'class' => ! $snippet_type ? 'active' : '',
'type' => '',
)
);
foreach ( $types as $type_key => $type ) {
$type_buttons[] = array(
'is_pro' => isset( $type['is_pro'] ) ? $type['is_pro'] : false,
'label' => $type['filter_label'],
'class' => $snippet_type === $type_key ? 'active' : '',
'type' => $type_key,
);
}
return $this->prepare_type_buttons( $type_buttons );
}
/**
* Reorder the buttons and add version-specific info.
*
* @param array $type_buttons The type buttons.
*
* @return array
*/
protected function prepare_type_buttons( $type_buttons ) {
// Reorder items so pro items are always last.
usort(
$type_buttons,
function ( $a, $b ) {
if ( $a['is_pro'] === $b['is_pro'] ) {
return 0;
}
return $a['is_pro'] ? 1 : - 1;
}
);
// Let's go through the items and add the pro class and update the label.
foreach ( $type_buttons as $key => $type ) {
if ( ! $type['is_pro'] ) {
continue;
}
$type_buttons[ $key ]['label'] = sprintf( '%s (PRO)', $type['label'] );
$type_buttons[ $key ]['class'] .= ' wpcode_pro_type_lite';
}
return $type_buttons;
}
/**
* Generate buttons for available snippet types.
*
* @return string HTML for the buttons.
*/
public function get_snippet_type_buttons() {
$buttons = $this->get_snippet_types_for_filters();
$buttons_html = '';
foreach ( $buttons as $button ) {
$buttons_html .= sprintf(
'<li><a class="%1$s" href="#" data-type="%2$s">%3$s</a></li>',
esc_attr( $button['class'] ),
esc_attr( $button['type'] ),
esc_attr( $button['label'] )
);
}
return $buttons_html;
}
/**
* Content of the bottom row of the header.
*
* @return void
*/
public function output_header_bottom() {
$add_new_url = $this->admin_url( 'admin.php?page=wpcode-snippet-manager' );
?>
<div class="wpcode-column wpcode-title-button">
<ul id="wpcode-snippet-type-buttons" class="wpcode-admin-tabs">
<?php echo $this->get_snippet_type_buttons(); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
</ul>
<button class="wpcode-mobile-dropdown-toggle wpcode-button wpcode-button-just-icon" data-target="#wpcode-snippet-type-buttons">
<?php wpcode_icon( 'menu', '24', '24', '0 -960 960 960' ); ?>
</button>
<a class="wpcode-button" href="<?php echo esc_url( $add_new_url ); ?>">
<?php esc_html_e( 'Add New', 'insert-headers-and-footers' ); ?>
</a>
</div>
<?php
}
/**
* Capture screen-specific messages and add notices.
*
* @return void
*/
public function process_message() {
// phpcs:disable WordPress.Security.NonceVerification
if ( ! empty( $_GET['trashed'] ) ) {
$count = absint( $_GET['trashed'] );
$notice = sprintf( /* Translators: %d - Trashed snippets count. */
_n( '%d snippet was successfully moved to Trash.', '%d snippets were successfully moved to Trash.', $count, 'insert-headers-and-footers' ),
$count
);
}
if ( ! empty( $_GET['untrashed'] ) ) {
$count = absint( $_GET['untrashed'] );
$notice = sprintf( /* translators: %d - Restored from trash snippets count. */
_n( '%d snippet was successfully restored.', '%d snippet were successfully restored.', $count, 'insert-headers-and-footers' ),
$count
);
}
if ( ! empty( $_GET['deleted'] ) ) {
$count = absint( $_GET['deleted'] );
$notice = sprintf( /* translators: %d - Deleted snippets count. */
_n( '%d snippet was successfully permanently deleted.', '%d snippets were successfully permanently deleted.', $count, 'insert-headers-and-footers' ),
$count
);
}
if ( isset( $_GET['enabled'] ) ) {
$count = absint( $_GET['enabled'] );
$notice = '';
if ( $count > 0 ) {
$notice = sprintf( /* translators: %d - Activated snippets count. */
_n( '%d snippet was successfully activated.', '%d snippets were successfully activated.', $count, 'insert-headers-and-footers' ),
$count
);
}
if ( isset( $_GET['error'] ) ) {
$error_count = absint( $_GET['error'] );
$notice .= ' ';
$notice .= sprintf( /* translators: %d - Failed to activate snippets count. */
_n( '%d snippet was not activated due to an error.', '%d snippets were not activated due to errors.', $error_count, 'insert-headers-and-footers' ),
$error_count
);
}
}
if ( ! empty( $_GET['disabled'] ) ) {
$count = absint( $_GET['disabled'] );
$notice = sprintf( /* translators: %d - Deactivated snippets count. */
_n( '%d snippet was successfully deactivated.', '%d snippets were successfully deactivated.', $count, 'insert-headers-and-footers' ),
$count
);
}
// phpcs:enable WordPress.Security.NonceVerification
if ( isset( $error_count ) && isset( $notice ) ) {
$this->set_error_message( $notice );
} elseif ( isset( $notice ) ) {
$this->set_success_message( $notice );
}
}
/**
* On the deactivated snippets view, show a notice explaining that this view shows the snippets that have been
* automatically disabled due to throwing an error and highlight the error logging option, if disabled.
*
* @return void
*/
public function maybe_show_deactivated_notice() {
if ( ! isset( $_GET['view'] ) || 'has_error' !== $_GET['view'] ) { // phpcs:ignore WordPress.Security.NonceVerification
return;
}
// Let's see if error logging is enabled.
$logging_enabled = wpcode()->settings->get_option( 'error_logging' );
$button_text = esc_html__( 'Enable Error Logging', 'insert-headers-and-footers' );
$button_url = add_query_arg(
array(
'page' => 'wpcode-settings',
'view' => 'errors',
),
$this->admin_url( 'admin.php' )
);
?>
<div class="info fade notice">
<p>
<?php esc_html_e( 'This view lists your snippets that threw errors. Some of the snippets may have also been automatically disabled due to potentially preventing you from accessing the admin.', 'insert-headers-and-footers' ); ?>
<a href="<?php echo esc_url( wpcode_utm_url( 'https://wpcode.com/docs/php-error-handling-safe-mode/', 'snippet-deactivated-notice', 'deactivated-list' ) ); ?>" target="_blank" rel="noopener noreferrer">
<?php esc_html_e( 'Learn More', 'insert-headers-and-footers' ); ?>
</a>
</p>
<?php
if ( ! $logging_enabled ) {
?>
<p>
<?php esc_html_e( 'In order to get more info about the errors please consider enabling error logging.', 'insert-headers-and-footers' ); ?>
</p>
<p>
<a href="<?php echo esc_url( $button_url ); ?>" class="button button-primary">
<?php echo esc_html( $button_text ); ?>
</a>
</p>
<?php } ?>
</div>
<?php
}
/**
* Add the per page option to the snippets list screen.
*
* @return void
*/
public function add_per_page_option() {
add_screen_option(
'per_page',
array(
'label' => esc_html__( 'Number of snippets per page:', 'insert-headers-and-footers' ),
'option' => 'wpcode_snippets_per_page',
'default' => 20,
)
);
}
/**
* Hide the last updated column by default.
*
* @param array $hidden The hidden columns.
* @param WP_Screen $screen The current screen.
*
* @return mixed
*/
public function hide_columns( $hidden, $screen ) {
$hidden[] = 'updated';
$hidden[] = 'id';
$hidden[] = 'shortcode';
$hidden[] = 'code_type';
return $hidden;
}
/**
* Prepare the data for the admin JS localization.
*
* @param array $data The data to be localized.
*
* @return array
*/
public function prepare_admin_js_localization_data( $data ) {
$data['blocks_title'] = __( 'Blocks snippets is a Pro Feature', 'insert-headers-and-footers' );
$data['blocks_description'] = __( 'Upgrade to PRO today and unlock building snippets using the Gutenberg Block Editor. Create templates using blocks and use the full power of WPCode to insert them in your site.', 'insert-headers-and-footers' );
$data['blocks_snippet_upgrade_url'] = wpcode_utm_url( 'https://wpcode.com/lite/', 'code_type', 'blocks', 'modal' );
$data['button_text'] = __( 'Upgrade to PRO', 'insert-headers-and-footers' );
$data['scss_title'] = __( 'SCSS snippets is a Pro Feature', 'insert-headers-and-footers' );
$data['scss_description'] = __( 'Upgrade to PRO today and unlock editing snippets using SCSS code with optimized compiling directly in the WordPress admin.', 'insert-headers-and-footers' );
$data['scss_snippet_upgrade_url'] = wpcode_utm_url( 'https://wpcode.com/lite/', 'code_type', 'scss', 'modal' );
return $data;
}
/**
*
* @param string $screen_settings Screen settings.
* @param WP_Screen $screen WP_Screen object.
*
* @return string
*/
public function add_custom_screen_option( $screen_settings, $screen ) {
$order_by = get_user_option( 'wpcode_snippets_order_by' );
$order = get_user_option( 'wpcode_snippets_order' );
if ( empty( $order_by ) ) {
$order_by = 'ID';
}
if ( empty( $order ) ) {
$order = 'desc';
}
// Pick which column to order by, title, date or last updated using a select.
$screen_settings .= '<h5>' . esc_html__( 'Order Snippets By', 'insert-headers-and-footers' ) . '</h5>';
$screen_settings .= '<fieldset>';
$screen_settings .= '<legend class="screen-reader-text">' . esc_html__( 'Order snippets by', 'insert-headers-and-footers' ) . '</legend>';
// Use dropdown to choose the column to order by.
$screen_settings .= '<label for="wpcode_screen_order_by">';
$screen_settings .= '<select name="wpcode_screen_order_by" id="wpcode_screen_order_by">';
$screen_settings .= '<option value="title" ' . selected( $order_by, 'title', false ) . '>' . esc_html__( 'Name', 'insert-headers-and-footers' ) . '</option>';
$screen_settings .= '<option value="ID" ' . selected( $order_by, 'ID', false ) . '>' . esc_html__( 'Created', 'insert-headers-and-footers' ) . '</option>';
$screen_settings .= '<option value="last_updated" ' . selected( $order_by, 'last_updated', false ) . '>' . esc_html__( 'Last Updated', 'insert-headers-and-footers' ) . '</option>';
$screen_settings .= '<option value="priority" ' . selected( $order_by, 'priority', false ) . '>' . esc_html__( 'Priority', 'insert-headers-and-footers' ) . '</option>';
$screen_settings .= '</select>';
$screen_settings .= '</label>';
// Display a dropdown to choose the order.
$screen_settings .= '<label for="wpcode_screen_order">';
$screen_settings .= '<select name="wpcode_screen_order" id="wpcode_screen_order">';
$screen_settings .= '<option value="asc" ' . selected( $order, 'asc', false ) . '>' . esc_html__( 'Ascending', 'insert-headers-and-footers' ) . '</option>';
$screen_settings .= '<option value="desc" ' . selected( $order, 'desc', false ) . '>' . esc_html__( 'Descending', 'insert-headers-and-footers' ) . '</option>';
$screen_settings .= '</select>';
$screen_settings .= '</label>';
$screen_settings .= '</fieldset>';
return $screen_settings;
}
/**
* Remove the duplicated parameter from the URL.
*
* @param array $args The arguments that should be removed from the URL.
*
* @return array
*/
public function remove_query_arg_from_url( $args ) {
$args[] = 'duplicated';
return $args;
}
}
@@ -0,0 +1,165 @@
<?php
/**
* Admin page for the Duplicator tool.
*
* @package WPCode
*/
/**
* Class for the Duplicator admin page.
*/
class WPCode_Admin_Page_Duplicator extends WPCode_Admin_Page {
/**
* The page slug to be used when adding the submenu.
*
* @var string
*/
public $page_slug = 'wpcode-duplicator';
/**
* The action used for the nonce.
*
* @var string
*/
protected $action = 'wpcode-duplicator';
/**
* The nonce name field.
*
* @var string
*/
protected $nonce_name = 'wpcode-duplicator_nonce';
/**
* Call this just to set the page title translatable.
*/
public function __construct() {
$this->page_title = 'Secure Backups';
$this->menu_title = 'Secure Backups';
parent::__construct();
}
/**
* Register hook on admin init just for this page.
*
* @return void
*/
public function page_hooks() {
add_action( 'admin_init', array( $this, 'maybe_redirect_to_duplicator' ) );
}
/**
* Override to hide default header on this page.
*
* @return void
*/
public function output_header() {
}
/**
* Redirect to the Duplicator page if the plugin is active.
*
* @return void
*/
public function maybe_redirect_to_duplicator() {
if ( class_exists( 'Duplicator\Lite\Requirements' ) ) {
wp_safe_redirect( admin_url( 'admin.php?page=duplicator' ) );
exit;
} elseif ( class_exists( 'Duplicator\Pro\Requirements' ) ) {
wp_safe_redirect( admin_url( 'admin.php?page=duplicator-pro' ) );
exit;
}
}
/**
* The page output.
*
* @return void
*/
public function output_content() {
?>
<div class="wpcode-plugin-page wpcode-plugin-page-duplicator">
<div class="wpcode-plugin-page-image">
<?php wpcode_icon( 'duplicator', 90, 90, '198 55 90 396' ); ?>
</div>
<div class="wpcode-plugin-page-title">
<h1>Protect Your Website with Secure WordPress Backups</h1>
<p>
<?php esc_html_e( 'Duplicator offers cloud WordPress backups with military-grade encryption. Automatically backup your entire WordPress site to secure cloud storage.', 'insert-headers-and-footers' ); ?>
</p>
</div>
<section class="wpcode-plugin-screenshot">
<div class="wpcode-plugin-screenshot-image">
<img src="<?php echo esc_url( WPCODE_PLUGIN_URL ); // phpcs:ignore PluginCheck.CodeAnalysis.ImageFunctions.NonEnqueuedImage ?>admin/images/duplicator.png" alt="<?php esc_attr_e( 'Duplicator Screenshot', 'insert-headers-and-footers' ); ?>"/>
<a href="<?php echo esc_url( WPCODE_PLUGIN_URL ); ?>admin/images/duplicator.png" data-lity>
<?php wpcode_icon( 'search', 16, 16 ); ?>
</a>
</div>
<ul>
<li><?php esc_html_e( 'Automatic Website Backups Made Easy.', 'insert-headers-and-footers' ); ?></li>
<li><?php esc_html_e( 'Secure Cloud Storage Integration (Google Drive, AWS, Dropbox, and more).', 'insert-headers-and-footers' ); ?></li>
<li><?php esc_html_e( '1-Click Restore from Recovery Points.', 'insert-headers-and-footers' ); ?></li>
<li><?php esc_html_e( 'Website Cloning and Migration.', 'insert-headers-and-footers' ); ?></li>
<li><?php esc_html_e( 'Used by 1.5 Million websites.', 'insert-headers-and-footers' ); ?></li>
</ul>
</section>
<section class="wpcode-plugin-step wpcode-plugin-step-install">
<aside class="wpcode-plugin-page-step-num">
<?php wpcode_icon( 'step-1', 50, 50, '0 0 100 100' ); ?>
<i class="wpcode-plugin-page-step-loader wpcode-plugin-page-step-loader-hidden"></i>
</aside>
<div>
<h2>
<?php
printf(
// translators: %s is the plugin name.
esc_html__( 'Install and Activate %s', 'insert-headers-and-footers' ),
'Duplicator'
)
?>
</h2>
<p>
<?php
printf(
// translators: %s is the plugin name.
esc_html__( 'Install %s from the WordPress.org plugin repository.', 'insert-headers-and-footers' ),
'Duplicator'
)
?>
</p>
<?php
// Let's check if you can install plugins on this site.
if ( current_user_can( 'install_plugins' ) && wp_is_file_mod_allowed( 'install_plugins' ) ) {
?>
<button class="wpcode-button wpcode-button-install-plugin" data-slug="duplicator">
<?php
printf(
// translators: %s is the plugin name.
esc_html__( 'Install %s', 'insert-headers-and-footers' ),
'Duplicator'
);
?>
</button>
<?php
} else {
?>
<p>
<?php esc_html_e( 'Please ask your website administrator to install Duplicator.', 'insert-headers-and-footers' ); ?>
</p>
<?php
}
?>
</div>
</section>
</div>
<?php
}
/**
* For this page we output a title and the save button.
*
* @return void
*/
public function output_header_bottom() {
}
}
@@ -0,0 +1,269 @@
<?php
/**
* File editor page.
*
* @package WPCode
*/
/**
* Class for the file editor page.
*/
class WPCode_Admin_Page_File_Editor extends WPCode_Admin_Page {
/**
* The page slug.
*
* @var string
*/
public $page_slug = 'wpcode-file-editor';
/**
* The default view.
*
* @var string
*/
public $view = 'adstxt';
/**
* The capability required to view this page.
*
* @var string
*/
protected $capability = 'wpcode_file_editor';
/**
* WPCode_Admin_Page_File_Editor constructor.
*/
public function __construct() {
$this->page_title = __( 'File Editor', 'insert-headers-and-footers' );
parent::__construct();
}
/**
* Add codemirror settings specific to the needs for this page.
*
* @return void
*/
public function page_hooks() {
// Add the codemirror settings.
add_filter( 'wpcode_editor_config', array( $this, 'editor_config' ) );
}
/**
* Output the page content.
*
* @return void
*/
public function output_content() {
$this->can_edit = true;
echo '<div class="wpcode-blur-area" style="min-height: 700px">';
$this->file_editor_area();
echo '</div>';
echo $this->get_pixel_overlay(); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
}
/**
* File editor area.
*
* @return void
*/
public function file_editor_area() {
$value = $this->get_value();
?>
<div class="wpcode-code-textarea" id="wpcode-edit-<?php echo esc_attr( $this->view ); ?>-area" style="max-width: 1000px">
<div class="wpcode-flex">
<div class="wpcode-column">
<h2>
<label for="wpcode_file_<?php echo esc_attr( $this->view ); ?>">
<?php
printf(
// Translators: %s is the name of the file.
esc_html__( '%s Editor', 'insert-headers-and-footers' ),
esc_html( $this->views[ $this->view ] )
);
?>
</label>
</h2>
</div>
<div class="wpcode-column">
<div class="wpcode-input-select">
<label for="<?php echo esc_attr( 'wpcode_file_' . $this->view . '[enabled]' ); ?>">
<?php esc_html_e( 'Enable file output', 'insert-headers-and-footers' ); ?>
</label>
<?php
echo $this->get_checkbox_toggle( // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
$value['enabled'],
esc_attr( 'wpcode_file_' . $this->view . '[enabled]' )
)
?>
</div>
</div>
</div>
<textarea name="wpcode_file_<?php echo esc_attr( $this->view ); ?>[content]" id="wpcode_file_<?php echo esc_attr( $this->view ); ?>" class="widefat" rows="8"><?php echo esc_textarea( $value['content'] ); ?></textarea>
<p>
<?php
printf(
// Translators: %s is the name of the file.
esc_html__( 'Use this area to edit your %s file.', 'insert-headers-and-footers' ),
esc_html( $this->views[ $this->view ] )
);
?>
</p>
<p>
<?php
printf(
// Translators: %1$s is the opening link tag, %2$s is the closing link tag.
esc_html__( 'The file contents above will be used to generated a dynamic file. There is no physical file created on your server. %1$sLearn more%2$s.', 'insert-headers-and-footers' ),
'<a href="' . esc_url( wpcode_utm_url( 'https://wpcode.com/docs/file-editor/', 'file-editor', 'docs', 'learn-more' ) ) . '" target="_blank" rel="noopener noreferrer">',
'</a>'
);
?>
</p>
</div>
<?php
wp_nonce_field( 'wpcode-edit-' . $this->view, 'wpcode-edit-' . $this->view . '-nonce' );
// If we need to add page-specific content we can do this here.
if ( method_exists( $this, 'output_view_' . $this->view ) ) {
call_user_func( array( $this, 'output_view_' . $this->view ) );
}
?>
<button class="wpcode-button" type="submit" <?php echo $this->can_edit ? '' : 'disabled'; ?>>
<?php esc_html_e( 'Save Changes', 'insert-headers-and-footers' ); ?>
</button>
<a href="<?php echo esc_url( home_url() . '/' . $this->views[ $this->view ] ); ?>" class="wpcode-button wpcode-button-secondary" target="_blank" rel="noopener noreferrer">
<?php esc_html_e( 'View File', 'insert-headers-and-footers' ); ?>
</a>
<?php
}
/**
* For this page we output a menu.
*
* @return void
*/
public function output_header_bottom() {
?>
<ul class="wpcode-admin-tabs">
<?php
foreach ( $this->views as $slug => $label ) {
$class = $this->view === $slug ? 'active' : '';
?>
<li>
<a href="<?php echo esc_url( $this->get_view_link( $slug ) ); ?>" class="<?php echo esc_attr( $class ); ?>"><?php echo esc_html( $label ); ?></a>
</li>
<?php } ?>
</ul>
<?php
}
/**
* Page specific scripts. Hooked to 'admin_enqueue_scripts'.
*
* @return void
*/
public function page_scripts() {
$editor = new WPCode_Code_Editor( 'text' );
$editor->register_editor( 'wpcode_file_' . $this->view );
$editor->init_editor();
}
/**
* Disable all the codemirror settings for this page as we need a basic editor.
*
* @param array $config The WPCode editor config.
*
* @return array
*/
public function editor_config( $config ) {
if ( 'serviceworkerjs' === $this->view ) {
$config['type'] = 'text/javascript';
} else {
$config['type'] = 'shell';
$config['codemirror'] = array();
$config['showHint'] = 'false';
}
return $config;
}
/**
* Output content specific to the robots.txt file.
*
* @return void
*/
public function output_view_robotstxt() {
?>
<p>
<?php esc_html_e( 'Content added here will be appended to the robots.txt content generated by WordPress and other plugins.', 'insert-headers-and-footers' ); ?>
</p>
<?php
}
/**
* Setup page-specific views.
*
* @return void
*/
protected function setup_views() {
$this->views = array(
'adstxt' => 'ads.txt',
'appadstxt' => 'app-ads.txt',
'serviceworkerjs' => 'service-worker.js',
'robotstxt' => 'robots.txt',
);
}
/**
* Nothing to return by default.
*
* @return array
*/
public function get_value() {
return array(
'enabled' => true,
'content' => '',
);
}
/**
* Get the overlay for the file editor page.
*
* @return string
*/
public function get_pixel_overlay() {
$text = '<p>' . esc_html__( 'Simplify your website management with the WPCode File Editor! Say goodbye to the hassle of manually editing files on your server.', 'insert-headers-and-footers' ) . '<p>';
$text .= sprintf(
// translators: %1$s and %2$s are <u> tags.
'<p>' . esc_html__( 'With this powerful tool, you can easily customize crucial files like %1$sads.txt%2$s, %1$sapp-ads.txt%2$s, %1$srobots.txt%2$s, and %1$sservice-worker.js%2$s right from your WordPress admin.', 'insert-headers-and-footers' ) . '</p>',
'<u>',
'</u>'
);
return self::get_upsell_box(
__( 'File Editor is a PRO Feature', 'insert-headers-and-footers' ),
$text,
array(
'text' => esc_html__( 'Upgrade to WPCode PRO', 'insert-headers-and-footers' ),
'url' => esc_url( wpcode_utm_url( 'https://wpcode.com/lite/', 'file-editor', 'tab-' . $this->view, 'upgrade-to-pro' ) ),
),
array(
'text' => esc_html__( 'Learn More about the File Editor', 'insert-headers-and-footers' ),
'url' => esc_url( wpcode_utm_url( 'https://wpcode.com/docs/file-editor/', 'file-editor', 'tab-' . $this->view, 'learn-more' ) ),
),
array(
esc_html__( 'No manual coding, no FTP', 'insert-headers-and-footers' ),
esc_html__( 'Effortless integrations setup', 'insert-headers-and-footers' ),
esc_html__( 'Reduce the number of plugins', 'insert-headers-and-footers' ),
esc_html__( 'Prevent advertising fraud', 'insert-headers-and-footers' ),
)
);
}
}
@@ -0,0 +1,283 @@
<?php
/**
* The admin page for the snippet generator.
*
* @package WPCode
*/
/**
* Class WPCode_Admin_Page_Generator.
*/
class WPCode_Admin_Page_Generator extends WPCode_Admin_Page {
/**
* The page slug.
*
* @var string
*/
public $page_slug = 'wpcode-generator';
/**
* Generator to show, if any.
*
* @var bool|string
*/
public $generator = false;
/**
* Available generators.
*
* @var WPCode_Generator_Type[]
*/
public $generators;
/**
* Set the code type for the editor on this page.
*
* @var string
*/
public $code_type = 'php';
/**
* Set the header title based on what is displayed.
*
* @var string
*/
public $header_title;
/**
* Snippet if editing an existing, generated snippet.
*
* @var WPCode_Snippet
*/
public $snippet;
/**
* The capability required to view this page.
*
* @var string
*/
protected $capability = 'wpcode_edit_php_snippets';
/**
* Hide the generator menu item.
*
* @var bool
*/
public $hide_menu = true;
/**
* Call this just to set the page title translatable.
*/
public function __construct() {
$this->page_title = __( 'Generator', 'insert-headers-and-footers' );
$this->header_title = $this->page_title;
parent::__construct();
}
/**
* Page-specific hooks & logic.
*
* @return void
*/
public function page_hooks() {
$this->generators = wpcode()->generator()->get_all_generators();
// phpcs:disable WordPress.Security.NonceVerification.Recommended
// Let's see if we should display a generator.
if ( isset( $_GET['generator'] ) ) {
$generator = sanitize_text_field( wp_unslash( $_GET['generator'] ) );
if ( array_key_exists( $generator, $this->generators ) ) {
$this->generator = $generator;
if ( isset( $this->generators[ $generator ]->code_type ) ) {
$this->code_type = $this->generators[ $generator ]->code_type;
}
}
}
$snippet_id = isset( $_GET['snippet'] ) ? absint( $_GET['snippet'] ) : false;
if ( $snippet_id ) {
$this->snippet = new WPCode_Snippet( $snippet_id );
if ( $this->snippet->get_post_data() ) {
WPCode_Notice::add(
sprintf(
// Translators: gets replaced with the snippet title.
__( 'You are now editing the generated snippet: "%s". Updating the snippet will override any edits you made to the code.', 'insert-headers-and-footers' ),
$this->snippet->get_title()
),
'warning'
);
} else {
unset( $this->snippet );
}
}
// phpcs:enable WordPress.Security.NonceVerification.Recommended
if ( $this->generator ) {
// Translators: gets replaced with the generator name.
$this->header_title = sprintf( __( '%s Generator', 'insert-headers-and-footers' ), $this->generators[ $this->generator ]->get_title() );
}
}
/**
* Output the content of the page.
*
* @return void
*/
public function output_content() {
if ( $this->generator ) {
$this->show_generator();
} else {
$this->show_generators_list();
}
}
/**
* Show the list of generators with categories.
*
* @return void
*/
public function show_generators_list() {
$categories = wpcode()->generator()->get_categories();
?>
<div class="wpcode-items-metabox wpcode-metabox">
<?php $this->get_items_list_sidebar( $categories, __( 'All Generators', 'insert-headers-and-footers' ), __( 'Search Generators', 'insert-headers-and-footers' ) ); ?>
<div class="wpcode-items-list">
<ul class="wpcode-items-list-category">
<?php
foreach ( $this->generators as $generator ) {
$url = add_query_arg(
array(
'page' => $this->page_slug,
'generator' => $generator->get_name(),
),
admin_url( 'admin.php' )
);
$button_1 = array(
'tag' => 'a',
'url' => $url,
'text' => __( 'Generate', 'insert-headers-and-footers' ),
);
$this->get_list_item( $generator->get_name(), $generator->get_title(), $generator->get_description(), $button_1, array(), $generator->get_categories() );
}
?>
</ul>
</div>
</div>
<?php
}
/**
* Show the generator based on the param.
*
* @return void
*/
public function show_generator() {
$generator = $this->generators[ $this->generator ];
$tabs = $generator->get_tabs();
$snippet_data = array();
if ( isset( $this->snippet ) ) {
$snippet_data = $this->snippet->get_generator_data();
}
?>
<form id="wpcode_generator_form">
<div class="wpcode-items-metabox wpcode-metabox">
<div class="wpcode-items-sidebar">
<ul class="wpcode-items-categories-list wpcode-items-tabs">
<?php
$selected = key( $tabs );
foreach ( $tabs as $tab_id => $tab ) {
$class = $tab_id === $selected ? 'wpcode-active' : '';
?>
<li>
<button type="button" class="<?php echo esc_attr( $class ); ?>" data-category="<?php echo esc_attr( $tab_id ); ?>"><?php echo esc_html( $tab['label'] ); ?></button>
</li>
<?php } ?>
</ul>
</div>
<div class="wpcode-items-list">
<?php
foreach ( $tabs as $tab_id => $tab ) {
$style = $selected === $tab_id ? '' : 'display:none;';
?>
<div class="wpcode-form-tab" data-tab="<?php echo esc_attr( $tab_id ); ?>" style="<?php echo esc_attr( $style ); ?>">
<?php $generator->render_tab( $tab_id, $snippet_data ); ?>
</div>
<?php } ?>
<div class="wpcode-generator-actions">
<?php wp_nonce_field( 'wpcode_generate', 'nonce', false ); ?>
<input type="hidden" name="type" value="<?php echo esc_attr( $this->generator ); ?>"/>
<input type="hidden" name="action" value="wpcode_generate_snippet"/>
<button type="submit" class="wpcode-button wpcode-button-secondary" id="wpcode-generator-update-code"><?php esc_html_e( 'Update code', 'insert-headers-and-footers' ); ?></button>
<?php if ( ! empty( $this->snippet ) ) { ?>
<input type="hidden" name="snippet_id" value="<?php echo absint( $this->snippet->get_id() ); ?>"/>
<?php } ?>
</div>
</div>
</div>
</form>
<div class="wpcode-generator-preview">
<div class="wpcode-generator-preview-header">
<h2><?php esc_html_e( 'Code Preview', 'insert-headers-and-footers' ); ?></h2>
<?php
if ( ! empty( $this->snippet ) ) {
?>
<button type="button" class="wpcode-button" id="wpcode-generator-use-snippet"><?php esc_html_e( 'Update Snippet', 'insert-headers-and-footers' ); ?></button>
<?php } else { ?>
<button type="button" class="wpcode-button" id="wpcode-generator-use-snippet"><?php esc_html_e( 'Use Snippet', 'insert-headers-and-footers' ); ?></button>
<?php } ?>
<button class="wpcode-button wpcode-button-icon wpcode-button-secondary wpcode-copy-target" data-target="#wpcode_generator_code_preview" type="button">
<span class="wpcode-default-icon"><?php wpcode_icon( 'copy', 16, 16 ); ?></span><span class="wpcode-success-icon"><?php wpcode_icon( 'check', 16, 13 ); ?></span> <?php echo esc_html_x( 'Copy Code', 'Copy to clipboard', 'insert-headers-and-footers' ); ?>
</button>
</div>
<textarea id="wpcode_generator_code_preview"><?php echo esc_textarea( $generator->get_snippet_code() ); ?></textarea>
</div>
<script type="text/template" id="wpcode-generator-repeater-row">
<?php $this->repeater_group_template(); ?>
</script>
<?php
}
/**
* The bottom part of the header.
*
* @return void
*/
public function output_header_bottom() {
?>
<div class="wpcode-column">
<h1><?php echo esc_html( $this->header_title ); ?></h1>
</div>
<?php
}
/**
* The template for the repeater row.
*
* @return void
*/
public function repeater_group_template() {
?>
<div class="wpcode-repeater-group">
<button type="button" class="wpcode-button wpcode-button-secondary wpcode-remove-row"><?php esc_html_e( 'Remove Row', 'insert-headers-and-footers' ); ?></button>
</div>
<?php
}
/**
* Add page-specific scripts.
*
* @return void
*/
public function page_scripts() {
if ( ! $this->generator ) {
return;
}
$editor = new WPCode_Code_Editor( $this->code_type );
$editor->set_setting( 'readOnly', 'nocursor' );
$editor->register_editor( 'wpcode_generator_code_preview' );
$editor->init_editor();
wp_enqueue_script( 'jquery-ui-autocomplete' );
wp_enqueue_media();
}
}
@@ -0,0 +1,360 @@
<?php
/**
* Headers & Footers admin page.
*
* @package WPCode
*/
/**
* Class for the headers & footers admin page.
*/
class WPCode_Admin_Page_Headers_Footers extends WPCode_Admin_Page {
use WPCode_Revisions_Display_Lite;
use WPCode_WPConsent_Notice;
/**
* The page slug to be used when adding the submenu.
*
* @var string
*/
public $page_slug = 'wpcode-headers-footers';
/**
* The action used for the nonce.
*
* @var string
*/
protected $action = 'insert-headers-and-footers';
/**
* If the page should be a submenu of Settings instead of wpcode.
*
* @var bool
*/
protected $settings_submenu = false;
/**
* The nonce name field.
*
* @var string
*/
protected $nonce_name = 'insert-headers-and-footers_nonce';
/**
* The capability required to view this page.
*
* @var string
*/
protected $capability = 'wpcode_edit_html_snippets';
/**
* Call this just to set the page title translatable.
*/
public function __construct() {
if ( wpcode()->settings->get_option( 'headers_footers_mode' ) ) {
$this->settings_submenu = true;
}
$this->page_title = __( 'Header & Footer', 'insert-headers-and-footers' );
parent::__construct();
add_action( 'wpcode_admin_page_content_wpcode-headers-footers', array( $this, 'revisions_box' ), 260 );
}
/**
* Add the submenu page.
*
* @return void
*/
public function add_page() {
if ( $this->settings_submenu ) {
add_options_page(
$this->menu_title,
$this->page_title,
'wpcode_edit_snippets',
$this->page_slug,
array(
wpcode()->admin_page_loader,
'admin_menu_page',
)
);
return;
}
parent::add_page();
}
/**
* Register hook on admin init just for this page.
*
* @return void
*/
public function page_hooks() {
// The Header & Footer content is always live, so editing it requires activation rights too.
$this->can_edit = current_user_can( 'unfiltered_html', 'wpcode-editor' ) && current_user_can( 'wpcode_activate_snippets' );
add_action( 'admin_init', array( $this, 'submit_listener' ) );
$this->process_message();
}
/**
* Process messages specific to this page.
*
* @return void
*/
public function process_message() {
// phpcs:disable WordPress.Security.NonceVerification
if ( ! isset( $_GET['message'] ) ) {
return;
}
$messages = array(
1 => __( 'Headers & Footers mode activated. Use the toggle next to the Save Changes button to disable it at any time.', 'insert-headers-and-footers' ),
2 => __( 'Headers & Footers mode deactivated, if you wish to switch back please use the option on the settings page.', 'insert-headers-and-footers' ),
);
$message = absint( $_GET['message'] );
// phpcs:enable WordPress.Security.NonceVerification
if ( ! isset( $messages[ $message ] ) ) {
return;
}
$this->set_success_message( $messages[ $message ] );
}
/**
* Wrap this page in a form tag.
*
* @return void
*/
public function output() {
if ( ! $this->can_edit ) {
$this->set_error_message( __( 'Sorry, you only have read-only access to this page. Ask your administrator for assistance editing.', 'insert-headers-and-footers' ) );
$headers_footers_mode = wpcode()->settings->get_option( 'headers_footers_mode' );
// If in headers & footers mode allow them to update to disable the simple mode.
if ( ! $headers_footers_mode ) {
// If the user can't edit the values just don't load form at all.
parent::output();
return;
}
}
?>
<form action="<?php echo esc_url( $this->get_page_action_url() ); ?>" method="post">
<?php parent::output(); ?>
</form>
<?php
}
/**
* The headers & footers page output.
*
* @return void
*/
public function output_content() {
$this->notice_wpconsent();
$header_desc = sprintf(
/* translators: %s: The `<head>` tag */
esc_html__( 'These scripts will be printed in the %s section.', 'insert-headers-and-footers' ),
'<code>&lt;head&gt;</code>'
);
$body_desc = sprintf(
/* translators: %s: The `<head>` tag */
esc_html__( 'These scripts will be printed just below the opening %s tag.', 'insert-headers-and-footers' ),
'<code>&lt;body&gt;</code>'
);
$footer_desc = sprintf(
/* translators: %s: The `</body>` tag */
esc_html__( 'These scripts will be printed above the closing %s tag.', 'insert-headers-and-footers' ),
'<code>&lt;/body&gt;</code>'
);
$this->textarea_field( 'header', __( 'Header', 'insert-headers-and-footers' ), $header_desc );
if ( $this->body_supported() ) {
$this->textarea_field( 'body', __( 'Body', 'insert-headers-and-footers' ), $body_desc );
}
$this->textarea_field( 'footer', __( 'Footer', 'insert-headers-and-footers' ), $footer_desc );
wp_nonce_field( $this->action, $this->nonce_name );
}
/**
* Check if the website supports wp_body_open.
*
* @return bool
*/
public function body_supported() {
return function_exists( 'wp_body_open' ) && version_compare( get_bloginfo( 'version' ), '5.2', '>=' );
}
/**
* Standard output for a code input field.
*
* @param string $option The option name as stored in the DB.
* @param string $title The title of the input (also used as label).
* @param string $desc The description that shows up under the field.
*
* @return void
*/
public function textarea_field( $option, $title, $desc ) {
$value = wp_unslash( $this->get_option( $option ) );
?>
<div class="wpcode-code-textarea" id="wpcode-global-<?php echo esc_attr( $option ); ?>">
<h2><label for="ihaf_insert_<?php echo esc_attr( $option ); ?>"><?php echo esc_html( $title ); ?></label>
</h2>
<textarea name="ihaf_insert_<?php echo esc_attr( $option ); ?>" id="ihaf_insert_<?php echo esc_attr( $option ); ?>" class="widefat" rows="8" <?php disabled( ! $this->can_edit ); ?>><?php echo esc_html( $value ); ?></textarea>
<p>
<?php echo wp_kses( $desc, array( 'code' => array() ) ); ?>
</p>
</div>
<?php
}
/**
* Get the value of an option.
*
* @param string $option The option name.
*
* @return mixed
*/
public function get_option( $option ) {
return get_option( 'ihaf_insert_' . $option );
}
/**
* For this page we output a title and the save button.
*
* @return void
*/
public function output_header_bottom() {
$headers_footers_mode = wpcode()->settings->get_option( 'headers_footers_mode' );
$button_disabled = ! $this->can_edit && ! $headers_footers_mode ? 'disabled' : '';
?>
<div class="wpcode-column">
<h1><?php esc_html_e( 'Global Header and Footer', 'insert-headers-and-footers' ); ?></h1>
</div>
<div class="wpcode-column">
<?php $this->get_submenu_toggle(); ?>
<button class="wpcode-button" type="submit" <?php echo esc_attr( $button_disabled ); ?>>
<?php esc_html_e( 'Save Changes', 'insert-headers-and-footers' ); ?>
</button>
</div>
<?php
}
/**
* Get the toggle to disable submenu mode.
*
* @return void
*/
public function get_submenu_toggle() {
if ( ! $this->settings_submenu ) {
return;
}
?>
<div class="wpcode-simple-mode-container-button">
<label for="headers_footers_mode" class="wpcode-status-text"><?php esc_html_e( 'Simple mode', 'insert-headers-and-footers' ); ?></label>
<?php echo $this->get_checkbox_toggle( true, 'headers_footers_mode' ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
</div>
<?php
}
/**
* Page specific scripts. Hooked to 'admin_enqueue_scripts'.
*
* @return void
*/
public function page_scripts() {
$editor = new WPCode_Code_Editor();
$editor->register_editor( 'ihaf_insert_header' );
$editor->register_editor( 'ihaf_insert_footer' );
if ( $this->body_supported() ) {
$editor->register_editor( 'ihaf_insert_body' );
}
$editor->init_editor();
}
/**
* If the form is submitted attempt to save the values.
*
* @return void
*/
public function submit_listener() {
if ( ! isset( $_REQUEST[ $this->nonce_name ] ) || ! wp_verify_nonce( sanitize_key( $_REQUEST[ $this->nonce_name ] ), $this->action ) ) {
// Nonce is missing, so we're not even going to try.
return;
}
if ( $this->can_edit && isset( $_REQUEST['ihaf_insert_header'] ) && isset( $_REQUEST['ihaf_insert_footer'] ) ) {
// If they are not allowed to edit the page these should not be processed but we still allow them to save to disable the simple mode.
update_option( 'ihaf_insert_header', $_REQUEST['ihaf_insert_header'] ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.MissingUnslash, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
update_option( 'ihaf_insert_footer', $_REQUEST['ihaf_insert_footer'] ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.MissingUnslash, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
update_option( 'ihaf_insert_body', isset( $_REQUEST['ihaf_insert_body'] ) ? $_REQUEST['ihaf_insert_body'] : '' ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.MissingUnslash, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
// Clear the cache.
if ( apply_filters( 'wpcode_clear_cache_on_global_save', true ) ) {
wpcode_clear_all_plugins_page_cache( 'global' );
}
}
if ( wpcode()->settings->get_option( 'headers_footers_mode' ) && ! isset( $_REQUEST['headers_footers_mode'] ) ) {
wpcode()->settings->update_option( 'headers_footers_mode', false );
wp_safe_redirect(
add_query_arg(
array(
'page' => $this->page_slug,
'message' => 2,
),
admin_url( 'admin.php' )
)
);
exit;
}
$this->set_success_message( __( 'Settings Saved. Please don\'t forget to clear the site cache if you are using a cache plugin, so that the changes will be reflected for all users.', 'insert-headers-and-footers' ) );
}
/**
* Use a different base url when the headers_footers_mode is enabled.
*
* @return string
*/
public function get_page_action_url() {
$url = parent::get_page_action_url();
if ( ! wpcode()->settings->get_option( 'headers_footers_mode' ) ) {
return $url;
}
return str_replace( 'admin.php', 'options-general.php', $url );
}
/**
* Add the revisions box.
*
* @return void
*/
public function revisions_box() {
$html = $this->code_revisions_list_with_notice(
esc_html__( 'Code Revisions is a Pro Feature', 'insert-headers-and-footers' ),
sprintf(
'<p>%s</p>',
esc_html__( 'Upgrade to WPCode Pro today and start tracking revisions and see exactly who, when and which changes were made to global Headers & Footers scripts.', 'insert-headers-and-footers' )
),
array(
'text' => esc_html__( 'Upgrade to Pro and Unlock Revisions', 'insert-headers-and-footers' ),
'url' => wpcode_utm_url( 'https://wpcode.com/lite/', 'headers-footers', 'revisions', 'upgrade-to-pro' ),
),
array(
'text' => esc_html__( 'Learn more about all the features', 'insert-headers-and-footers' ),
'url' => wpcode_utm_url( 'https://wpcode.com/lite/', 'headers-footers', 'revisions', 'features' ),
)
);
$this->metabox(
__( 'Code Revisions', 'insert-headers-and-footers' ),
$html,
__( 'Easily switch back to a previous version of your global scripts.', 'insert-headers-and-footers' )
);
}
}
@@ -0,0 +1,246 @@
<?php
/**
* Admin page for the snippets library.
*
* @package WPCode
*/
/**
* WPCode_Admin_Page_Library class.
*/
class WPCode_Admin_Page_Library extends WPCode_Admin_Page {
use WPCode_My_Library_Markup_Lite;
/**
* The page slug.
*
* @var string
*/
public $page_slug = 'wpcode-library';
/**
* We always show the library on this page.
*
* @var bool
*/
protected $show_library = true;
/**
* The default view.
*
* @var string
*/
public $view = 'library';
/**
* The object used for loading data on this page.
*
* @var WPCode_Library
*/
protected $data_handler;
/**
* The capability required to view this page.
*
* @var string
*/
protected $capability = 'wpcode_edit_php_snippets';
/**
* Call this just to set the page title translatable.
*/
public function __construct() {
$this->page_title = __( 'Library', 'insert-headers-and-footers' );
parent::__construct();
}
/**
* Setup page-specific views.
*
* @return void
*/
protected function setup_views() {
$this->views = array(
'library' => __( 'Snippets', 'insert-headers-and-footers' ),
'my_library' => __( 'My Library', 'insert-headers-and-footers' ),
'my_favorites' => __( 'My Favorites', 'insert-headers-and-footers' ),
);
}
/**
* Add page-specific hooks.
*
* @return void
*/
public function page_hooks() {
$this->process_message();
add_action( 'admin_init', array( $this, 'maybe_add_from_library' ) );
}
/**
* Handle grabbing snippets from the library.
*
* @return void
*/
public function maybe_add_from_library() {
if ( ! isset( $_GET['_wpnonce'] ) || ! wp_verify_nonce( sanitize_key( $_GET['_wpnonce'] ), 'wpcode_add_from_library' ) ) {
return;
}
$library_id = isset( $_GET['snippet_library_id'] ) ? absint( $_GET['snippet_library_id'] ) : 0;
if ( empty( $library_id ) ) {
return;
}
$snippet = $this->get_data_handler()->create_new_snippet( $library_id );
if ( $snippet ) {
$url = add_query_arg(
array(
'page' => 'wpcode-snippet-manager',
'snippet_id' => $snippet->get_id(),
),
$this->admin_url( 'admin.php' )
);
} else {
$url = add_query_arg(
array(
'message' => 1,
),
remove_query_arg(
array(
'_wpnonce',
'snippet_library_id',
)
)
);
}
wp_safe_redirect( $url );
exit;
}
/**
* Markup for the Library page content.
*
* @return void
*/
public function output_content() {
if ( method_exists( $this, 'output_view_' . $this->view ) ) {
call_user_func( array( $this, 'output_view_' . $this->view ) );
}
}
/**
* Ouptut the library content (default view).
*
* @return void
*/
public function output_view_library() {
$library_data = $this->get_data_handler()->get_data();
$categories = $library_data['categories'];
$snippets = $library_data['snippets'];
$this->get_library_markup( $categories, $snippets );
$this->library_preview_modal_content();
$this->library_connect_banner_template();
}
/**
* For this page we output a menu.
*
* @return void
*/
public function output_header_bottom() {
?>
<ul class="wpcode-admin-tabs">
<?php
foreach ( $this->views as $slug => $label ) {
$class = $this->view === $slug ? 'active' : '';
?>
<li>
<a href="<?php echo esc_url( $this->get_view_link( $slug ) ); ?>" class="<?php echo esc_attr( $class ); ?>"><?php echo esc_html( $label ); ?></a>
</li>
<?php } ?>
</ul>
<?php
}
/**
* Process messages specific to this page.
*
* @return void
*/
public function process_message() {
// phpcs:disable WordPress.Security.NonceVerification
if ( ! isset( $_GET['message'] ) ) {
return;
}
$messages = array(
1 => __( 'We encountered an error while trying to load the snippet data. Please try again.', 'insert-headers-and-footers' ),
);
$message = absint( $_GET['message'] );
// phpcs:enable WordPress.Security.NonceVerification
if ( ! isset( $messages[ $message ] ) ) {
return;
}
$this->set_error_message( $messages[ $message ] );
}
/**
* Markup for the "My Library" page.
*
* @return void
*/
public function output_view_my_library() {
$this->get_my_library_markup();
}
/**
* Markup for the "My Library" page.
*
* @return void
*/
public function output_view_my_favorites() {
$this->blurred_placeholder_items();
// Show upsell.
echo WPCode_Admin_Page::get_upsell_box( // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
esc_html__( 'My Favorites is a PRO Feature', 'insert-headers-and-footers' ),
'<p>' . esc_html__( 'Upgrade to WPCode PRO today and see the snippets you starred in the WPCode Library directly in the plugin.', 'insert-headers-and-footers' ) . '</p>',
array(
'text' => esc_html__( 'Upgrade to PRO and Unlock "My Favorites"', 'insert-headers-and-footers' ),
'url' => esc_url( wpcode_utm_url( 'https://wpcode.com/lite/', 'library-page', 'my-favorites', 'upgrade-and-unlock' ) ),
),
array(
'text' => esc_html__( 'Learn more about all the features', 'insert-headers-and-footers' ),
'url' => esc_url( wpcode_utm_url( 'https://wpcode.com/lite/', 'library-page', 'my-favorites', 'features' ) ),
),
array(
esc_html__( 'Load favorite snippets in the plugin', 'insert-headers-and-footers' ),
esc_html__( 'Import snippets from the WPCode Library', 'insert-headers-and-footers' ),
esc_html__( 'Save your snippets to the WPCode Library', 'insert-headers-and-footers' ),
esc_html__( 'Set up new websites faster', 'insert-headers-and-footers' ),
esc_html__( 'Easily implement features on multiple sites', 'insert-headers-and-footers' ),
esc_html__( 'Edit snippets in the WPCode Library', 'insert-headers-and-footers' ),
)
);
}
/**
* Get the data handler for this page.
*
* @return WPCode_Library
*/
public function get_data_handler() {
if ( ! isset( $this->data_handler ) ) {
$this->data_handler = wpcode()->library;
}
return $this->data_handler;
}
}
@@ -0,0 +1,275 @@
<?php
/**
* Live Preview Admin Page.
*
* This page handles the split-screen CSS live preview interface.
*
* @package WPCode
*/
/**
* Class WPCode_Admin_Page_Live_Preview
*/
class WPCode_Admin_Page_Live_Preview extends WPCode_Admin_Page {
/**
* The page slug to be used when adding the submenu.
*
* @var string
*/
public $page_slug = 'wpcode-live-preview';
/**
* Hide this page from the menu.
*
* @var bool
*/
public $hide_menu = true;
/**
* The snippet ID being previewed.
*
* @var int
*/
private $snippet_id;
/**
* The snippet instance.
*
* @var WPCode_Snippet
*/
private $snippet;
/**
* The CSS code to preview.
*
* @var string
*/
private $preview_css;
/**
* Constructor.
*/
public function __construct() {
$this->page_title = __( 'Live CSS Preview', 'insert-headers-and-footers' );
parent::__construct();
}
/**
* Page-specific hooks.
*
* @return void
*/
public function page_hooks() {
// phpcs:disable WordPress.Security.NonceVerification.Recommended
if ( ! isset( $_GET['snippet_id'] ) ) {
wp_die( esc_html__( 'No snippet ID provided.', 'insert-headers-and-footers' ) );
}
if ( ! isset( $_GET['_wpnonce'] ) || ! wp_verify_nonce( sanitize_key( $_GET['_wpnonce'] ), 'wpcode-live-preview' ) ) {
wp_die( esc_html__( 'The link you followed has expired.', 'insert-headers-and-footers' ) );
}
$this->snippet_id = absint( $_GET['snippet_id'] );
// phpcs:enable WordPress.Security.NonceVerification.Recommended
if ( $this->snippet_id ? ! current_user_can( 'edit_post', $this->snippet_id ) : ! current_user_can( 'wpcode_edit_snippets' ) ) {
wp_die( esc_html__( 'Sorry, you are not allowed to do that.', 'insert-headers-and-footers' ), '', array( 'response' => 403 ) );
}
$this->snippet = wpcode_get_snippet( $this->snippet_id );
if ( ! $this->snippet ) {
wp_die( esc_html__( 'Invalid snippet ID.', 'insert-headers-and-footers' ) );
}
// Get the CSS to preview.
$this->preview_css = $this->get_snippet_css();
// Store CSS in transient for the preview frame.
$this->save_preview_css();
add_filter( 'wpcode_admin_js_data', array( $this, 'add_preview_data' ) );
}
/**
* Output the page content.
*
* @return void
*/
public function output_content() {
$preview_url = add_query_arg(
array(
'wpcode_preview' => '1',
'snippet_id' => $this->snippet_id,
),
home_url( '/' )
);
?>
<div class="wpcode-live-preview-container">
<div class="wpcode-live-preview-editor">
<div class="wpcode-live-preview-editor-header">
<h3><?php echo 'scss' === $this->snippet->get_code_type() ? esc_html__( 'SCSS Editor', 'insert-headers-and-footers' ) : esc_html__( 'CSS Editor', 'insert-headers-and-footers' ); ?></h3>
<div class="wpcode-live-preview-device-toggles">
<button type="button" class="wpcode-device-toggle wpcode-device-desktop wpcode-active" data-device="desktop" title="<?php esc_attr_e( 'Desktop View', 'insert-headers-and-footers' ); ?>">
<?php wpcode_icon( 'desktop', 20, 20, '0 0 48 48' ); ?>
</button>
<button type="button" class="wpcode-device-toggle wpcode-device-tablet" data-device="tablet" title="<?php esc_attr_e( 'Tablet View', 'insert-headers-and-footers' ); ?>">
<?php wpcode_icon( 'tablet', 20, 20, '2 1 20 20' ); ?>
</button>
<button type="button" class="wpcode-device-toggle wpcode-device-mobile" data-device="mobile" title="<?php esc_attr_e( 'Mobile View', 'insert-headers-and-footers' ); ?>">
<?php wpcode_icon( 'mobile', 20, 20, '0 0 48 48' ); ?>
</button>
</div>
</div>
<div class="wpcode-live-preview-editor-area">
<textarea id="wpcode-live-preview-css-editor" name="wpcode_live_preview_css"><?php echo esc_textarea( $this->preview_css ); ?></textarea>
</div>
</div>
<div class="wpcode-live-preview-resizer" title="<?php esc_attr_e( 'Drag to resize the editor', 'insert-headers-and-footers' ); ?>"></div>
<div class="wpcode-live-preview-iframe-wrapper wpcode-device-desktop">
<div class="wpcode-live-preview-loading">
<?php esc_html_e( 'Loading preview...', 'insert-headers-and-footers' ); ?>
</div>
<iframe id="wpcode-live-preview-frame" src="<?php echo esc_url( $preview_url ); ?>" title="<?php esc_attr_e( 'Live Preview', 'insert-headers-and-footers' ); ?>"></iframe>
</div>
</div>
<div class="wpcode-live-preview-actions">
<img id="wpcode-live-preview-logo" class="wpcode-live-preview-logo" src="<?php echo esc_url( WPCODE_PLUGIN_URL . 'admin/images/wpcode-logo.png' ); ?>" alt="<?php esc_attr_e( 'WPCode', 'insert-headers-and-footers' ); ?>" />
<button type="button" class="wpcode-button wpcode-button-secondary" id="wpcode-live-preview-discard">
<?php esc_html_e( 'Discard & Exit', 'insert-headers-and-footers' ); ?>
</button>
<button type="button" class="wpcode-button" id="wpcode-live-preview-save">
<?php esc_html_e( 'Save & Exit', 'insert-headers-and-footers' ); ?>
</button>
</div>
<?php
}
/**
* Output the header for this page.
*
* @return void
*/
public function output_header() {
// Intentionally empty - no header for the live preview page.
}
/**
* Don't output the standard footer for this page.
*
* @return void
*/
public function output_footer() {
// Intentionally empty - we don't want the standard footer overlays.
}
/**
* Enqueue page-specific scripts.
*
* @return void
*/
public function page_scripts() {
// Determine the code type (CSS or SCSS).
$code_type = $this->snippet ? $this->snippet->get_code_type() : 'css';
// The code editor.
$code_editor = new WPCode_Code_Editor( $code_type );
$code_editor->register_editor( 'wpcode-live-preview-css-editor' );
$code_editor->init_editor();
}
/**
* Add preview-specific data to the JavaScript.
*
* @param array $data The existing data.
*
* @return array
*/
public function add_preview_data( $data ) {
$data['livePreview'] = array(
'snippetId' => $this->snippet_id,
'editorId' => 'wpcode-live-preview-css-editor',
'iframeId' => 'wpcode-live-preview-frame',
'snippetUrl' => add_query_arg(
array(
'page' => 'wpcode-snippet-manager',
'snippet_id' => $this->snippet_id,
),
admin_url( 'admin.php' )
),
'hasChanges' => false,
'exitConfirm' => __( 'You have unsaved changes. Are you sure you want to exit?', 'insert-headers-and-footers' ),
'codeType' => $this->snippet ? $this->snippet->get_code_type() : 'css',
);
return $data;
}
/**
* Get the CSS/SCSS code to preview.
*
* @return string
*/
private function get_snippet_css() {
$user_id = get_current_user_id();
$code_type = $this->snippet->get_code_type();
// For SCSS snippets, check for unsaved SCSS source first.
if ( 'scss' === $code_type ) {
$source_transient_key = "wpcode_preview_scss_source_{$user_id}_{$this->snippet_id}";
$transient_source = get_transient( $source_transient_key );
if ( false !== $transient_source ) {
return $transient_source;
}
} else {
// For CSS snippets, check if there's unsaved CSS in the transient.
$transient_key = "wpcode_preview_css_{$user_id}_{$this->snippet_id}";
$transient_css = get_transient( $transient_key );
if ( false !== $transient_css ) {
return $transient_css;
}
}
// Otherwise, get the code from the snippet.
return $this->snippet->get_code();
}
/**
* Save the preview CSS to a transient.
*
* @return void
*/
private function save_preview_css() {
$user_id = get_current_user_id();
$code_type = $this->snippet->get_code_type();
// For SCSS, store the source code in the source transient.
// The compiled CSS will be generated client-side and stored separately.
if ( 'scss' === $code_type ) {
$source_transient_key = "wpcode_preview_scss_source_{$user_id}_{$this->snippet_id}";
set_transient( $source_transient_key, $this->preview_css, HOUR_IN_SECONDS );
} else {
// For CSS, store directly.
$transient_key = "wpcode_preview_css_{$user_id}_{$this->snippet_id}";
set_transient( $transient_key, $this->preview_css, HOUR_IN_SECONDS );
}
}
/**
* Add a body class specific to the live preview page.
*
* @param string $body_class The existing body classes.
*
* @return string
*/
public function page_specific_body_class( $body_class ) {
$body_class = parent::page_specific_body_class( $body_class );
$body_class .= ' wpcode-live-preview-page';
return $body_class;
}
}
@@ -0,0 +1,919 @@
<?php
/**
* The Conversion Pixels page.
*
* @package WPCode
*/
/**
* Class WPCode_Admin_Page_Pixel.
*/
class WPCode_Admin_Page_Pixel extends WPCode_Admin_Page {
use WPCode_WPConsent_Notice;
/**
* The page slug to be used when adding the submenu.
*
* @var string
*/
public $page_slug = 'wpcode-pixel';
/**
* Default view.
*
* @var string
*/
public $view = 'facebook';
/**
* The capability required to view this page.
*
* @var string
*/
protected $capability = 'wpcode_manage_conversion_pixels';
/**
* Call this just to set the page title translatable.
*/
public function __construct() {
$this->page_title = __( 'Conversion Pixels', 'insert-headers-and-footers' );
parent::__construct();
}
/**
* The Conversion Pixels page output.
*
* @return void
*/
public function output_content() {
$this->notice_wpconsent();
if ( method_exists( $this, 'output_view_' . $this->view ) ) {
echo '<div class="wpcode-blur-area">';
call_user_func( array( $this, 'output_view_' . $this->view ) );
echo '</div>';
echo $this->get_pixel_overlay(); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
}
}
/**
* Get the overlay for the pixel settings.
*
* @return string
*/
public function get_pixel_overlay() {
$text = sprintf(
// translators: %1$s and %2$s are <u> tags.
'<p>' . esc_html__( 'While you can always add pixels manually using code snippets, our Conversion Pixels addon helps you %1$ssave time%2$s while %1$sreducing errors%2$s. It lets you properly implement Facebook, Google, Pinterest, TikTok, Snapchat and OpenAI ads tracking with deep integrations for eCommerce events, interaction measurement, and more. This addon is available on WPCode Plus plan or higher.', 'insert-headers-and-footers' ) . '</p>',
'<u>',
'</u>'
);
return self::get_upsell_box(
esc_html__( 'Conversion Pixels Addon is a PRO Feature', 'insert-headers-and-footers' ),
$text,
array(
'text' => esc_html__( 'Upgrade to WPCode PRO', 'insert-headers-and-footers' ),
'url' => esc_url( wpcode_utm_url( 'https://wpcode.com/lite/', 'conversion-pixels', 'tab-' . $this->view, 'upgrade-to-pro' ) ),
),
array(),
array(
esc_html__( 'Seamless integration with WooCommerce, Easy Digital Downloads and MemberPress', 'insert-headers-and-footers' ),
esc_html__( 'Works with Facebook, Google Ads, Pinterest, TikTok, Snapchat and OpenAI', 'insert-headers-and-footers' ),
esc_html__( 'No coding required', 'insert-headers-and-footers' ),
esc_html__( '1-click setup for conversion tracking', 'insert-headers-and-footers' ),
)
);
}
/**
* Setup page-specific views.
*
* @return void
*/
protected function setup_views() {
$this->views = array(
'facebook' => __( 'Facebook', 'insert-headers-and-footers' ),
'google' => __( 'Google', 'insert-headers-and-footers' ),
'pinterest' => __( 'Pinterest', 'insert-headers-and-footers' ),
'tiktok' => __( 'TikTok', 'insert-headers-and-footers' ),
'snapchat' => __( 'Snapchat', 'insert-headers-and-footers' ),
'openai' => __( 'OpenAI', 'insert-headers-and-footers' ),
'click_tracking' => __( 'Click Tracking', 'insert-headers-and-footers' ),
);
}
/**
* For this page we output a menu.
*
* @return void
*/
public function output_header_bottom() {
?>
<ul class="wpcode-admin-tabs">
<?php
foreach ( $this->views as $slug => $label ) {
$class = $this->view === $slug ? 'active' : '';
?>
<li>
<a href="<?php echo esc_url( $this->get_view_link( $slug ) ); ?>" class="<?php echo esc_attr( $class ); ?>"><?php echo esc_html( $label ); ?></a>
</li>
<?php } ?>
</ul>
<?php
}
/**
* Form for Facebook Pixel.
*
* @return void
*/
public function output_view_facebook() {
?>
<h2><?php esc_html_e( 'Facebook Pixel', 'insert-headers-and-footers' ); ?></h2>
<?php
$this->metabox_row(
__( 'Facebook Pixel ID', 'insert-headers-and-footers' ),
$this->get_input_text(
'facebook_pixel_id',
$this->get_option( 'facebook_pixel_id', '' ),
sprintf(
// translators: %1$s and %2$s are the opening and closing anchor tags.
__( 'You can find your Facebook Pixel ID in the Facebook Ads Manager. %1$sRead our step by step directions%2$s. ', 'insert-headers-and-footers' ),
'<a target="_blank" href="' . wpcode_utm_url( 'https://wpcode.com/docs/how-to-find-your-facebook-pixel-id-and-conversions-api-token/', 'conversion-pixels', 'facebook', 'pixel' ) . '">',
'</a>'
)
),
'facebook_pixel_id'
);
$this->metabox_row(
__( 'Conversions API Token', 'insert-headers-and-footers' ),
$this->get_input_text(
'facebook_pixel_api_token',
$this->get_option( 'facebook_pixel_api_token', '' ),
__( 'The Conversions API token allows you to send API events that are more reliable and can improve audience targeting.', 'insert-headers-and-footers' ),
true
),
'facebook_pixel_api_token'
);
?>
<button type="button" class="wpcode-button wpcode-button-secondary wpcode-add-pixel"><?php esc_html_e( 'Add Another Pixel', 'insert-headers-and-footers' ); ?></button>
<?php
$this->metabox_row(
__( 'Facebook Pixel Events', 'insert-headers-and-footers' ),
$this->get_checkbox_inputs(
array(
array(
'label' => __( 'PageView Event', 'insert-headers-and-footers' ),
'name' => 'page_view',
'description' => __( 'Enable the PageView event to track and record page visits on all the pages of your website using the Facebook Pixel.', 'insert-headers-and-footers' ),
'ecommerce' => false,
),
),
'facebook_pixel_events'
)
);
$this->metabox_row(
__( 'eCommerce Events Tracking', 'insert-headers-and-footers' ),
$this->get_ecommerce_events_input() . $this->get_checkbox_inputs( $this->get_fb_pixel_events_inputs(), 'facebook_pixel_events' )
);
wp_nonce_field( 'wpcode-save-facebook-pixel-data', 'wpcode-pixel-nonce' );
?>
<button type="submit" class="wpcode-button">
<?php esc_html_e( 'Save Changes', 'insert-headers-and-footers' ); ?>
</button>
<?php
}
/**
* Form for Google Pixel.
*
* @return void
*/
public function output_view_google() {
?>
<h2><?php esc_html_e( 'Google Analytics & Ads Tracking', 'insert-headers-and-footers' ); ?></h2>
<?php
$this->metabox_row(
__( 'Google Analytics ID', 'insert-headers-and-footers' ),
$this->get_input_text(
'google_analytics_id',
$this->get_option( 'google_analytics_id', '' ),
sprintf(
// translators: %1$s and %2$s are the opening and closing anchor tags.
__( 'You can find your Google Analytics ID in the Google Analytics Admin panel. %1$sRead our step by step directions%2$s. ', 'insert-headers-and-footers' ),
'<a target="_blank" href="' . wpcode_utm_url( 'https://wpcode.com/docs/how-to-find-your-google-analytics-id/', 'conversion-pixels', 'google', 'pixel' ) . '">',
'</a>'
)
),
'google_analytics_id'
);
$this->metabox_row(
__( 'Google Ads Tag ID', 'insert-headers-and-footers' ),
$this->get_input_text(
'google_ads_id',
$this->get_option( 'google_ads_id', '' ),
sprintf(
// translators: %1$s and %2$s are the opening and closing anchor tags.
__( 'You can find your Google Ads Tag ID in the Google Ads Settings under Google Tag. %1$sRead our step by step directions%2$s. ', 'insert-headers-and-footers' ),
'<a target="_blank" href="' . wpcode_utm_url( 'https://wpcode.com/docs/how-to-find-your-google-ads-tag-id/', 'conversion-pixels', 'google', 'pixel' ) . '">',
'</a>'
)
),
'google_ads_id'
);
$this->metabox_row(
__( 'Ads Conversion Label', 'insert-headers-and-footers' ),
$this->get_input_text(
'google_ads_label',
$this->get_option( 'google_ads_label', '' ),
sprintf(
// translators: %1$s and %2$s are the opening and closing anchor tags.
__( 'Add your Google Ads Conversion Label for tracking conversion events. %1$sLearn More%2$s.', 'insert-headers-and-footers' ),
'<a target="_blank" href="' . wpcode_utm_url( 'https://wpcode.com/docs/how-to-find-your-google-ads-tag-id/', 'conversion-pixels', 'google', 'pixel' ) . '">',
'</a>'
)
),
'google_ads_label'
);
?>
<button type="button" class="wpcode-button wpcode-button-secondary wpcode-add-pixel"><?php esc_html_e( 'Add Google ID', 'insert-headers-and-footers' ); ?></button>
<?php
$this->metabox_row(
__( 'Google Events', 'insert-headers-and-footers' ),
$this->get_checkbox_inputs(
array(
array(
'label' => __( 'PageView Event', 'insert-headers-and-footers' ),
'name' => 'page_view',
'description' => __( 'Enable PageView event on all pages.', 'insert-headers-and-footers' ),
'ecommerce' => false,
),
),
'google_pixel_events'
)
);
$this->metabox_row(
__( 'eCommerce Events Tracking', 'insert-headers-and-footers' ),
$this->get_ecommerce_events_input() . $this->get_checkbox_inputs( $this->get_google_pixel_events_inputs(), 'google_pixel_events' )
);
wp_nonce_field( 'wpcode-save-google-pixel-data', 'wpcode-pixel-nonce' );
?>
<button type="submit" class="wpcode-button">
<?php esc_html_e( 'Save Changes', 'insert-headers-and-footers' ); ?>
</button>
<?php
}
/**
* Settings for the Pinterest pixel.
*
* @return void
*/
public function output_view_pinterest() {
?>
<h2><?php esc_html_e( 'Pinterest Tag', 'insert-headers-and-footers' ); ?></h2>
<?php
$this->metabox_row(
__( 'Tag ID', 'insert-headers-and-footers' ),
$this->get_input_text(
'pinterest_id',
$this->get_option( 'pinterest_id', '' ),
sprintf(
// translators: %1$s and %2$s are the opening and closing anchor tags.
__( 'You can find your Tag id in your Pinterest Business account. %1$sRead our step by step directions%2$s. ', 'insert-headers-and-footers' ),
'<a target="_blank" href="' . wpcode_utm_url( 'https://wpcode.com/docs/how-to-find-your-pinterest-tag-id-and-conversion-access-token/', 'conversion-pixels', 'pinterest', 'pixel' ) . '">',
'</a>'
)
),
'pinterest_id'
);
$this->metabox_row(
__( 'Ad Account ID', 'insert-headers-and-footers' ),
$this->get_input_text(
'pinterest_ad_account_id',
$this->get_option( 'pinterest_ad_account_id', '' ),
sprintf(
// translators: %1$s and %2$s are the opening and closing anchor tags.
__( 'You can find your Ad Account ID in your Pinterest Business account. %1$sRead more%2$s. ', 'insert-headers-and-footers' ),
'<a target="_blank" href="' . wpcode_utm_url( 'https://wpcode.com/docs/how-to-find-your-pinterest-tag-id-and-conversion-access-token/', 'conversion-pixels', 'pinterest', 'pixel' ) . '">',
'</a>'
)
),
'pinterest_ad_account_id'
);
$this->metabox_row(
__( 'Conversion Access Token', 'insert-headers-and-footers' ),
$this->get_input_text(
'pinterest_conversion_token',
$this->get_option( 'pinterest_conversion_token', '' ),
sprintf(
// translators: %1$s and %2$s are the opening and closing anchor tags.
__( 'You can find your Conversion Access Token under Ads > Conversions > Conversion access token. %1$sRead more%2$s. ', 'insert-headers-and-footers' ),
'<a target="_blank" href="' . wpcode_utm_url( 'https://wpcode.com/docs/how-to-find-your-pinterest-tag-id-and-conversion-access-token/', 'conversion-pixels', 'pinterest', 'pixel' ) . '">',
'</a>'
),
true
),
'pinterest_conversion_token'
);
$this->metabox_row(
__( 'eCommerce Events Tracking', 'insert-headers-and-footers' ),
$this->get_ecommerce_events_input() . $this->get_checkbox_inputs( $this->get_pinterest_pixel_events_inputs(), 'pinterest_pixel_events' )
);
wp_nonce_field( 'wpcode-save-pinterest-pixel-data', 'wpcode-pixel-nonce' );
?>
<button type="submit" class="wpcode-button">
<?php esc_html_e( 'Save Changes', 'insert-headers-and-footers' ); ?>
</button>
<?php
}
/**
* Settings for the Pinterest pixel.
*
* @return void
*/
public function output_view_tiktok() {
?>
<h2><?php esc_html_e( 'TikTok Pixel', 'insert-headers-and-footers' ); ?></h2>
<?php
$this->metabox_row(
__( 'Pixel ID', 'insert-headers-and-footers' ),
$this->get_input_text(
'tiktok_pixel_id',
$this->get_option( 'tiktok_pixel_id', '' ),
sprintf(
// translators: %1$s and %2$s are the opening and closing anchor tags.
__( 'You can find your Pixel id in your TikTok Business Account. %1$sRead our step by step directions%2$s.', 'insert-headers-and-footers' ),
'<a target="_blank" href="' . wpcode_utm_url( 'https://wpcode.com/docs/how-to-find-your-tiktok-pixel-id-and-events-api-access-token/', 'conversion-pixels', 'tiktok', 'pixel' ) . '">',
'</a>'
)
),
'tiktok_pixel_id'
);
$this->metabox_row(
__( 'Events API Access Token', 'insert-headers-and-footers' ),
$this->get_input_text(
'tiktok_access_token',
$this->get_option( 'tiktok_access_token', '' ),
sprintf(
// translators: %1$s and %2$s are the opening and closing anchor tags.
__( 'You can generate an access token in the Pixel Settings under Access Token Generation. %1$sRead more%2$s', 'insert-headers-and-footers' ),
'<a target="_blank" href="' . wpcode_utm_url( 'https://wpcode.com/docs/how-to-find-your-tiktok-pixel-id-and-events-api-access-token/', 'conversion-pixels', 'tiktok', 'pixel' ) . '">',
'</a>'
),
true
),
'tiktok_access_token'
);
$this->metabox_row(
__( 'eCommerce Events Tracking', 'insert-headers-and-footers' ),
$this->get_ecommerce_events_input() . $this->get_checkbox_inputs( $this->get_tiktok_pixel_events_inputs(), 'tiktok_pixel_events' )
);
wp_nonce_field( 'wpcode-save-tiktok-pixel-data', 'wpcode-pixel-nonce' );
?>
<button type="submit" class="wpcode-button">
<?php esc_html_e( 'Save Changes', 'insert-headers-and-footers' ); ?>
</button>
<?php
}
/**
* Page for Snapchat pixel settings.
*
* @return void
*/
public function output_view_snapchat() {
?>
<h2><?php esc_html_e( 'Snapchat Pixel', 'insert-headers-and-footers' ); ?></h2>
<?php
$this->metabox_row(
__( 'Snap Pixel ID', 'insert-headers-and-footers' ),
$this->get_input_text(
'snapchat_pixel_id',
$this->get_option( 'snapchat_pixel_id', '' ),
sprintf(
// translators: %1$s and %2$s are the opening and closing anchor tags.
__( 'You can find your Snapchat Pixel ID in the Snapchat Ads Manager. %1$sRead our step by step directions%2$s. ', 'insert-headers-and-footers' ),
'<a target="_blank" href="' . wpcode_utm_url( 'https://wpcode.com/docs/how-to-find-your-snapchat-pixel-id-and-conversions-api-token/', 'conversion-pixels', 'snapchat', 'pixel' ) . '">',
'</a>'
),
true
),
'snapchat_pixel_id'
);
$this->metabox_row(
__( 'Conversions API Token', 'insert-headers-and-footers' ),
$this->get_input_text(
'snapchat_pixel_api_token',
$this->get_option( 'snapchat_pixel_api_token', '' ),
__( 'The Conversions API token allows you to send API events that are more reliable and can improve audience targeting.', 'insert-headers-and-footers' ),
true
),
'snapchat_pixel_api_token'
);
$this->metabox_row(
__( 'Snapchat Pixel Events', 'insert-headers-and-footers' ),
$this->get_checkbox_inputs(
array(
array(
'label' => __( 'Pave View Event', 'insert-headers-and-footers' ),
'name' => 'page_view',
'description' => __( 'Enable the PAGE_VIEW event to track and record page visits on all the pages of your website using the Snapchat Pixel.', 'insert-headers-and-footers' ),
'ecommerce' => false,
),
),
'snapchat_pixel_events'
)
);
$this->metabox_row(
__( 'eCommerce Events Tracking', 'insert-headers-and-footers' ),
$this->get_ecommerce_events_input() . $this->get_checkbox_inputs( $this->get_snap_pixel_events_inputs(), 'snapchat_pixel_events' )
);
wp_nonce_field( 'wpcode-save-snapchat-pixel-data', 'wpcode-pixel-nonce' );
?>
<button type="submit" class="wpcode-button">
<?php esc_html_e( 'Save Changes', 'insert-headers-and-footers' ); ?>
</button>
<?php
}
/**
* Page for OpenAI pixel settings.
*
* @return void
*/
public function output_view_openai() {
?>
<h2><?php esc_html_e( 'OpenAI Ads Measurement Pixel', 'insert-headers-and-footers' ); ?></h2>
<?php
$this->metabox_row(
__( 'OpenAI Pixel ID', 'insert-headers-and-footers' ),
$this->get_input_text(
'openai_pixel_id',
$this->get_option( 'openai_pixel_id', '' ),
__( 'Enter the Pixel ID from OpenAI Ads Manager to load the OpenAI Ads Measurement Pixel on your site.', 'insert-headers-and-footers' ),
true
),
'openai_pixel_id'
);
$this->metabox_row(
__( 'OpenAI Conversion Key', 'insert-headers-and-footers' ),
$this->get_input_text(
'openai_pixel_api_key',
$this->get_option( 'openai_pixel_api_key', '' ),
__( 'Enter the Conversion Key from your OpenAI Ads Manager > Conversions tab to send matching server-side events. This is not your platform API key.', 'insert-headers-and-footers' ),
true
),
'openai_pixel_api_key'
);
$this->metabox_row(
__( 'OpenAI Pixel Events', 'insert-headers-and-footers' ),
$this->get_checkbox_inputs(
array(
array(
'label' => __( 'Page Viewed Event', 'insert-headers-and-footers' ),
'name' => 'page_view',
'description' => __( 'Enable the "page_viewed" event to track and record page visits on all pages using the OpenAI Ads Measurement Pixel.', 'insert-headers-and-footers' ),
'ecommerce' => false,
),
),
'openai_pixel_events'
)
);
$this->metabox_row(
__( 'eCommerce Events Tracking', 'insert-headers-and-footers' ),
$this->get_ecommerce_events_input() . $this->get_checkbox_inputs( $this->get_openai_pixel_events_inputs(), 'openai_pixel_events' )
);
wp_nonce_field( 'wpcode-save-openai-pixel-data', 'wpcode-pixel-nonce' );
?>
<button type="submit" class="wpcode-button">
<?php esc_html_e( 'Save Changes', 'insert-headers-and-footers' ); ?>
</button>
<?php
}
/**
* Event options checkboxes for Facebook Pixel.
*
* @return array[]
*/
public function get_fb_pixel_events_inputs() {
return array(
array(
'label' => __( 'ViewContent Event', 'insert-headers-and-footers' ),
'name' => 'view_content',
'description' => __( 'Turn on the "ViewContent" event to track views of product pages on your website.', 'insert-headers-and-footers' ),
'ecommerce' => true,
'css_class' => 'view-content',
),
array(
'label' => __( 'AddtoCart Event', 'insert-headers-and-footers' ),
'name' => 'add_to_cart',
'description' => __( 'Turn on the "AddToCart" event to track when items are added to a shopping cart on your website.', 'insert-headers-and-footers' ),
'ecommerce' => true,
'css_class' => 'add-to-cart',
),
array(
'label' => __( 'InitiateCheckout Event', 'insert-headers-and-footers' ),
'name' => 'begin_checkout',
'description' => __( 'Turn on the "InitiateCheckout" event to track when a user reaches the checkout page on your website.', 'insert-headers-and-footers' ),
'ecommerce' => true,
'css_class' => 'begin-checkout',
),
array(
'label' => __( 'Purchase Event', 'insert-headers-and-footers' ),
'name' => 'purchase',
'description' => __( 'Turn on the "Purchase" event to track successful purchases on your website.', 'insert-headers-and-footers' ),
'ecommerce' => true,
'css_class' => 'purchase',
),
);
}
/**
* Events checkboxes for Google Analytics & Ads.
*
* @return array[]
*/
public function get_google_pixel_events_inputs() {
return array(
array(
'label' => __( 'View Item Event', 'insert-headers-and-footers' ),
'name' => 'view_item',
'description' => __( 'Send the View Item event to track views of product pages on your website.', 'insert-headers-and-footers' ),
'ecommerce' => true,
'css_class' => 'view-content',
),
array(
'label' => __( 'Add to Cart Event', 'insert-headers-and-footers' ),
'name' => 'add_to_cart',
'description' => __( 'Send the Add to Cart event when a product is added to the cart.', 'insert-headers-and-footers' ),
'ecommerce' => true,
'css_class' => 'add-to-cart',
),
array(
'label' => __( 'Begin Checkout Event', 'insert-headers-and-footers' ),
'name' => 'begin_checkout',
'description' => __( 'Send the Begin Checkout event when the user sees the checkout page.', 'insert-headers-and-footers' ),
'ecommerce' => true,
'css_class' => 'begin-checkout',
),
array(
'label' => __( 'Purchase Event', 'insert-headers-and-footers' ),
'name' => 'purchase',
'description' => __( 'Send the Purchase event when the user completes a purchase.', 'insert-headers-and-footers' ),
'ecommerce' => true,
'css_class' => 'purchase',
),
array(
'label' => __( 'Conversion Event', 'insert-headers-and-footers' ),
'name' => 'conversion',
'description' => __( 'Send the conversion event with the Google Ads label set above on a successful purchase.', 'insert-headers-and-footers' ),
'ecommerce' => true,
'css_class' => 'conversion',
),
);
}
/**
* Events checkboxes for Pinterest.
*
* @return array[]
*/
public function get_pinterest_pixel_events_inputs() {
return array(
array(
'label' => __( 'PageVisit Product Event', 'insert-headers-and-footers' ),
'name' => 'pagevisit_product',
'description' => __( 'Turn on the "PageVisit" event to track views of product pages on your website.', 'insert-headers-and-footers' ),
'ecommerce' => true,
'css_class' => 'view-content ',
),
array(
'label' => __( 'Add to Cart Event', 'insert-headers-and-footers' ),
'name' => 'add_to_cart',
'description' => __( 'Turn on the Add to Cart event to track when items are added to a shopping cart on your website.', 'insert-headers-and-footers' ),
'ecommerce' => true,
'css_class' => 'add-to-cart',
),
array(
'label' => __( 'Checkout PageVisit Event', 'insert-headers-and-footers' ),
'name' => 'begin_checkout',
'description' => __( 'Enable the Checkout PageVisit event to track when a user reaches the checkout page on your website.', 'insert-headers-and-footers' ),
'ecommerce' => true,
'css_class' => 'begin-checkout',
),
array(
'label' => __( 'Checkout Event', 'insert-headers-and-footers' ),
'name' => 'purchase',
'description' => __( 'Turn on the "Checkout" event to track successful purchases on your website.', 'insert-headers-and-footers' ),
'ecommerce' => true,
'css_class' => 'purchase',
),
);
}
/**
* Events checkboxes for TikTok.
*
* @return array[]
*/
public function get_tiktok_pixel_events_inputs() {
return array(
array(
'label' => __( 'ViewContent Product Event', 'insert-headers-and-footers' ),
'name' => 'view_content',
'description' => __( 'Turn on the "ViewContent" event to track views of product pages on your website.', 'insert-headers-and-footers' ),
'ecommerce' => true,
'css_class' => 'view-content',
),
array(
'label' => __( 'Add to Cart Event', 'insert-headers-and-footers' ),
'name' => 'add_to_cart',
'description' => __( 'Turn on the "AddToCart" event to track when items are added to a shopping cart on your website.', 'insert-headers-and-footers' ),
'ecommerce' => true,
'css_class' => 'add-to-cart',
),
array(
'label' => __( 'InitiateCheckout Event', 'insert-headers-and-footers' ),
'name' => 'begin_checkout',
'description' => __( 'Turn on the "InitiateCheckout" event to track when a user reaches the checkout page on your website.', 'insert-headers-and-footers' ),
'ecommerce' => true,
'css_class' => 'begin-checkout',
),
array(
'label' => __( 'PlaceAnOrder Event', 'insert-headers-and-footers' ),
'name' => 'purchase',
'description' => __( 'Turn on the "PlaceAnOrder" event to track successful purchases on your website.', 'insert-headers-and-footers' ),
'ecommerce' => true,
'css_class' => 'purchase',
),
);
}
/**
* Get the markup for a list of checkboxes.
*
* @param array $inputs The details for the checkbox inputs.
* @param string $name The name of the inputs.
* @param string $pixel_options_key The key of the pixel options (defaults to $name above if not set).
*
* @return string
*/
public function get_checkbox_inputs( $inputs, $name, $pixel_options_key = '' ) {
$markup = '';
if ( empty( $pixel_options_key ) ) {
$pixel_options_key = $name;
}
$pixel_options = $this->get_option( $pixel_options_key, array() );
$ecommerce_vendors = $this->ecommerce_available();
foreach ( $inputs as $input ) {
$row_class = isset( $input['css_class'] ) ? $input['css_class'] : '';
$input_name = $name . '[' . $input['name'] . ']';
$checked = ! empty( $pixel_options[ $input['name'] ] );
if ( $input['ecommerce'] && empty( $ecommerce_vendors ) ) {
$row_class = ' wpcode-checkbox-row-disabled';
}
$markup .= '<div class="wpcode-checkbox-row ' . $row_class . '">';
$markup .= $this->get_checkbox_toggle(
$checked,
$input_name,
$input['description'],
1,
$input['label']
);
$markup .= '</div>';
}
return $markup;
}
/**
* There's no actual value to show in this instance.
*
* @param string $key The key of the option.
* @param mixed $default The default value of the option.
*
* @return mixed
*/
public function get_option( $key, $default = false ) {
return $default;
}
/**
* Whether we have a supported eCommerce plugin installed.
*
* @return array
*/
public function ecommerce_available() {
return array();
}
/**
* Get the markup for the eCommerce events input.
*
* @return string
*/
public function get_ecommerce_events_input() {
$providers = $this->ecommerce_available();
$markup = '<div class="wpcode-label-text-row">';
if ( empty( $providers ) ) {
$markup .= '<p><strong>' . __( 'Disabled, no eCommerce Platform Detected', 'insert-headers-and-footers' ) . '</strong></p>';
} else {
foreach ( $providers as $provider ) {
// translators: %s is the name of the eCommerce provider.
$markup .= '<p><strong>' . sprintf( __( '%s Tracking Enabled', 'insert-headers-and-footers' ), $provider ) . '</strong></p>';
}
}
$markup .= '<p>';
$markup .= sprintf(
// translators: %s a html break.
__( 'Advanced eCommerce tracking is available for WooCommerce, Easy Digital Downloads and MemberPress. %s These plugins are detected automatically and when available you can toggle individual events using the options below.', 'insert-headers-and-footers' ),
'</br>'
);
$markup .= '</p>';
$markup .= '</div>';
return $markup;
}
/**
* Event options checkboxes for the Snapchat Pixel.
*
* @return array[]
*/
public function get_snap_pixel_events_inputs() {
return array(
array(
'label' => __( 'View Content Event', 'insert-headers-and-footers' ),
'name' => 'view_content',
'description' => __( 'Turn on the "VIEW_CONTENT" event to track views of product pages on your website.', 'insert-headers-and-footers' ),
'ecommerce' => true,
'css_class' => 'view-content',
),
array(
'label' => __( 'Add to Cart Event', 'insert-headers-and-footers' ),
'name' => 'add_to_cart',
'description' => __( 'Turn on the "ADD_CART" event to track when items are added to a shopping cart on your website.', 'insert-headers-and-footers' ),
'ecommerce' => true,
'css_class' => 'add-to-cart',
),
array(
'label' => __( 'Start Checkout Event', 'insert-headers-and-footers' ),
'name' => 'begin_checkout',
'description' => __( 'Turn on the "START_CHECKOUT" event to track when a user reaches the checkout page on your website.', 'insert-headers-and-footers' ),
'ecommerce' => true,
'css_class' => 'begin-checkout',
),
array(
'label' => __( 'Purchase Event', 'insert-headers-and-footers' ),
'name' => 'purchase',
'description' => __( 'Turn on the "PURCHASE" event to track successful purchases on your website.', 'insert-headers-and-footers' ),
'ecommerce' => true,
'css_class' => 'purchase',
),
);
}
/**
* Event options checkboxes for the OpenAI Ads Measurement Pixel.
*
* @return array[]
*/
public function get_openai_pixel_events_inputs() {
return array(
array(
'label' => __( 'Contents Viewed Event', 'insert-headers-and-footers' ),
'name' => 'view_content',
'description' => __( 'Turn on the "contents_viewed" event to track views of product pages on your website.', 'insert-headers-and-footers' ),
'ecommerce' => true,
'css_class' => 'view-content',
),
array(
'label' => __( 'Items Added Event', 'insert-headers-and-footers' ),
'name' => 'add_to_cart',
'description' => __( 'Turn on the "items_added" event to track when items are added to a shopping cart on your website.', 'insert-headers-and-footers' ),
'ecommerce' => true,
'css_class' => 'add-to-cart',
),
array(
'label' => __( 'Checkout Started Event', 'insert-headers-and-footers' ),
'name' => 'begin_checkout',
'description' => __( 'Turn on the "checkout_started" event to track when a user reaches the checkout page on your website.', 'insert-headers-and-footers' ),
'ecommerce' => true,
'css_class' => 'begin-checkout',
),
array(
'label' => __( 'Order Created Event', 'insert-headers-and-footers' ),
'name' => 'purchase',
'description' => __( 'Turn on the "order_created" event to track successful purchases on your website.', 'insert-headers-and-footers' ),
'ecommerce' => true,
'css_class' => 'purchase',
),
);
}
/**
* This is the page content for the Custom Events page.
*
* @return void
*/
public function output_view_click_tracking() {
?>
<h2><?php esc_html_e( 'Custom Click Tracking', 'insert-headers-and-footers' ); ?></h2>
<p>
<?php
printf(
/* Translators: %1$s is the opening link tag, %2$s is the closing link tag */
esc_html__( 'Use this section to add custom click events to your site. You can add as many as you like. Each event can have multiple pixels and each pixel can have a custom event name and value. Read more about how to configure these settings in %1$sthis article%2$s', 'insert-headers-and-footers' ),
'<a href="' . esc_url( wpcode_utm_url( 'https://wpcode.com/docs/conversion-pixels-custom-click-tracking/' ) ) . '" target="_blank" rel="noopener noreferrer">',
'</a>'
);
?>
</p>
<div id="wpcode-settings-repeater" class="wpcode-settings-repeater-group">
<div class="wpcode-settings-repeater-item">
<?php
$this->metabox_row(
__( 'CSS Selector', 'insert-headers-and-footers' ),
$this->get_input_text(
'',
'',
sprintf(
// Translators: %1$s is an opening anchor tag, %2$s is a closing anchor tag.
esc_html__( 'Define the HTML element that triggers the event upon clicking (button, link, etc). Input the appropriate CSS selector here. %1$sLearn more%2$s', 'insert-headers-and-footers' ),
'<a href="' . esc_url( wpcode_utm_url( 'https://wpcode.com/docs/finding-css-selector/' ) ) . '" target="_blank" rel="noopener noreferrer">',
'</a>'
),
true
)
);
$this->metabox_row(
__( 'Event Name', 'insert-headers-and-footers' ),
$this->get_input_text(
'',
'',
__( 'Assign a unique identifier to your event for easy recognition and categorization. ', 'insert-headers-and-footers' )
)
);
$this->metabox_row(
__( 'Event Value', 'insert-headers-and-footers' ),
$this->get_input_text(
'',
'',
__( 'Input a numerical value for your event. This helps in quantifying user interactions for your tracking needs. ', 'insert-headers-and-footers' )
)
);
?>
<div class="wpcode-pixels-chooser-row">
<div class="wpcode-metabox-form-row">
<div class="wpcode-metabox-form-row-label">
<label for="">Pixels </label>
</div>
<div class="wpcode-metabox-form-row-input">
<p>Choose which pixels to enable for this event. </p>
<p>You can choose a standard event for each pixel to override the custom event label set
above.</p>
<?php
$pixels = array(
'Facebook',
'Google',
'Pinterest',
'TikTok',
'Snapchat',
__( 'OpenAI', 'insert-headers-and-footers' ),
);
foreach ( $pixels as $pixel ) {
echo '<div class="wpcode-checkbox-row">';
echo $this->get_checkbox_toggle( // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
true,
'',
'',
1,
$pixel // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
);
echo '</div>';
}
?>
</div>
</div>
</div>
</div>
</div>
<button type="button" class="wpcode-button wpcode-button-secondary" id="wpcode-add-click-event">
<?php esc_html_e( 'Add New Click Event', 'insert-headers-and-footers' ); ?>
</button>
<?php
wp_nonce_field( 'wpcode-save-click-pixel-data', 'insert-headers-and-footers-nonce' );
?>
<button type="submit" class="wpcode-button">
<?php esc_html_e( 'Save Changes', 'insert-headers-and-footers' ); ?>
</button>
<?php
}
}
@@ -0,0 +1,163 @@
<?php
/**
* Admin page for the Search & Replace tool.
*
* @package WPCode
*/
/**
* Class for the Search & Replace admin page.
*/
class WPCode_Admin_Page_Search_Replace extends WPCode_Admin_Page {
/**
* The page slug to be used when adding the submenu.
*
* @var string
*/
public $page_slug = 'wpcode-search-replace';
/**
* The action used for the nonce.
*
* @var string
*/
protected $action = 'wpcode-search-replace';
/**
* The nonce name field.
*
* @var string
*/
protected $nonce_name = 'wpcode-search-replace_nonce';
/**
* Call this just to set the page title translatable.
*/
public function __construct() {
$this->page_title = 'Search & Replace Everything';
$this->menu_title = 'Search & Replace';
parent::__construct();
}
/**
* Register hook on admin init just for this page.
*
* @return void
*/
public function page_hooks() {
add_action( 'admin_init', array( $this, 'maybe_redirect_to_search_replace' ) );
}
/**
* Override to hide default header on this page.
*
* @return void
*/
public function output_header() {
}
/**
* Redirect to the search replace page if the plugin is active.
*
* @return void
*/
public function maybe_redirect_to_search_replace() {
if ( function_exists( 'wsrw_main' ) ) {
wp_safe_redirect( admin_url( 'tools.php?page=wsrw-search-replace' ) );
exit;
}
}
/**
* The page output.
*
* @return void
*/
public function output_content() {
?>
<div class="wpcode-plugin-page wpcode-plugin-page-search-replace">
<div class="wpcode-plugin-page-image">
<?php wpcode_icon( 'logo-sr', 90, 90, '0 0 65 64' ); ?>
</div>
<div class="wpcode-plugin-page-title">
<h1>Search & Replace Everything by WPCode</h1>
<p>
<?php esc_html_e( 'Confidently replace any text in your database and update images without duplicating uploads, all with a single plugin.', 'insert-headers-and-footers' ); ?>
</p>
</div>
<section class="wpcode-plugin-screenshot">
<div class="wpcode-plugin-screenshot-image">
<img src="<?php echo esc_url( WPCODE_PLUGIN_URL ); // phpcs:ignore PluginCheck.CodeAnalysis.ImageFunctions.NonEnqueuedImage?>admin/images/sr-screenshot-thumb.jpg" alt="<?php esc_attr_e( 'Search & Replace Everything Screenshot', 'insert-headers-and-footers' ); ?>"/>
<a href="<?php echo esc_url( WPCODE_PLUGIN_URL ); ?>admin/images/sr-screenshot.jpg" data-lity>
<?php wpcode_icon( 'search', 16, 16 ); ?>
</a>
</div>
<ul>
<li><?php esc_html_e( 'Replace Text Across Your Whole Database.', 'insert-headers-and-footers' ); ?></li>
<li><?php esc_html_e( 'Preview Changes Every Time.', 'insert-headers-and-footers' ); ?></li>
<li><?php esc_html_e( 'Replace Image Sources to Clear Up Space.', 'insert-headers-and-footers' ); ?></li>
<li><?php esc_html_e( 'Support for Serialized Data.', 'insert-headers-and-footers' ); ?></li>
</ul>
</section>
<section class="wpcode-plugin-step wpcode-plugin-step-install">
<aside class="wpcode-plugin-page-step-num">
<?php wpcode_icon( 'step-1', 50, 50, '0 0 100 100' ); ?>
<i class="wpcode-plugin-page-step-loader wpcode-plugin-page-step-loader-hidden"></i>
</aside>
<div>
<h2>
<?php
printf(
// translators: %s is the plugin name.
esc_html__( 'Install and Activate %s', 'insert-headers-and-footers' ),
'Search & Replace Everything'
)
?>
</h2>
<p>
<?php
printf(
// translators: %s is the plugin name.
esc_html__( 'Install %s from the WordPress.org plugin repository.', 'insert-headers-and-footers' ),
'Search & Replace Everything'
)
?>
</p>
<?php
// Let's check if you can install plugins on this site.
if ( current_user_can( 'install_plugins' ) && wp_is_file_mod_allowed( 'install_plugins' ) ) {
?>
<button class="wpcode-button wpcode-button-install-plugin" data-slug="search-replace-wpcode">
<?php
printf(
// translators: %s is the plugin name.
esc_html__( 'Install %s', 'insert-headers-and-footers' ),
'Search & Replace Everything'
);
?>
</button>
<?php
} else {
?>
<p>
<?php esc_html_e( 'Please ask your website administrator to install Search & Replace Everything.', 'insert-headers-and-footers' ); ?>
</p>
<?php
}
?>
</div>
</section>
</div>
<?php
}
/**
* For this page we output a title and the save button.
*
* @return void
*/
public function output_header_bottom() {
}
}
@@ -0,0 +1,825 @@
<?php
/**
* Settings admin page.
*
* @package WPCode
*/
/**
* Class for the Settings admin page.
*/
class WPCode_Admin_Page_Settings extends WPCode_Admin_Page {
/**
* The page slug to be used when adding the submenu.
*
* @var string
*/
public $page_slug = 'wpcode-settings';
/**
* The action used for the nonce.
*
* @var string
*/
protected $action = 'wpcode-settings';
/**
* The nonce name field.
*
* @var string
*/
protected $nonce_name = 'wpcode-settings_nonce';
/**
* The view to be loaded by default.
*
* @var string
*/
public $view = 'general';
/**
* The capability required to view this page.
*
* @var string
*/
protected $capability = 'wpcode_manage_settings';
/**
* Call this just to set the page title translatable.
*/
public function __construct() {
$this->page_title = __( 'WPCode Settings', 'insert-headers-and-footers' );
$this->menu_title = __( 'Settings', 'insert-headers-and-footers' );
parent::__construct();
}
/**
* Setup page-specific views.
*
* @return void
*/
protected function setup_views() {
$this->views = array(
'general' => __( 'General Settings', 'insert-headers-and-footers' ),
'errors' => __( 'Error Handling', 'insert-headers-and-footers' ),
'access' => __( 'Access Control', 'insert-headers-and-footers' ),
);
}
/**
* Register hook on admin init just for this page.
*
* @return void
*/
public function page_hooks() {
$this->process_message();
add_action( 'admin_init', array( $this, 'submit_listener' ) );
add_filter( 'wpcode_admin_js_data', array( $this, 'add_connect_strings' ) );
}
/**
* Handle the message after the settings are saved with a redirect.
*
* @return void
*/
public function process_message() {
if ( isset( $_GET['message'] ) && 1 === absint( $_GET['message'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
$this->set_success_message( __( 'Settings Saved.', 'insert-headers-and-footers' ) );
}
}
/**
* Wrap this page in a form tag.
*
* @return void
*/
public function output() {
?>
<form action="<?php echo esc_url( $this->get_page_action_url() ); ?>" method="post">
<?php parent::output(); ?>
</form>
<?php
}
/**
* The Settings page output.
*
* @return void
*/
public function output_content() {
if ( method_exists( $this, 'output_view_' . $this->view ) ) {
call_user_func( array( $this, 'output_view_' . $this->view ) );
}
}
/**
* The Settings page output.
*
* @return void
*/
public function output_view_general() {
$header_and_footers = wpcode()->settings->get_option( 'headers_footers_mode' );
$usage_tracking = wpcode()->settings->get_option( 'usage_tracking' );
$description = __( 'This allows you to disable all Code Snippets functionality and have a single "Headers & Footers" item under the settings menu.', 'insert-headers-and-footers' );
$description .= '<br />';
$description .= sprintf(
// Translators: Placeholders make the text bold.
__( '%1$sNOTE:%2$s Please use this setting with caution. It will disable all custom snippets that you add using the new snippet management interface.', 'insert-headers-and-footers' ),
'<strong>',
'</strong>'
);
$this->metabox_row(
__( 'License Key', 'insert-headers-and-footers' ),
$this->get_license_key_input()
);
$this->metabox_row(
__( 'Headers & Footers mode', 'insert-headers-and-footers' ),
$this->get_checkbox_toggle(
$header_and_footers,
'headers_footers_mode',
$description
),
'headers_footers_mode'
);
$this->common_settings();
$this->php_load_as_file_setting_upsell();
$this->metabox_row(
__( 'Allow Usage Tracking', 'insert-headers-and-footers' ),
$this->get_checkbox_toggle(
$usage_tracking,
'usage_tracking',
esc_html__( 'By allowing us to track usage data, we can better help you, as we will know which WordPress configurations, themes, and plugins we should test.', 'insert-headers-and-footers' )
),
'usage_tracking'
);
$this->uninstall_setting();
wp_nonce_field( $this->action, $this->nonce_name );
?>
<button class="wpcode-button" type="submit">
<?php esc_html_e( 'Save Changes', 'insert-headers-and-footers' ); ?>
</button>
<?php
}
/**
* Output the uninstall setting.
*
* @return void
*/
public function uninstall_setting() {
$uninstall_description = esc_html__( 'Remove ALL WPCode data upon plugin deletion.', 'insert-headers-and-footers' );
$uninstall_description .= '<br />';
$uninstall_description .= sprintf(
'<strong style="color: #DF2A35">%s</strong>',
esc_html__( 'All WPCode snippets & scripts will be unrecoverable.', 'insert-headers-and-footers' )
);
$this->metabox_row(
__( 'Delete All Data on Uninstall', 'insert-headers-and-footers' ),
$this->get_checkbox_toggle(
wpcode()->settings->get_option( 'uninstall_data', false ),
'wpcode-uninstall-data',
$uninstall_description,
1
),
'wpcode-admin-bar-info'
);
}
/**
* Move common settings to a separate method so we can use it in other versions of this page.
*
* @return void
*/
public function common_settings() {
$this->metabox_row(
__( 'WPCode Library Connection', 'insert-headers-and-footers' ),
$this->get_library_connection_input()
);
$this->metabox_row(
__( 'Editor Height', 'insert-headers-and-footers' ),
$this->get_editor_height_input(),
'wpcode-editor-height'
);
$this->metabox_row(
__( 'Dark Mode', 'insert-headers-and-footers' ),
$this->get_checkbox_toggle(
wpcode()->settings->get_option( 'dark_mode' ),
'wpcode-dark-mode',
esc_html__( 'Enable Dark Mode across WPCode.', 'insert-headers-and-footers' ),
1
),
'wpcode-dark-mode'
);
$this->metabox_row(
__( 'Admin Bar Info', 'insert-headers-and-footers' ),
$this->get_checkbox_toggle(
wpcode()->settings->get_option( 'admin_bar_info', true ),
'wpcode-admin-bar-info',
esc_html__( 'Enable the admin bar menu that shows info about which snippets & scripts are loaded on the current page.', 'insert-headers-and-footers' ),
1
),
'wpcode-admin-bar-info'
);
}
/**
* Output the PHP load as file setting upsell for lite users.
*
* @return void
*/
public function php_load_as_file_setting_upsell() {
$description = esc_html__( 'When enabled, all active PHP, HTML, and Universal snippets will be loaded from files instead of the database. Files are stored in ', 'insert-headers-and-footers' );
// Show site-specific path in multisite.
if ( function_exists( 'is_multisite' ) && is_multisite() && function_exists( 'get_current_blog_id' ) ) {
$blog_id = get_current_blog_id();
if ( $blog_id > 0 ) {
$file_path = str_replace( ABSPATH, '', WP_CONTENT_DIR . '/wpcode/snippets/site-' . absint( $blog_id ) . '/' );
} else {
$file_path = str_replace( ABSPATH, '', WP_CONTENT_DIR . '/wpcode/snippets/' );
}
} else {
$file_path = str_replace( ABSPATH, '', WP_CONTENT_DIR . '/wpcode/snippets/' );
}
$description .= '<code>' . esc_html( $file_path ) . '</code>';
if ( is_multisite() ) {
$description .= ' <strong>' . esc_html__( 'Note: In multisite networks, each site has its own file directory to prevent cross-site conflicts.', 'insert-headers-and-footers' ) . '</strong>';
}
$this->metabox_row(
__( 'Load PHP Snippets as Files', 'insert-headers-and-footers' ),
$this->get_checkbox_toggle(
false,
'wpcode-php-load-as-file',
$description
),
'wpcode-php-load-as-file',
'',
'',
'',
true
);
}
/**
* Get an input to connect or disconnect from the snippet library.
*
* @return string
*/
public function get_library_connection_input() {
$button_classes = array(
'wpcode-button',
);
$button_text = __( 'Connect to the WPCode Library', 'insert-headers-and-footers' );
if ( WPCode()->library_auth->has_auth() ) {
$button_classes[] = 'wpcode-delete-auth';
$button_text = __( 'Disconnect from the WPCode Library', 'insert-headers-and-footers' );
} else {
$button_classes[] = 'wpcode-start-auth';
}
return sprintf(
'<button type="button" class="%1$s">%2$s</button>',
esc_attr( implode( ' ', $button_classes ) ),
esc_html( $button_text )
);
}
/**
* For this page we output a menu.
*
* @return void
*/
public function output_header_bottom() {
?>
<div class="wpcode-column">
<ul class="wpcode-admin-tabs">
<?php
foreach ( $this->views as $slug => $label ) {
if ( 'importer' === $slug ) {
continue;
}
$class = $this->view === $slug ? 'active' : '';
?>
<li>
<a href="<?php echo esc_url( $this->get_view_link( $slug ) ); ?>" class="<?php echo esc_attr( $class ); ?>"><?php echo esc_html( $label ); ?></a>
</li>
<?php } ?>
</ul>
</div>
<div class="wpcode-column">
</div>
<?php
}
/**
* If the form is submitted attempt to save the values.
*
* @return void
*/
public function submit_listener() {
if ( ! isset( $_REQUEST[ $this->nonce_name ] ) || ! wp_verify_nonce( sanitize_key( $_REQUEST[ $this->nonce_name ] ), $this->action ) ) {
// Nonce is missing, so we're not even going to try.
return;
}
if ( 'errors' === $this->view ) {
$settings = array(
'error_logging' => isset( $_POST['wpcode-error-logging'] ),
);
} else {
$settings = array(
'headers_footers_mode' => isset( $_POST['headers_footers_mode'] ),
'editor_height_auto' => isset( $_POST['editor_height_auto'] ),
'editor_height' => isset( $_POST['editor_height'] ) ? absint( $_POST['editor_height'] ) : 300,
'usage_tracking' => isset( $_POST['usage_tracking'] ),
'admin_bar_info' => isset( $_POST['wpcode-admin-bar-info'] ),
'dark_mode' => isset( $_POST['wpcode-dark-mode'] ),
'uninstall_data' => isset( $_POST['wpcode-uninstall-data'] ),
);
}
$settings = $this->before_save( $settings );
wpcode()->settings->bulk_update_options( $settings );
if ( isset( $settings['headers_footers_mode'] ) && true === $settings['headers_footers_mode'] ) {
wp_safe_redirect(
add_query_arg(
array(
'page' => 'wpcode-headers-footers',
'message' => 1,
),
admin_url( 'options-general.php' )
)
);
exit;
}
wp_safe_redirect(
add_query_arg(
array(
'message' => 1,
),
$this->get_page_action_url()
)
);
exit;
}
/**
* Give child classes a chance to update the settings object before saving.
*
* @param array $settings The settings to be saved.
*
* @return array
*/
public function before_save( $settings ) {
return $settings;
}
/**
* Allow users to change the code editor height.
*
* @return string
*/
public function get_editor_height_input() {
$editor_auto_height = boolval( wpcode()->settings->get_option( 'editor_height_auto' ) );
$editor_height = wpcode()->settings->get_option( 'editor_height', 300 );
$html = sprintf(
'<input type="number" min="100" value="%1$d" id="wpcode-editor-height" name="editor_height" %2$s />',
absint( $editor_height ),
disabled( $editor_auto_height, true, false )
);
$html .= $this->get_checkbox_toggle(
$editor_auto_height,
'editor_height_auto'
);
$html .= '<label for="editor_height_auto">' . __( 'Auto height', 'insert-headers-and-footers' ) . '</label>';
$html .= '<p class="description">';
$html .= esc_html__( 'Set the editor height in pixels or enable auto-grow so the code editor automatically grows in height with the code.', 'insert-headers-and-footers' );
$html .= '</p>';
return $html;
}
/**
* Get the license key input.
*
* @return string
*/
public function get_license_key_input() {
ob_start();
?>
<div class="wpcode-metabox-form">
<p><?php esc_html_e( 'You\'re using WPCode Lite - no license needed. Enjoy!', 'insert-headers-and-footers' ); ?> 🙂</p>
<p>
<?php
printf(
// Translators: %1$s - Opening anchor tag, do not translate. %2$s - Closing anchor tag, do not translate.
esc_html__( 'To unlock more features consider %1$supgrading to PRO%2$s.', 'insert-headers-and-footers' ),
'<strong><a href="' . esc_url( wpcode_utm_url( 'https://wpcode.com/lite/', 'settings-license', 'upgrading-to-pro' ) ) . '" target="_blank" rel="noopener noreferrer">',
'</a></strong>'
)
?>
</p>
<hr>
<p><?php esc_html_e( 'Already purchased? Simply enter your license key below to enable WPCode PRO!', 'insert-headers-and-footers' ); ?></p>
<p>
<input type="password" class="wpcode-input-text" id="wpcode-settings-upgrade-license-key" placeholder="<?php esc_attr_e( 'Paste license key here', 'insert-headers-and-footers' ); ?>" value="">
<button type="button" class="wpcode-button" id="wpcode-settings-connect-btn">
<?php esc_html_e( 'Verify Key', 'insert-headers-and-footers' ); ?>
</button>
</p>
</div>
<?php
return ob_get_clean();
}
/**
* Add the strings for the connect page to the JS object.
*
* @param array $data The localized data we already have.
*
* @return array
*/
public function add_connect_strings( $data ) {
$data['oops'] = esc_html__( 'Oops!', 'insert-headers-and-footers' );
$data['ok'] = esc_html__( 'OK', 'insert-headers-and-footers' );
$data['almost_done'] = esc_html__( 'Almost Done', 'insert-headers-and-footers' );
$data['plugin_activate_btn'] = esc_html__( 'Activate', 'insert-headers-and-footers' );
$data['server_error'] = esc_html__( 'Unfortunately there was a server connection error.', 'insert-headers-and-footers' );
return $data;
}
/**
* Output the form for the access management tab.
*
* @return void
*/
public function output_view_access() {
echo '<div class="wpcode-blur-area">';
$this->access_view_content();
echo '</div>';
echo $this->get_access_overlay(); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
}
/**
* Output the form for the access management tab.
*
* @return void
*/
public function output_view_errors() {
$this->error_view_fields();
wp_nonce_field( $this->action, $this->nonce_name );
?>
<button class="wpcode-button" type="submit">
<?php esc_html_e( 'Save Changes', 'insert-headers-and-footers' ); ?>
</button>
<?php
}
/**
* The error handling tab fields.
*
* @return void
*/
public function error_view_fields() {
$this->error_logging_field();
?>
<h2><?php esc_html_e( 'Email Notifications', 'insert-headers-and-footers' ); ?>
&nbsp;<span class="wpcode-pro-pill">PRO</span></h2>
<p>
<?php esc_html_e( 'Receive email notifications when snippets throw errors or are automatically deactivated.', 'insert-headers-and-footers' ); ?>
</p>
<?php $this->wp_mail_smtp_notice(); ?>
<hr/>
<div style="position: relative">
<div class="wpcode-blur-area">
<?php
$this->error_emails_fields();
?>
</div>
<?php
echo self::get_upsell_box( // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
esc_html__( 'Email Notifications is a Pro Feature', 'insert-headers-and-footers' ),
'<p>' . esc_html__( 'Do you want to get email notifications the moment your snippets throw an error or are automatically deactivated? Upgrade today and improve your workflow with WPCode Error Email Notifications.', 'insert-headers-and-footers' ) . '</p>',
array(
'text' => esc_html__( 'Upgrade to WPCode PRO', 'insert-headers-and-footers' ),
'url' => esc_url( wpcode_utm_url( 'https://wpcode.com/lite/', 'settings', 'tab-' . $this->view, 'email' ) ),
)
);
?>
</div>
<?php
}
/**
* The fields used for email settings.
*
* @return void
*/
public function error_emails_fields() {
$this->metabox_row(
__( 'Error Notifications', 'insert-headers-and-footers' ),
$this->get_checkbox_toggle(
wpcode()->settings->get_option( 'emails_errors' ),
'wpcode-emails-errors',
sprintf(
// Translators: %1$s: opening anchor tag, %2$s: closing anchor tag. Link to docs about error notifications.
esc_html__( 'Send email notifications when snippets throw errors? %1$sLearn more%2$s', 'insert-headers-and-footers' ),
'<a href="' . esc_url( wpcode_utm_url( 'https://wpcode.com/docs/error-notifications/', 'settings', 'errors', 'errornotifications' ) ) . '" target="_blank" rel="noopener noreferrer">',
'</a>'
),
1
),
'wpcode-error-notifications'
);
$this->metabox_row(
__( 'Send To', 'insert-headers-and-footers' ),
$this->get_input_text(
'wpcode-emails-errors-addresses',
wpcode()->settings->get_option( 'emails_errors_addresses', get_option( 'admin_email' ) ),
__( 'Enter a comma separated list of email addresses to receive error notifications. Defaults to the admin email address.', 'insert-headers-and-footers' ),
true
),
'wpcode-emails-errors-addresses'
);
$preview_url = add_query_arg(
array(
'wpcode_email_template' => 'error',
'wpcode_email_preview' => '1',
),
admin_url()
);
$this->metabox_row(
'',
'<a href="' . esc_url( $preview_url ) . '" class="wpcode-button wpcode-button-secondary" target="_blank" rel="noopener noreferrer">' . esc_html__( 'Preview Email', 'insert-headers-and-footers' ) . '</a>',
'wpcode-emails-errors-preview'
);
$this->metabox_row(
__( 'Deactivation Notifications', 'insert-headers-and-footers' ),
$this->get_checkbox_toggle(
wpcode()->settings->get_option( 'emails_deactivated' ),
'wpcode-emails-deactivated',
sprintf(
// Translators: %1$s: opening anchor tag, %2$s: closing anchor tag. Link to docs about error notifications.
esc_html__( 'Send an email when a snippet gets automatically deactivated? %1$sLearn more%2$s', 'insert-headers-and-footers' ),
'<a href="' . esc_url( wpcode_utm_url( 'https://wpcode.com/docs/error-notifications/', 'settings', 'errors', 'deactivated' ) ) . '" target="_blank" rel="noopener noreferrer">',
'</a>'
),
1
),
'wpcode-emails-deactivated'
);
$this->metabox_row(
__( 'Send To', 'insert-headers-and-footers' ),
$this->get_input_text(
'wpcode-emails-deactivated-addresses',
wpcode()->settings->get_option( 'emails_deactivated_addresses', get_option( 'admin_email' ) ),
__( 'Enter a comma separated list of email addresses to receive deactivation notifications. Defaults to the admin email address.', 'insert-headers-and-footers' ),
true
),
'wpcode-emails-deactivated-addresses'
);
$preview_url = add_query_arg(
array(
'wpcode_email_template' => 'deactivated',
'wpcode_email_preview' => '1',
),
admin_url()
);
$this->metabox_row(
'',
'<a href="' . esc_url( $preview_url ) . '" class="wpcode-button wpcode-button-secondary" target="_blank" rel="noopener noreferrer">' . esc_html__( 'Preview Email', 'insert-headers-and-footers' ) . '</a>',
'wpcode-emails-deactivated-preview'
);
}
/**
* The error logging field.
*
* @return void
*/
public function error_logging_field() {
$this->metabox_row(
__( 'Error Logging', 'insert-headers-and-footers' ),
$this->get_checkbox_toggle(
wpcode()->settings->get_option( 'error_logging' ),
'wpcode-error-logging',
sprintf(
// Translators: %1$s: opening anchor tag, %2$s: closing anchor tag.
esc_html__( 'Log errors thrown by snippets? %1$sView Logs%2$s', 'insert-headers-and-footers' ),
'<a href="' . esc_url( admin_url( 'admin.php?page=wpcode-tools&view=logs' ) ) . '">',
'</a>'
),
1
),
'wpcode-error-logging'
);
}
/**
* The access management tab content.
*
* @return void
*/
public function access_view_content() {
?>
<h2><?php esc_html_e( 'Access Control', 'insert-headers-and-footers' ); ?></h2>
<p>
<?php
printf(
// Translators: %1$s - Opening anchor tag. %2$s - Closing anchor tag.
esc_html__( 'Select the user roles that are allowed to manage different types of snippets or parts of WPCode. By default, all permissions are provided only to administrator users. Please see our %1$sAccess Control documentation%2$s for more details.', 'insert-headers-and-footers' ),
'<a href="' . esc_url( wpcode_utm_url( 'https://wpcode.com/docs/access-control/', 'settings-access-controls', 'access-controls-documentation' ) ) . '" target="_blank" rel="noopener noreferrer">',
'</a>'
);
?>
</p>
<hr/>
<?php
$capabilities = $this->get_capabilites();
foreach ( $capabilities as $capability => $capability_data ) {
$selected_roles = wpcode()->settings->get_option( $capability, array() );
$this->metabox_row(
$capability_data['label'],
$this->get_roles_dropdown( $selected_roles, 'wpcode_capability_' . $capability ) .
'<p class="description">' . esc_html( $capability_data['description'] ) . '</p>'
);
}
$this->php_setting();
?>
<button class="wpcode-button" type="submit">
<?php esc_html_e( 'Save Changes', 'insert-headers-and-footers' ); ?>
</button>
<?php
}
/**
* Access control overlay.
*
* @return string
*/
public function get_access_overlay() {
$text = sprintf(
// translators: %1$s and %2$s are <u> tags.
'<p>' . esc_html__( 'Improve the way you and your team manage your snippets with the WPCode Access Control settings. Enable other users on your site to manage different types of snippets or configure Conversion Pixels settings and update configuration files. This feature is available on the %1$sWPCode Pro%2$s plan or higher.', 'insert-headers-and-footers' ) . '</p>',
'<u>',
'</u>'
);
return self::get_upsell_box(
esc_html__( 'Access Control is a PRO Feature', 'insert-headers-and-footers' ),
$text,
array(
'text' => esc_html__( 'Upgrade to WPCode PRO', 'insert-headers-and-footers' ),
'url' => esc_url( wpcode_utm_url( 'https://wpcode.com/lite/', 'settings', 'tab-' . $this->view, 'upgrade-to-pro' ) ),
),
array(),
array(
esc_html__( 'Save time and improve website management with your team', 'insert-headers-and-footers' ),
esc_html__( 'Delegate snippet management to other users with full control', 'insert-headers-and-footers' ),
esc_html__( 'Enable other users to set up ads & 3rd party services', 'insert-headers-and-footers' ),
esc_html__( 'Choose if PHP snippets should be enabled on the site', 'insert-headers-and-footers' ),
)
);
}
/**
* Output the PHP disable setting.
*
* @return void
*/
public function php_setting() {
?>
<h2><?php esc_html_e( 'PHP Snippets', 'insert-headers-and-footers' ); ?></h2>
<?php
$this->metabox_row(
esc_html__( 'Disable PHP snippets', 'insert-headers-and-footers' ),
$this->get_checkbox_toggle(
boolval( wpcode()->settings->get_option( 'completely_disable_php' ) ),
'completely_disable_php',
esc_html__( 'This option will completely disable PHP snippets execution and the option to edit or add new PHP snippets.', 'insert-headers-and-footers' )
),
'wpcode_disable_php'
);
}
/**
* Get the custom capabilities.
*
* @return array[]
*/
public function get_capabilites() {
return wpcode_custom_capabilities();
}
/**
* Get a dropdown with the user roles.
*
* @param array $selected The roles that are selected.
* @param string $name The name of the select.
* @param string $id The ID of the select, defaults to the name.
*
* @return string
*/
public function get_roles_dropdown( $selected, $name, $id = '' ) {
if ( empty( $id ) ) {
$id = $name;
}
$user_roles = wp_roles()->roles;
$dropdown = '<select name="' . esc_attr( $name ) . '[]" id="' . esc_attr( $id ) . '" class="wpcode-select2" multiple>';
foreach ( $user_roles as $key => $user_role ) {
if ( ! isset( $user_role['name'] ) ) {
continue;
}
$check_role = is_multisite() ? 'superadmin' : 'administrator';
if ( $check_role === $key ) {
continue;
}
$dropdown .= '<option value="' . esc_attr( $key ) . '" ' . selected( in_array( $key, $selected, true ), true, false ) . '>' . esc_html( $user_role['name'] ) . '</option>';
}
$dropdown .= '</select>';
return $dropdown;
}
/**
* Display a notice to suggest installing WP Mail SMTP.
*
* @return void
*/
public function wp_mail_smtp_notice() {
if ( function_exists( 'wp_mail_smtp' ) ) {
return;
}
$dismissed_notices = get_option( 'wpcode_admin_notices', array() );
$slug = 'emailsmtp';
$smtp_url = add_query_arg(
array(
'type' => 'term',
's' => 'wp mail smtp',
'tab' => 'search',
),
admin_url( 'plugin-install.php' )
);
if ( ! isset( $dismissed_notices[ $slug ] ) || empty( $dismissed_notices[ $slug ]['dismissed'] ) ) {
?>
<div class="notice wpcode-notice notice-global is-dismissible" id="wpcode-notice-global-<?php echo esc_attr( $slug ); ?>">
<h3><?php echo esc_html__( 'Make Sure Important Emails Reach Your Inbox', 'insert-headers-and-footers' ); ?></h3>
<p>
<?php
printf(
// Translators: %1$s: opening anchor tag, %2$s: closing anchor tag.
esc_html__( 'Solve common email deliverability issues for good. %1$sGet WP Mail SMTP%2$s!', 'insert-headers-and-footers' ),
'<a href="' . esc_url( $smtp_url ) . '">',
'</a>'
);
?>
</p>
</div>
<?php
wpcode()->notice->enqueues();
}
}
}
@@ -0,0 +1,25 @@
<?php
/**
* Trait for the library refresh button (lite version).
*
* @package WPCode
*/
/**
* Trait WPCode_Library_Refresh_Button.
*/
trait WPCode_Library_Refresh_Button {
/**
* Add the "Check for Updates" button to the header.
* Lite version - simple button without update check logic.
*
* @return void
*/
public function add_check_for_updates_button() {
$tooltip_text = esc_html__( 'Check for updates to your private library snippets.', 'insert-headers-and-footers' );
echo '<span class="wpcode-help-tooltip"><button type="button" id="wpcode-check-for-updates" class="wpcode-button-just-icon">' . wp_kses( get_wpcode_icon( 'sync', 16, 16, '0 0 20 21' ), wpcode_get_icon_allowed_tags() ) . '</button>';
echo '<span class="wpcode-help-tooltip-text wpcode-help-tooltip-text-down wpcode-check-updates-tooltip">' . esc_html( $tooltip_text ) . '</span></span>';
}
}
@@ -0,0 +1,250 @@
<?php
trait WPCode_My_Library_Markup_Lite {
/**
* Get an array of items for the library blurred background.
*
* @return array
*/
public function get_placeholder_library_items() {
$categories = array(
'*' => 'Most Popular',
'admin' => 'Admin',
'archive' => 'Archive',
'attachments' => 'Attachments',
'comments' => 'Comments',
'disable' => 'Disable',
'login' => 'Login',
'rss-feeds' => 'RSS Feeds',
'search' => 'Search',
);
$categories_parsed = array();
foreach ( $categories as $slug => $name ) {
$categories_parsed[] = array(
'slug' => $slug,
'name' => $name,
);
}
return array(
'categories' => $categories_parsed,
'snippets' => array(
array(
'library_id' => 0,
'title' => 'Add an Edit Post Link to Archives',
'code' => '',
'note' => 'Make it easier to edit posts when viewing archives. Or on single pages. If you...',
'categories' =>
array(
0 => 'archive',
),
'code_type' => 'php',
),
array(
'library_id' => 0,
'title' => 'Add Featured Images to RSS Feeds',
'code' => '',
'note' => 'Extend your site\'s RSS feeds by including featured images in the feed.',
'categories' =>
array(
0 => 'rss-feeds',
),
'code_type' => 'php',
),
array(
'library_id' => 0,
'title' => 'Add the Page Slug to Body Class',
'code' => '',
'note' => 'Add the page slug to the body class for better styling.',
'categories' =>
array(
0 => 'archive',
),
'code_type' => 'php',
),
array(
'library_id' => 0,
'title' => 'Allow SVG Files Upload',
'code' => '',
'note' => 'Add support for SVG files to be uploaded in WordPress media.',
'categories' =>
array(
0 => 'most-popular',
1 => 'attachments',
),
'code_type' => 'php',
),
array(
'library_id' => 0,
'title' => 'Automatically Link Featured Images to Posts',
'code' => '',
'note' => 'Wrap featured images in your theme in links to posts.',
'categories' =>
array(
0 => 'attachments',
),
'code_type' => 'php',
),
array(
'library_id' => 0,
'title' => 'Change "Howdy Admin" in Admin Bar',
'code' => '',
'note' => 'Customize the "Howdy" message in the admin bar.',
'categories' =>
array(
0 => 'admin',
),
'code_type' => 'php',
),
array(
'library_id' => 0,
'title' => 'Change Admin Panel Footer Text',
'code' => '',
'note' => 'Display custom text in the admin panel footer with this snippet.',
'categories' =>
array(
0 => 'admin',
),
'code_type' => 'php',
),
array(
'library_id' => 0,
'title' => 'Change Excerpt Length',
'code' => '',
'note' => 'Update the length of the Excerpts on your website using this snippet.',
'categories' =>
array(
0 => 'archive',
),
'code_type' => 'php',
),
array(
'library_id' => 0,
'title' => 'Change Read More Text for Excerpts',
'code' => '',
'note' => 'Customize the "Read More" text that shows up after excerpts.',
'categories' =>
array(
0 => 'archive',
),
'code_type' => 'php',
),
array(
'library_id' => 0,
'title' => 'Completely Disable Comments',
'code' => '',
'note' => 'Disable comments for all post types, in the admin and the frontend.',
'categories' =>
array(
0 => 'most-popular',
1 => 'comments',
),
'code_type' => 'php',
),
array(
'library_id' => 0,
'title' => 'Delay Posts in RSS Feeds',
'code' => '',
'note' => 'Add a delay before published posts show up in the RSS feeds.',
'categories' =>
array(
0 => 'rss-feeds',
),
'code_type' => 'php',
),
array(
'library_id' => 0,
'title' => 'Disable Attachment Pages',
'code' => '',
'note' => 'Hide the Attachment/Attachments pages on the frontend from all visitors.',
'categories' =>
array(
0 => 'most-popular',
1 => 'attachments',
),
'code_type' => 'php',
),
array(
'library_id' => 0,
'title' => 'Disable Automatic Updates',
'code' => '',
'note' => 'Use this snippet to completely disable automatic updates on your website.',
'categories' =>
array(
0 => 'most-popular',
1 => 'disable',
),
'code_type' => 'php',
),
array(
'library_id' => 0,
'title' => 'Disable Automatic Updates Emails',
'code' => '',
'note' => 'Stop getting emails about automatic updates on your WordPress site.',
'categories' =>
array(
0 => 'most-popular',
1 => 'disable',
),
'code_type' => 'php',
),
array(
'library_id' => 0,
'title' => 'Disable Gutenberg Editor (use Classic Editor)',
'code' => '',
'note' => 'Switch back to the Classic Editor by disablling the Block Editor.',
'categories' =>
array(
0 => 'most-popular',
1 => 'admin',
),
'code_type' => 'php',
),
),
);
}
/**
* Get placeholder library items in a blurred box.
*
* @return void
*/
public function blurred_placeholder_items() {
$snippets = $this->get_placeholder_library_items();
echo '<div class="wpcode-blur-area">';
$this->get_library_markup( $snippets['categories'], $snippets['snippets'] );
echo '</div>';
}
/**
* Get the markup for the "My Library" section.
*
* @return void
*/
public function get_my_library_markup() {
$this->blurred_placeholder_items();
// Show upsell.
echo WPCode_Admin_Page::get_upsell_box( // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
esc_html__( 'My Library is a PRO Feature', 'insert-headers-and-footers' ),
'<p>' . esc_html__( 'Upgrade to WPCode PRO today and save your snippets in your private library directly from the plugin and import them with 1-click on other sites.', 'insert-headers-and-footers' ) . '</p>',
array(
'text' => esc_html__( 'Upgrade to PRO and Unlock "My Library"', 'insert-headers-and-footers' ),
'url' => esc_url( wpcode_utm_url( 'https://wpcode.com/lite/', 'add-snippet', 'my-library', 'upgrade-and-unlock' ) ),
),
array(
'text' => esc_html__( 'Learn more about all the features', 'insert-headers-and-footers' ),
'url' => esc_url( wpcode_utm_url( 'https://wpcode.com/lite/', 'add-snippet', 'my-library', 'features' ) ),
),
array(
esc_html__( 'Save your snippets to your library', 'insert-headers-and-footers' ),
esc_html__( '1-click import snippets from you library', 'insert-headers-and-footers' ),
esc_html__( 'Deploy new snippets from your account', 'insert-headers-and-footers' ),
esc_html__( 'Update snippets across all your sites', 'insert-headers-and-footers' ),
esc_html__( 'Set up new websites faster', 'insert-headers-and-footers' ),
esc_html__( 'Edit snippets in the WPCode Library', 'insert-headers-and-footers' ),
)
);
}
}
@@ -0,0 +1,143 @@
<?php
/**
* Trait for displaying code revisions in the admin.
*
* @package WPCode
*/
/**
* Trait WPCode_Revisions_Display_Lite.
*/
trait WPCode_Revisions_Display_Lite {
/**
* Get a code revisions list with a notice on top.
*
* @param string $title The title for the notice.
* @param string $description Description or text below the title.
* @param array $button_1 Button 1 params for the get_upsell_box method.
* @param array $button_2 Button 2 params for the get_upsell_box method.
*
* @return string
*/
public function code_revisions_list_with_notice( $title, $description = '', $button_1 = array(), $button_2 = array() ) {
$html = '<div class="wpcode-revisions-list-area">';
$html .= $this->get_code_revisions_empty_list();
$html .= WPCode_Admin_Page::get_upsell_box(
$title,
$description,
$button_1,
$button_2
);
$html .= '</div>';// .wpcode-revisions-list-area.
return $html;
}
/**
* Get the markup for a revision item in the list of revisions.
*
* @param int $author_id The author id to display the avatar and name for.
* @param string $date The date used to display time passed.
* @param array $actions Links specific to this row.
*
* @return string
*/
public function get_revision_item( $author_id, $date, $actions = array() ) {
$list_item = '<li class="wpcode-revision-list-item">';
if ( ! empty( $author_id ) ) {
$list_item .= get_avatar( $author_id, 30 );
$list_item .= sprintf(
'<span class="wpcode-revision-list-author">%s</span>',
get_the_author_meta( 'display_name', $author_id )
);
} else {
$list_item .= sprintf(
'<img src="%s" class="avatar avatar-30 photo" alt="Avatar" width="30" height="30" />',
esc_url( WPCODE_PLUGIN_URL . 'admin/images/default-user-icon.png' )
);
$list_item .= '<span class="wpcode-revision-list-author">John Doe</span>';
}
$list_item .= sprintf(
'<span class="wpcode-revision-list-date">%s</span>',
$date
);
if ( ! empty( $actions ) ) {
$list_item .= sprintf(
'<span class="wpcode-revision-list-item-actions">%s</span>',
implode( '', $actions )
);
}
$list_item .= '</li>';
return $list_item;
}
/**
* Get a list of code revisions to use behind the notice.
*
* @return string
*/
public function get_code_revisions_empty_list() {
$list = array();
$post_modified = isset( $this->snippet ) ? strtotime( $this->snippet->get_post_data()->post_modified ) : time();
$snippet_author = isset( $this->snippet ) ? $this->snippet->get_snippet_author() : get_current_user_id();
$revisions_data = array(
$post_modified,
$post_modified - DAY_IN_SECONDS,
$post_modified - WEEK_IN_SECONDS,
$post_modified - 2 * WEEK_IN_SECONDS,
$post_modified - MONTH_IN_SECONDS,
$post_modified - 2 * MONTH_IN_SECONDS,
);
$compare = sprintf(
'<span>%s</span>',
esc_html__( 'Compare', 'insert-headers-and-footers' )
);
$view = sprintf(
'<span>%s</a>',
get_wpcode_icon( 'eye', 16, 11, '0 0 16 11' )
);
foreach ( $revisions_data as $revisions_date ) {
$updated = sprintf(
// Translators: time since the revision has been updated.
esc_html__( 'Updated %s ago', 'insert-headers-and-footers' ),
human_time_diff( $revisions_date )
);
$list[] = $this->get_revision_item(
0,
$updated,
array(
$compare,
$view,
)
);
}
$html = '<div class="wpcode-blur-area">';
$html .= sprintf(
'<ul class="wpcode-revisions-list">%s</ul>',
implode( '', $list )
);
$button_text = sprintf(
// Translators: The placeholder gets replaced with the extra number of revisions available.
esc_html__( '%d Other Revisions', 'insert-headers-and-footers' ),
3
);
$html .= sprintf(
'<button type="button" class="wpcode-button wpcode-button-secondary wpcode-button-icon" id="wpcode-show-all-snippets">%1$s %2$s</button>',
get_wpcode_icon( 'rewind', 16, 14 ),
$button_text
);
$html .= '</div>';// .wpcode-blur-area.
return $html;
}
}
@@ -0,0 +1,46 @@
<?php
/**
* WPConsent Notice Trait
*
* @package WPCode
*/
trait WPCode_WPConsent_Notice {
/**
* Display a notice to suggest WPConsent.
*
* @return void
*/
public function notice_wpconsent() {
if ( function_exists( 'wpconsent' ) ) {
return;
}
$dismissed_notices = get_option( 'wpcode_admin_notices', array() );
$slug = 'wpconsent_pixel';
$smtp_url = add_query_arg(
array(
'type' => 'term',
's' => 'wpconsent',
'tab' => 'search',
),
admin_url( 'plugin-install.php' )
);
if ( ! isset( $dismissed_notices[ $slug ] ) || empty( $dismissed_notices[ $slug ]['dismissed'] ) ) {
?>
<div class="notice wpcode-notice notice-success notice-global is-dismissible" id="wpcode-notice-global-<?php echo esc_attr( $slug ); ?>">
<h3><?php echo esc_html__( 'Using tracking scripts? Make Sure You’re Covered with a Cookie Banner!', 'insert-headers-and-footers' ); ?></h3>
<p>
<?php esc_html_e( 'Easily customize your own cookie banner and let our tools block cookies until users give consent. Scan and set up automatically!', 'insert-headers-and-footers' ); ?>
</p>
<p>
<button class="wpcode-button wpcode-button-secondary wpcode-button-install-plugin" data-slug="wpconsent">
<?php esc_html_e( 'Install WPConsent for Free', 'insert-headers-and-footers' ); ?>
</button>
</p>
</div>
<?php
wpcode()->notice->enqueues();
}
}
}
@@ -0,0 +1,110 @@
<?php
/**
* Class to auto-insert snippets in the Admin area.
*
* @package wpcode
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Class WPCode_Auto_Insert_Admin.
*/
class WPCode_Auto_Insert_Admin extends WPCode_Auto_Insert_Type {
/**
* The category of this type.
*
* @var string
*/
public $category = 'global';
/**
* Load the available options and labels.
*
* @return void
*/
public function init() {
$this->locations = array(
'admin_head' => array(),
'admin_footer' => array(),
);
}
/**
* Load the label.
*
* @return void
*/
public function load_label() {
$this->label = __( 'Admin Area', 'insert-headers-and-footers' );
}
/**
* Load the available locations.
*
* @return void
*/
public function load_locations() {
$this->locations = array(
'admin_head' => array(
'label' => esc_html__( 'Admin header', 'insert-headers-and-footers' ),
'description' => esc_html__( 'Insert snippet in the wp-admin header area.', 'insert-headers-and-footers' ),
),
'admin_footer' => array(
'label' => esc_html__( 'Admin footer', 'insert-headers-and-footers' ),
'description' => esc_html__( 'Insert snippet in the wp-admin footer.', 'insert-headers-and-footers' ),
),
);
}
/**
* Checks if we are on an archive page and we should be executing hooks.
*
* @return bool
*/
public function conditions() {
return is_admin();
}
/**
* Add hooks specific to single posts.
*
* @return void
*/
public function hooks() {
add_action( 'admin_head', array( $this, 'insert_admin_head' ), 9 );
add_action( 'admin_footer', array( $this, 'insert_admin_footer' ), 9 );
}
/**
* Output snippet in the admin head.
*
* @return void
*/
public function insert_admin_head() {
$this->output_location( 'admin_head' );
}
/**
* Output snippet in the admin footer.
*
* @return void
*/
public function insert_admin_footer() {
$this->output_location( 'admin_footer' );
}
/**
* Override the parent method to add the start hook specific to the admin.
*
* @return void
*/
protected function add_start_hook() {
add_action( 'admin_init', array( $this, 'maybe_run_hooks' ) );
}
}
new WPCode_Auto_Insert_Admin();
@@ -0,0 +1,191 @@
<?php
/**
* Class to auto-insert snippets on archive pages, taxonomies, etc.
*
* @package wpcode
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Class WPCode_Auto_Insert_Archive.
*/
class WPCode_Auto_Insert_Archive extends WPCode_Auto_Insert_Type {
/**
* The type unique name (slug).
*
* @var string
*/
public $name = 'archive';
/**
* The category of this type.
*
* @var string
*/
public $category = 'page';
/**
* Load the available options and labels.
*
* @return void
*/
public function init() {
$this->locations = array(
'before_excerpt' => array(),
'after_excerpt' => array(),
'between_posts' => array(),
'archive_before_post' => array(),
'archive_after_post' => array(),
);
}
/**
* Load the label.
*
* @return void
*/
public function load_label() {
$this->label = __( 'Categories, Archives, Tags, Taxonomies', 'insert-headers-and-footers' );
}
/**
* Load the available locations.
*
* @return void
*/
public function load_locations() {
$this->locations = array(
'before_excerpt' => array(
'label' => __( 'Insert Before Excerpt', 'insert-headers-and-footers' ),
'description' => __( 'Insert snippet above post summary.', 'insert-headers-and-footers' ),
),
'after_excerpt' => array(
'label' => __( 'Insert After Excerpt', 'insert-headers-and-footers' ),
'description' => __( 'Insert snippet below post summary.', 'insert-headers-and-footers' ),
),
'between_posts' => array(
'label' => __( 'Between Posts', 'insert-headers-and-footers' ),
'description' => __( 'Insert snippet between multiple posts.', 'insert-headers-and-footers' ),
),
'archive_before_post' => array(
'label' => __( 'Before Post', 'insert-headers-and-footers' ),
'description' => __( 'Insert snippet at the beginning of a post.', 'insert-headers-and-footers' ),
),
'archive_after_post' => array(
'label' => __( 'After Post', 'insert-headers-and-footers' ),
'description' => __( 'Insert snippet at the end of a post.', 'insert-headers-and-footers' ),
),
);
}
/**
* Checks if we are on an archive page and we should be executing hooks.
*
* @return bool
*/
public function conditions() {
return is_archive() || is_home();
}
/**
* Add hooks specific to single posts.
*
* @return void
*/
public function hooks() {
add_filter( 'the_excerpt', array( $this, 'insert_before_excerpt' ) );
add_filter( 'the_excerpt', array( $this, 'insert_after_excerpt' ) );
add_action( 'the_post', array( $this, 'insert_between_posts' ), 10, 2 );
add_action( 'the_post', array( $this, 'insert_before_after_post' ), 10, 2 );
}
/**
* Output snippet before excerpt on archive pages.
*
* @param string $excerpt The excerpt text.
*
* @return string
*/
public function insert_before_excerpt( $excerpt ) {
$snippets = $this->get_snippets_for_location( 'before_excerpt' );
foreach ( $snippets as $snippet ) {
$excerpt = wpcode()->execute->get_snippet_output( $snippet ) . $excerpt;
}
return $excerpt;
}
/**
* Output snippet after excerpt on archive pages.
*
* @param string $excerpt The excerpt text.
*
* @return string
*/
public function insert_after_excerpt( $excerpt ) {
$snippets = $this->get_snippets_for_location( 'after_excerpt' );
foreach ( $snippets as $snippet ) {
$excerpt .= wpcode()->execute->get_snippet_output( $snippet );
}
return $excerpt;
}
/**
* Output snippets between posts in a list of posts.
*
* @param WP_Post $post_data The post.
* @param WP_Query $query The query.
*
* @return void
*/
public function insert_between_posts( $post_data, $query ) {
// If the query has at least two posts to display snippets between.
if ( $query->post_count < 2 ) {
return;
}
// If the current post is not the first one in the list.
if ( $query->current_post < 1 ) {
return;
}
// If the current post is not the last one in the list.
if ( $query->post_count <= $query->current_post ) {
return;
}
$this->output_location( 'between_posts' );
}
/**
* Output snippets before or after posts.
*
* @param WP_Post $post_data The post.
* @param WP_Query $query The query.
*
* @return void
*/
public function insert_before_after_post( $post_data, $query ) {
$snippets = $this->get_snippets_for_location( 'archive_before_post' );
foreach ( $snippets as $snippet ) {
$insert_number = $snippet->get_auto_insert_number();
if ( $query->current_post === $insert_number - 1 ) {
echo wpcode()->execute->get_snippet_output( $snippet ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
}
}
$snippets = $this->get_snippets_for_location( 'archive_after_post' );
foreach ( $snippets as $snippet ) {
$insert_number = $snippet->get_auto_insert_number();
if ( $query->current_post === $insert_number ) {
echo wpcode()->execute->get_snippet_output( $snippet ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
}
}
}
}
new WPCode_Auto_Insert_Archive();
@@ -0,0 +1,164 @@
<?php
/**
* Class to auto-insert snippets site-wide.
*
* @package wpcode
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Class WPCode_Auto_Insert_Single.
*/
class WPCode_Auto_Insert_Everywhere extends WPCode_Auto_Insert_Type {
/**
* The type unique name (slug).
*
* @var string
*/
public $name = 'everywhere';
/**
* The category of this type.
*
* @var string
*/
public $category = 'global';
/**
* This should is only available for PHP scripts.
*
* @var string
*/
public $code_type = 'php';
/**
* Load the available options and labels.
*
* @return void
*/
public function init() {
$this->locations = array(
'everywhere' => array(),
'frontend_only' => array(),
'admin_only' => array(),
'frontend_cl' => array(),
'on_demand' => array(),
);
}
/**
* Load the label.
*
* @return void
*/
public function load_label() {
$this->label = __( 'PHP Snippets Only', 'insert-headers-and-footers' );
}
/**
* Load the available locations.
*
* @return void
*/
public function load_locations() {
$this->locations = array(
'everywhere' => array(
'label' => esc_html__( 'Run Everywhere', 'insert-headers-and-footers' ),
'description' => esc_html__( 'Snippet gets executed everywhere on your website.', 'insert-headers-and-footers' ),
),
'frontend_only' => array(
'label' => esc_html__( 'Frontend Only', 'insert-headers-and-footers' ),
'description' => esc_html__( 'Snippet gets executed only in the frontend of the website.', 'insert-headers-and-footers' ),
),
'admin_only' => array(
'label' => esc_html__( 'Admin Only', 'insert-headers-and-footers' ),
'description' => esc_html__( 'The snippet only gets executed in the wp-admin area.', 'insert-headers-and-footers' ),
),
'frontend_cl' => array(
'label' => esc_html__( 'Frontend Conditional Logic', 'insert-headers-and-footers' ),
'description' => esc_html__( 'Ideal for running the snippet later with conditional logic rules in the frontend.', 'insert-headers-and-footers' ),
),
'on_demand' => array(
'label' => esc_html__( 'On Demand', 'insert-headers-and-footers' ),
'description' => esc_html__( 'Execute this snippet on demand or programmatically just when you need it.', 'insert-headers-and-footers' ),
),
);
}
/**
* Execute snippets.
*
* @return void
*/
public function run_snippets() {
$snippets = $this->get_snippets_for_location( 'everywhere' );
$line_reference = array();
$code = array();
$last_line = 0;
$last_snippet = null;
if ( is_admin() ) {
$snippets = array_merge( $snippets, $this->get_snippets_for_location( 'admin_only' ) );
}
// Merge all the code into 1, so we can track on which line the error occurs, if any.
foreach ( $snippets as $snippet ) {
// Use the WPCode_Snippet_Execute_Type filters here for compatibility with class even though we're skipping it for these particular locations.
$snippet_code = apply_filters( 'wpcode_snippet_output_php', $snippet->get_code(), $snippet );
$snippet_code = apply_filters( 'wpcode_snippet_output', $snippet_code, $snippet );
// Let's see how many lines the code has.
$lines = substr_count( $snippet_code, PHP_EOL );
// Let's keep a record of the start and end line of each snippet.
$last_line ++;
$line_reference[ $snippet->get_id() ] = array(
'start' => $last_line,
'end' => $last_line + $lines,
);
$last_line = $last_line + $lines;
$code[] = $snippet_code;
$last_snippet = $snippet;
}
if ( ! empty( $code ) ) {
// Implode all the code and execute it.
$code = implode( PHP_EOL, $code );
// Execute the code.
wpcode()->execute->safe_execute_php( $code, $last_snippet, $line_reference );
}
if ( ! is_admin() ) {
$snippets = $this->get_snippets_for_location( 'frontend_only' );
foreach ( $snippets as $snippet ) {
wpcode()->execute->get_snippet_output( $snippet );
}
}
}
/**
* Execute snippets on the init hook to allow using more Conditional Logic options.
*
* @return void
*/
public function run_init_snippets() {
$snippets = $this->get_snippets_for_location( 'frontend_cl' );
foreach ( $snippets as $snippet ) {
wpcode()->execute->get_snippet_output( $snippet );
}
}
/**
* Override the default hook and short-circuit any other conditions
* checks as these snippets will run everywhere.
*
* @return void
*/
protected function add_start_hook() {
add_action( 'plugins_loaded', array( $this, 'run_snippets' ), 5 );
add_action( 'wp', array( $this, 'run_init_snippets' ) );
}
}
new WPCode_Auto_Insert_Everywhere();
@@ -0,0 +1,281 @@
<?php
/**
* Class to auto-insert snippets on single posts.
*
* @package wpcode
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Class WPCode_Auto_Insert_Single.
*/
class WPCode_Auto_Insert_Single extends WPCode_Auto_Insert_Type {
/**
* The type unique name (slug).
*
* @var string
*/
public $name = 'single';
/**
* The category of this type.
*
* @var string
*/
public $category = 'page';
/**
* Used to make sure we only output the before post code once.
*
* @var bool
*/
private $did_before_post_output = false;
/**
* Load the available options and labels.
*
* @return void
*/
public function init() {
$this->locations = array(
'before_post' => array(),
'after_post' => array(),
'before_content' => array(),
'after_content' => array(),
'before_paragraph' => array(),
'after_paragraph' => array(),
);
}
/**
* Load the label.
*
* @return void
*/
public function load_label() {
$this->label = __( 'Page, Post, Custom Post Type', 'insert-headers-and-footers' );
}
/**
* Load the available locations.
*
* @return void
*/
public function load_locations() {
$this->locations = array(
'before_post' => array(
'label' => esc_html__( 'Insert Before Post', 'insert-headers-and-footers' ),
'description' => esc_html__( 'Insert snippet at the beginning of a post.', 'insert-headers-and-footers' ),
),
'after_post' => array(
'label' => esc_html__( 'Insert After Post', 'insert-headers-and-footers' ),
'description' => esc_html__( 'Insert snippet at the end of a post.', 'insert-headers-and-footers' ),
),
'before_content' => array(
'label' => esc_html__( 'Insert Before Content', 'insert-headers-and-footers' ),
'description' => esc_html__( 'Insert snippet at the beginning of the post content.', 'insert-headers-and-footers' ),
),
'after_content' => array(
'label' => esc_html__( 'Insert After Content', 'insert-headers-and-footers' ),
'description' => esc_html__( 'Insert snippet at the end of the post content.', 'insert-headers-and-footers' ),
),
'before_paragraph' => array(
'label' => esc_html__( 'Insert Before Paragraph', 'insert-headers-and-footers' ),
'description' => esc_html__( 'Insert snippet before paragraph # of the post content.', 'insert-headers-and-footers' ),
),
'after_paragraph' => array(
'label' => esc_html__( 'Insert After Paragraph', 'insert-headers-and-footers' ),
'description' => esc_html__( 'Insert snippet after paragraph # of the post content.', 'insert-headers-and-footers' ),
),
);
}
/**
* Checks if we are on a singular page and we should be executing hooks.
*
* @return bool
*/
public function conditions() {
return is_singular();
}
/**
* Add hooks specific to single posts.
*
* @return void
*/
public function hooks() {
add_action( 'the_post', array( $this, 'insert_before_post' ) );
add_filter( 'render_block_core/template-part', array( $this, 'insert_before_post_fse' ), 15, 2 );
add_action( 'the_content', array( $this, 'insert_after_post' ) );
add_filter( 'the_content', array( $this, 'insert_before_content' ) );
add_filter( 'the_content', array( $this, 'insert_after_content' ) );
add_filter( 'the_content', array( $this, 'insert_after_before_paragraph' ) );
}
/**
* Insert snippet before the post.
*
* @param WP_Post $post_object The post object being loaded.
*
* @return void
*/
public function insert_before_post( $post_object ) {
if ( ! did_action( 'get_header' ) || get_the_ID() !== $post_object->ID || $this->did_before_post_output ) {
return;
}
$this->output_location( 'before_post' );
$this->did_before_post_output = true;
}
/**
* In FSE themes there's no "get_header" action to check for, so we hook after the core template-part header block.
*
* @param string $block_content The normal block HTML that would be sent to the screen.
* @param array $block An array of data about the block, and the way the user configured it.
*
* @return string
*/
public function insert_before_post_fse( $block_content, $block ) {
// If the get_header action ran we use the classic output method above.
if ( did_action( 'get_header' ) ) {
return $block_content;
}
if ( ! isset( $block['attrs']['slug'] ) || 'header' !== $block['attrs']['slug'] ) {
return $block_content;
}
$before_post = '';
$snippets = $this->get_snippets_for_location( 'before_post' );
foreach ( $snippets as $snippet ) {
$before_post .= wpcode()->execute->get_snippet_output( $snippet );
}
return $block_content . $before_post;
}
/**
* Insert snippet output after the content.
*
* @param string $content The content of the post.
*
* @return string
*/
public function insert_after_content( $content ) {
$snippets = $this->get_snippets_for_location( 'after_content' );
foreach ( $snippets as $snippet ) {
$content .= wpcode()->execute->get_snippet_output( $snippet );
}
return $content;
}
/**
* Insert snippet after the post
*
* @param string $content The post content.
*
* @return string
*/
public function insert_after_post( $content ) {
$snippets = $this->get_snippets_for_location( 'after_post' );
foreach ( $snippets as $snippet ) {
$content .= wpcode()->execute->get_snippet_output( $snippet );
}
return $content;
}
/**
* Insert snippets before the content.
*
* @param string $content The post content.
*
* @return string
*/
public function insert_before_content( $content ) {
$snippets = $this->get_snippets_for_location( 'before_content' );
$snippets_output = '';
foreach ( $snippets as $snippet ) {
$snippets_output .= wpcode()->execute->get_snippet_output( $snippet );
}
return $snippets_output . $content;
}
/**
* Insert content before or after paragraphs based on settings.
*
* @param string $content The post content.
*
* @return string
*/
public function insert_after_before_paragraph( $content ) {
$snippets = $this->get_snippets_for_location( 'before_paragraph' );
foreach ( $snippets as $snippet ) {
$auto_insert_number = $snippet->get_auto_insert_number();
$auto_insert_number = empty( $auto_insert_number ) ? 1 : absint( $auto_insert_number );
$snippet_output = wpcode()->execute->get_snippet_output( $snippet );
$content = $this->insert_between_paragraphs( $snippet_output, $auto_insert_number, $content, 'before' );
}
$snippets = $this->get_snippets_for_location( 'after_paragraph' );
foreach ( $snippets as $snippet ) {
$auto_insert_number = $snippet->get_auto_insert_number();
$auto_insert_number = empty( $auto_insert_number ) ? 1 : absint( $auto_insert_number );
$snippet_output = wpcode()->execute->get_snippet_output( $snippet );
$content = $this->insert_between_paragraphs( $snippet_output, $auto_insert_number, $content, 'after' );
}
return $content;
}
/**
* Insert snippet code before or after paragraphs in a post.
*
* @param string $content_to_insert The content to insert (snippet code output).
* @param int $p_number The paragraph number.
* @param string $content_to_add_to The content in which the content should be added.
* @param string $before_or_after Add it before or after the paragraph.
*
* @return string
*/
public function insert_between_paragraphs( $content_to_insert, $p_number, $content_to_add_to, $before_or_after = 'after' ) {
if ( 'before' === $before_or_after ) {
preg_match_all( '/<p(.*?)>/', $content_to_add_to, $matches );
} else {
preg_match_all( '/<\/p>/', $content_to_add_to, $matches );
}
$paragraphs = $matches[0];
// We don't have enough paragraphs to add the snippet.
if ( count( $paragraphs ) < $p_number ) {
return $content_to_add_to;
}
$p_number = -- $p_number;
$offset = 0;
foreach ( $paragraphs as $p_index => $p ) {
$position = strpos( $content_to_add_to, $p, $offset );
if ( $p_index === $p_number ) {
if ( 'before' === $before_or_after ) {
$content_to_add_to = substr( $content_to_add_to, 0, $position ) . $content_to_insert . substr( $content_to_add_to, $position );
} else {
$content_to_add_to = substr( $content_to_add_to, 0, $position + 4 ) . $content_to_insert . substr( $content_to_add_to, $position + 4 );
}
break;
} else {
$offset = $position + 1;
}
}
return $content_to_add_to;
}
}
new WPCode_Auto_Insert_Single();
@@ -0,0 +1,113 @@
<?php
/**
* Class to auto-insert snippets site-wide.
*
* @package wpcode
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Class WPCode_Auto_Insert_Single.
*/
class WPCode_Auto_Insert_Site_Wide extends WPCode_Auto_Insert_Type {
/**
* The type unique name (slug).
*
* @var string
*/
public $name = 'site_wide';
/**
* The category of this type.
*
* @var string
*/
public $category = 'global';
/**
* Load the available options and labels.
*
* @return void
*/
public function init() {
$this->locations = array(
'site_wide_header' => array(),
'site_wide_body' => array(),
'site_wide_footer' => array(),
);
}
/**
* Load the label.
*
* @return void
*/
public function load_label() {
$this->label = __( 'Site Wide (Frontend)', 'insert-headers-and-footers' );
}
/**
* Load the available locations.
*
* @return void
*/
public function load_locations() {
$this->locations = array(
'site_wide_header' => array(
'label' => esc_html__( 'Site Wide Header', 'insert-headers-and-footers' ),
'description' => esc_html__( 'Insert snippet between the head tags of your website on all pages.', 'insert-headers-and-footers' ),
),
'site_wide_body' => array(
'label' => esc_html__( 'Site Wide Body', 'insert-headers-and-footers' ),
'description' => esc_html__( 'Insert the snippet just after the opening body tag.', 'insert-headers-and-footers' ),
),
'site_wide_footer' => array(
'label' => esc_html__( 'Site Wide Footer', 'insert-headers-and-footers' ),
'description' => esc_html__( 'Insert the snippet in the footer just before the closing body tag.', 'insert-headers-and-footers' ),
),
);
}
/**
* Add hooks specific to this type.
*
* @return void
*/
public function hooks() {
add_action( 'wp_head', array( $this, 'insert_header' ) );
add_action( 'wp_footer', array( $this, 'insert_footer' ) );
add_action( 'wp_body_open', array( $this, 'insert_body' ) );
}
/**
* Insert snippets in the header.
*
* @return void
*/
public function insert_header() {
$this->output_location( 'site_wide_header' );
}
/**
* Insert snippets in the footer.
*
* @return void
*/
public function insert_footer() {
$this->output_location( 'site_wide_footer' );
}
/**
* Insert snippets after the opening body tag.
*
* @return void
*/
public function insert_body() {
$this->output_location( 'site_wide_body' );
}
}
new WPCode_Auto_Insert_Site_Wide();
@@ -0,0 +1,440 @@
<?php
/**
* Base class for of auto-insert options.
*
* @package wpcode
*/
/**
* Abstract class WPCode_Auto_Insert_Type.
*/
abstract class WPCode_Auto_Insert_Type {
/**
* The auto-insert label.
*
* @var string
*/
public $label;
/**
* A unique name for this type.
*
* @var string
*/
public $name;
/**
* An array of locations.
* This is an array of unique locations where snippets can be executed in the form
* of key => label where the keys should be unique for all the options across
* all child classes as those will be used as taxonomy terms to store the
* relationship between snippets and their location.
*
* @var array
*/
public $locations;
/**
* Terms of the locations for this type.
*
* @var array
*/
public $locations_terms;
/**
* All the snippets for this location.
*
* @var array
*/
public $snippets;
/**
* For which code type this insert is available.
* By default, all.
*
* @var string
*/
public $code_type = 'all';
/**
* If we should skip the cache set this to false.
*
* @var bool
*/
protected $use_cache = true;
/**
* Display a label next to the optgroup title.
*
* @var string
*/
public $label_pill = '';
/**
* Title of the upgrade prompt.
*
* @var string
*/
public $upgrade_title = '';
/**
* Text of the upgrade prompt.
*
* @var string
*/
public $upgrade_text = '';
/**
* URL of the upgrade prompt (CTA) with UTM.
*
* @var string
*/
public $upgrade_link = '';
/**
* Text for the CTA Button.
*
* @var string
*/
public $upgrade_button = '';
/**
* Category used for displaying this type in the admin.
*
* @var string
*/
public $category = '';
/**
* Start the auto insertion.
*/
public function __construct() {
$this->init();
$this->register_type();
/**
* Constant to enable safe mode.
* Filter to allow disabling auto insert.
*/
if ( defined( 'WPCODE_SAFE_MODE' ) && WPCODE_SAFE_MODE ) {
return;
}
if ( ! apply_filters( 'wpcode_do_auto_insert', true ) ) {
return;
}
// If we're in headers & footers mode prevent execution of any type of snippet.
if ( WPCode()->settings->get_option( 'headers_footers_mode' ) ) {
return;
}
add_action( 'admin_init', array( $this, 'load_upgrade_strings' ), 140 );
$this->add_start_hook();
}
/**
* Register this instance to the global auto-insert types.
*
* @return void
*/
private function register_type() {
wpcode()->auto_insert->register_type( $this );
}
/**
* Init function that is specific to each auto-insert type.
*
* @return void
*/
abstract public function init();
/**
* Give child classes a chance to load on a different hook.
*
* @return void
*/
protected function add_start_hook() {
add_action( 'wp', array( $this, 'maybe_run_hooks' ) );
}
/**
* Check if conditions are met before calling the hooks.
*
* @return void
*/
public function maybe_run_hooks() {
if ( ! $this->conditions() ) {
return;
}
// Go through relevant hooks and output based on settings.
$this->hooks();
}
/**
* Conditions that have to be met for the class to do its thing.
* For example, in the single post class we'll check if is_single
* and only then will we change the_content.
*
* @return bool
*/
public function conditions() {
// Most types only run on the frontend.
return ! is_admin();
}
/**
* Hooks specific to this type of auto-insertion.
*
* @return void
*/
public function hooks() {
}
/**
* Get an array of options for the admin.
* Check if the insert type is compatible with the code type.
*
* @return array
*/
public function get_locations() {
$this->load_locations();
return isset( $this->locations ) ? $this->locations : array();
}
/**
* Load the locations for this type.
*
* @return void
*/
abstract public function load_locations();
/**
* Load the label for this type.
*
* @return void
*/
abstract public function load_label();
/**
* Query snippets by location.
*
* @param string $location The location slug.
*
* @return WPCode_Snippet[]
*/
public function get_snippets_for_location( $location ) {
$snippets = $this->get_snippets();
$snippets_for_location = isset( $snippets[ $location ] ) ? $snippets[ $location ] : array();
return apply_filters(
'wpcode_get_snippets_for_location',
wpcode()->conditional_logic->check_snippets_conditions( $snippets_for_location ),
$location
);
}
/**
* Get the snippets for this type and query on demand.
*
* @return array
*/
public function get_snippets() {
if ( ! isset( $this->snippets ) ) {
$this->load_all_snippets_for_type();
}
return $this->snippets;
}
/**
* Load all the snippets for this type and group them by location.
* This can be further improved by separating the snippet loading and loading
* all the relevant snippets for a screen at once (regardless of type) or just loading all the
* active snippets in 1 query.
*
* @return void
*/
public function load_all_snippets_for_type() {
if ( $this->use_cache() ) {
$this->snippets = $this->get_snippets_from_cache();
return;
}
$this->snippets = array();
$args = array(
'post_type' => wpcode_get_post_type(),
'posts_per_page' => - 1,
'post_status' => 'publish',
// We don't want to cache this query ever as it should only run when snippets are preloaded in case of an error it will provide false values if cached.
'cache_results' => false,
// We don't want to allow any filters to be applied to this query.
'suppress_filters' => true,
);
$snippets_query = new WP_Query( $args );
$snippets = $snippets_query->posts;
foreach ( $snippets as $snippet ) {
$snippet_locations = wp_get_post_terms( $snippet->ID, 'wpcode_location', array( 'fields' => 'slugs' ) );
if ( empty( $snippet_locations ) || is_wp_error( $snippet_locations ) ) {
continue;
}
$location_key = $snippet_locations[0];
$this->snippets[ $location_key ][] = wpcode_get_snippet( $snippet );
}
}
/**
* Get snippets from cache split by relevant locations for this type.
*
* @return array
*/
public function get_snippets_from_cache() {
$cached_snippets = wpcode()->cache->get_cached_snippets();
$type_snippets = array();
foreach ( $this->locations as $location => $label ) {
if ( array_key_exists( $location, $cached_snippets ) ) {
$type_snippets[ $location ] = $cached_snippets[ $location ];
} else {
$type_snippets[ $location ] = array();
}
}
return $type_snippets;
}
/**
* Get the ids of the loaded location terms.
*
* @return int[]
*/
public function get_locations_ids() {
$terms = $this->get_location_terms();
$ids = array();
foreach ( $terms as $term ) {
$ids[] = $term->term_id;
}
return $ids;
}
/**
* Get the location terms.
*
* @return WP_Term[]
*/
public function get_location_terms() {
if ( ! isset( $this->locations_terms ) ) {
$this->load_locations_terms();
}
return $this->locations_terms;
}
/**
* Query the location terms using get_terms and store them in the instance.
*
* @return void
*/
public function load_locations_terms() {
$terms = get_terms(
array(
'taxonomy' => 'wpcode_location',
'slug' => array_keys( $this->locations ),
)
);
$this->locations_terms = array();
if ( is_wp_error( $terms ) ) {
// If the terms don't exist, bail early.
return;
}
foreach ( $terms as $term ) {
$term_slug = $term->slug ?? '';
$this->locations_terms[ $term_slug ] = $term;
}
}
/**
* Change the clauses for our specific query to include the term id in the resulting
* WP_Post object so that we can group the results by the type locations.
*
* @param array $clauses Array of clauses for the SQL query.
*
* @return mixed
*/
public function include_term_in_post( $clauses ) {
global $wpdb;
$clauses['fields'] .= ", {$wpdb->term_relationships}.term_taxonomy_id";
$clauses['groupby'] = '';
return $clauses;
}
/**
* Return the type label.
*
* @return string
*/
public function get_label() {
if ( ! isset( $this->label ) ) {
$this->load_label();
}
return $this->label;
}
/**
* Grab the use cache value allowing filtering.
*
* @return bool
*/
public function use_cache() {
return boolval( apply_filters( 'wpcode_use_auto_insert_cache', $this->use_cache ) );
}
/**
* Get the snippets for a location and echo them executed.
*
* @param string $location_name The location to grab snippets for.
*
* @return void
*/
public function output_location( $location_name ) {
$snippets = $this->get_snippets_for_location( $location_name );
foreach ( $snippets as $snippet ) {
echo wpcode()->execute->get_snippet_output( $snippet ); //phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
}
}
/**
* Get the snippets for a location and return them executed.
*
* @param string $location_name The location to grab snippets for.
*
* @return string
*/
public function get_location( $location_name ) {
$content = '';
$snippets = $this->get_snippets_for_location( $location_name );
foreach ( $snippets as $snippet ) {
$content .= wpcode()->execute->get_snippet_output( $snippet );
}
return $content;
}
/**
* Load the strings for the upgrade prompt, if any.
*
* @return void
*/
public function load_upgrade_strings() {
}
}
@@ -0,0 +1,87 @@
<?php
/**
* Map capabilites with backwards compatibility.
*
* @package WPCode
*/
// Prevent direct access.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
add_filter( 'map_meta_cap', 'wpcode_map_meta_cap', 10, 4 );
/**
* Map capabilites with backwards compatibility.
*
* @param string[] $caps Primitive capabilities required of the user.
* @param string $cap Capability being checked.
* @param int $user_id The user ID.
* @param array $args Adds context to the capability check, typically
* starting with an object ID.
*
* @return array
*/
function wpcode_map_meta_cap( $caps, $cap, $user_id, $args ) {
$custom_capabilities = array(
'wpcode_edit_php_snippets',
'wpcode_edit_html_snippets',
'wpcode_manage_conversion_pixels',
'wpcode_file_editor',
'wpcode_manage_settings',
);
if ( in_array( $cap, $custom_capabilities, true ) ) {
return array( 'wpcode_edit_snippets' );
}
return $caps;
}
/**
* Get an array of the custom capabilities that WPCode uses.
*
* @return array[]
*/
function wpcode_custom_capabilities() {
return array(
'wpcode_edit_text_snippets' => array(
'label' => __( 'Edit Text/Blocks Snippets', 'insert-headers-and-footers' ),
'description' => __( 'This enables users to edit just text & blocks snippets, no HTML code is allowed.', 'insert-headers-and-footers' ),
),
'wpcode_edit_html_snippets' => array(
'label' => __( 'Edit HTML, JavaScript & CSS Snippets', 'insert-headers-and-footers' ),
'description' => __( 'This enables users to add and manage HTML, JavaScript & CSS snippets but also Text & Blocks snippets.', 'insert-headers-and-footers' ),
),
'wpcode_edit_php_snippets' => array(
'label' => __( 'Edit PHP Snippets', 'insert-headers-and-footers' ),
'description' => __( 'This enables users to add and manage PHP snippets and all the other types of snippets.', 'insert-headers-and-footers' ),
),
'wpcode_manage_conversion_pixels' => array(
'label' => __( 'Manage Conversion Pixels Settings', 'insert-headers-and-footers' ),
'description' => __( 'This enables users to manage the conversion pixels settings.', 'insert-headers-and-footers' ),
),
'wpcode_file_editor' => array(
'label' => __( 'Use the File Editor', 'insert-headers-and-footers' ),
'description' => __( 'This enables users to use the file editor.', 'insert-headers-and-footers' ),
),
);
}
/**
* Return just the keys to avoid a gettext call that causes an endless loop with TranslatePress.
*
* @return string[]
*/
function wpcode_custom_capabilities_keys() {
return array(
'wpcode_edit_text_snippets',
'wpcode_edit_html_snippets',
'wpcode_edit_php_snippets',
'wpcode_manage_conversion_pixels',
'wpcode_file_editor',
);
}
@@ -0,0 +1,541 @@
<?php
/**
* WordPress Abilities API Integration for WPCode (Read-Only)
*
* @package WPCode
* @since 2.3.0
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* WPCode_Abilities_API class.
*
* Registers read-only abilities for WordPress 6.9+ Abilities API
* to allow AI and automation tools to query WPCode data safely.
*/
class WPCode_Abilities_API {
/**
* Constructor.
*/
public function __construct() {
add_action( 'wp_abilities_api_categories_init', array( $this, 'register_categories' ) );
add_action( 'wp_abilities_api_init', array( $this, 'register_abilities' ) );
}
/**
* Register WPCode categories for the Abilities API.
*
* @return void
*/
public function register_categories() {
// WPCode Diagnostics category.
wp_register_ability_category(
'wpcode-diagnostics',
array(
'label' => __( 'WPCode Diagnostics', 'insert-headers-and-footers' ),
'description' => __( 'Abilities for checking snippet health', 'insert-headers-and-footers' ),
)
);
// WPCode Library category.
wp_register_ability_category(
'wpcode-library',
array(
'label' => __( 'WPCode Library', 'insert-headers-and-footers' ),
'description' => __( 'Abilities for searching pre-built templates', 'insert-headers-and-footers' ),
)
);
// WPCode Insights category.
wp_register_ability_category(
'wpcode-insights',
array(
'label' => __( 'WPCode Insights', 'insert-headers-and-footers' ),
'description' => __( 'Abilities for reading current snippet configurations', 'insert-headers-and-footers' ),
)
);
}
/**
* Register all read-only abilities.
*
* @return void
*/
public function register_abilities() {
// 1. List snippets.
$this->register_list_snippets_ability();
// 2. Detect snippet errors.
$this->register_detect_snippet_errors_ability();
// 3. Get error logs.
$this->register_get_error_logs_ability();
// 4. Search library.
$this->register_search_library_ability();
// 5. Get settings.
$this->register_get_settings_ability();
}
/**
* Register ability to list snippets.
*
* @return void
*/
private function register_list_snippets_ability() {
wp_register_ability(
'wpcode/list-snippets',
array(
'label' => __( 'List Code Snippets', 'insert-headers-and-footers' ),
'description' => __( 'Provides a summary of all snippets and their active/inactive status', 'insert-headers-and-footers' ),
'category' => 'wpcode-diagnostics',
'meta' => array(
'annotations' => array(
'readonly' => true,
'destructive' => false,
'idempotent' => true,
),
'show_in_rest' => true,
),
'input_schema' => array(
'type' => 'object',
'properties' => array(
'status' => array(
'type' => 'string',
'enum' => array( 'all', 'active', 'inactive' ),
'description' => __( 'Filter by snippet status', 'insert-headers-and-footers' ),
'default' => 'all',
),
'code_type' => array(
'type' => 'string',
'enum' => array( 'php', 'js', 'css', 'html', 'text', 'universal', 'blocks', 'scss' ),
'description' => __( 'Filter by code type', 'insert-headers-and-footers' ),
),
'tag' => array(
'type' => 'string',
'description' => __( 'Filter by tag', 'insert-headers-and-footers' ),
),
),
),
'output_schema' => array(
'type' => 'array',
'items' => array(
'type' => 'object',
'properties' => array(
'id' => array( 'type' => 'integer' ),
'title' => array( 'type' => 'string' ),
'code_type' => array( 'type' => 'string' ),
'location' => array( 'type' => 'string' ),
'active' => array( 'type' => 'boolean' ),
'tags' => array( 'type' => 'array' ),
'has_error' => array( 'type' => 'boolean' ),
'last_update' => array( 'type' => 'string' ),
),
),
),
'execute_callback' => array( $this, 'execute_list_snippets' ),
'permission_callback' => array( $this, 'check_read_permission' ),
)
);
}
/**
* Register ability to detect snippet errors.
*
* @return void
*/
private function register_detect_snippet_errors_ability() {
wp_register_ability(
'wpcode/detect-snippet-errors',
array(
'label' => __( 'Detect Snippet Errors', 'insert-headers-and-footers' ),
'description' => __( 'Checks if WPCode\'s error handler has flagged any active snippets', 'insert-headers-and-footers' ),
'category' => 'wpcode-diagnostics',
'meta' => array(
'annotations' => array(
'readonly' => true,
'destructive' => false,
'idempotent' => true,
),
'show_in_rest' => true,
),
'input_schema' => array(
'type' => 'object',
'properties' => array(
'snippet_id' => array(
'type' => 'integer',
'description' => __( 'Snippet ID to check', 'insert-headers-and-footers' ),
),
),
'required' => array( 'snippet_id' ),
),
'output_schema' => array(
'type' => 'object',
'properties' => array(
'has_error' => array( 'type' => 'boolean' ),
'error_message' => array( 'type' => 'string' ),
'error_line' => array( 'type' => 'integer' ),
'error_time' => array( 'type' => 'integer' ),
'error_url' => array( 'type' => 'string' ),
),
),
'execute_callback' => array( $this, 'execute_detect_snippet_errors' ),
'permission_callback' => array( $this, 'check_read_permission' ),
)
);
}
/**
* Register ability to get error logs.
*
* @return void
*/
private function register_get_error_logs_ability() {
wp_register_ability(
'wpcode/get-error-logs',
array(
'label' => __( 'Get Error Logs', 'insert-headers-and-footers' ),
'description' => __( 'Provides the stack trace of recent snippet-related failures', 'insert-headers-and-footers' ),
'category' => 'wpcode-diagnostics',
'meta' => array(
'annotations' => array(
'readonly' => true,
'destructive' => false,
'idempotent' => true,
),
'show_in_rest' => true,
),
'output_schema' => array(
'type' => 'object',
'properties' => array(
'snippets_affected' => array( 'type' => 'integer' ),
'log_files' => array( 'type' => 'array' ),
),
),
'execute_callback' => array( $this, 'execute_get_error_logs' ),
'permission_callback' => array( $this, 'check_admin_permission' ),
)
);
}
/**
* Register ability to search library.
*
* @return void
*/
private function register_search_library_ability() {
wp_register_ability(
'wpcode/search-library',
array(
'label' => __( 'Search WPCode Library', 'insert-headers-and-footers' ),
'description' => __( 'Queries the WPCode Cloud Library for snippets matching a keyword', 'insert-headers-and-footers' ),
'category' => 'wpcode-library',
'meta' => array(
'annotations' => array(
'readonly' => true,
'destructive' => false,
'idempotent' => true,
),
'show_in_rest' => true,
),
'input_schema' => array(
'type' => 'object',
'properties' => array(
'keyword' => array(
'type' => 'string',
'description' => __( 'Search keyword', 'insert-headers-and-footers' ),
),
),
'required' => array( 'keyword' ),
),
'output_schema' => array(
'type' => 'array',
'items' => array(
'type' => 'object',
'properties' => array(
'id' => array( 'type' => 'string' ),
'title' => array( 'type' => 'string' ),
'description' => array( 'type' => 'string' ),
'category' => array( 'type' => 'string' ),
'tags' => array( 'type' => 'array' ),
),
),
),
'execute_callback' => array( $this, 'execute_search_library' ),
'permission_callback' => array( $this, 'check_read_permission' ),
)
);
}
/**
* Register ability to get settings.
*
* @return void
*/
private function register_get_settings_ability() {
wp_register_ability(
'wpcode/get-settings',
array(
'label' => __( 'Get WPCode Settings', 'insert-headers-and-footers' ),
'description' => __( 'Reads global settings (e.g., "Safe Mode" status)', 'insert-headers-and-footers' ),
'category' => 'wpcode-insights',
'meta' => array(
'annotations' => array(
'readonly' => true,
'destructive' => false,
'idempotent' => true,
),
'show_in_rest' => true,
),
'output_schema' => array(
'type' => 'object',
'properties' => array(
'version' => array( 'type' => 'string' ),
'error_logging' => array( 'type' => 'boolean' ),
'safe_mode_active' => array( 'type' => 'boolean' ),
),
),
'execute_callback' => array( $this, 'execute_get_settings' ),
'permission_callback' => array( $this, 'check_admin_permission' ),
)
);
}
// ========================================
// PERMISSION CALLBACKS
// ========================================
/**
* Check if user has permission to read WPCode data.
*
* @return bool
*/
public function check_read_permission() {
return current_user_can( 'wpcode_edit_snippets' );
}
/**
* Check if user has admin permission.
*
* @return bool
*/
public function check_admin_permission() {
return current_user_can( 'manage_options' );
}
// ========================================
// EXECUTION METHODS
// ========================================
/**
* Execute list snippets.
*
* @param array $input Input parameters.
*
* @return array
*/
public function execute_list_snippets( $input ) {
$args = array(
'post_type' => 'wpcode',
'posts_per_page' => - 1,
'post_status' => array( 'publish', 'draft' ),
);
// Apply status filter.
if ( ! empty( $input['status'] ) && 'all' !== $input['status'] ) {
$args['post_status'] = 'active' === $input['status'] ? 'publish' : 'draft';
}
// Apply code type filter.
if ( ! empty( $input['code_type'] ) ) {
$args['tax_query'] = array(
array(
'taxonomy' => 'wpcode_type',
'field' => 'slug',
'terms' => sanitize_text_field( $input['code_type'] ),
),
);
}
// Apply tag filter.
if ( ! empty( $input['tag'] ) ) {
if ( ! isset( $args['tax_query'] ) ) {
$args['tax_query'] = array();
}
$args['tax_query'][] = array(
'taxonomy' => 'wpcode_tags',
'field' => 'slug',
'terms' => sanitize_text_field( $input['tag'] ),
);
}
$snippets = get_posts( $args );
$result = array();
foreach ( $snippets as $post ) {
$snippet = new WPCode_Snippet( $post->ID );
$last_error = $snippet->get_last_error();
$result[] = array(
'id' => $snippet->get_id(),
'title' => $snippet->get_title(),
'code_type' => $snippet->get_code_type(),
'location' => $snippet->get_location(),
'active' => $snippet->is_active(),
'tags' => $snippet->get_tags(),
'has_error' => ! empty( $last_error ),
'last_update' => get_the_modified_date( 'c', $post ),
// IMPORTANT: Do NOT include 'code' field for security.
);
}
return $result;
}
/**
* Execute detect snippet errors.
*
* @param array $input Input parameters.
*
* @return array|WP_Error
*/
public function execute_detect_snippet_errors( $input ) {
$snippet_id = absint( $input['snippet_id'] );
$snippet = new WPCode_Snippet( $snippet_id );
if ( ! $snippet->get_id() ) {
return new WP_Error(
'snippet_not_found',
__( 'Snippet not found', 'insert-headers-and-footers' ),
array( 'status' => 404 )
);
}
$last_error = $snippet->get_last_error();
return array(
'has_error' => ! empty( $last_error ),
'error_message' => ! empty( $last_error['message'] ) ? $last_error['message'] : '',
'error_line' => ! empty( $last_error['error_line'] ) ? (int) $last_error['error_line'] : 0,
'error_time' => ! empty( $last_error['time'] ) ? (int) $last_error['time'] : 0,
'error_url' => ! empty( $last_error['url'] ) ? esc_url( $last_error['url'] ) : '',
);
}
/**
* Execute get error logs.
*
* @param array|null $input Input parameters (optional, not used).
*
* @return array
*/
public function execute_get_error_logs( $input = null ) {
$logs = wpcode()->logger->get_logs();
return array(
'snippets_affected' => wpcode()->error->get_error_count(),
'log_files' => $logs,
);
}
/**
* Execute search library.
*
* @param array $input Input parameters.
*
* @return array|WP_Error
*/
public function execute_search_library( $input ) {
$keyword = sanitize_text_field( $input['keyword'] );
// Lazy load library classes if not already available.
if ( ! isset( wpcode()->library ) || ! is_object( wpcode()->library ) ) {
if ( ! class_exists( 'WPCode_File_Cache' ) ) {
require_once WPCODE_PLUGIN_PATH . 'includes/class-wpcode-file-cache.php';
}
if ( ! class_exists( 'WPCode_Library' ) ) {
require_once WPCODE_PLUGIN_PATH . 'includes/class-wpcode-library.php';
}
if ( ! class_exists( 'WPCode_Library_Auth' ) ) {
require_once WPCODE_PLUGIN_PATH . 'includes/class-wpcode-library-auth.php';
}
wpcode()->file_cache = new WPCode_File_Cache();
wpcode()->library = new WPCode_Library();
wpcode()->library_auth = new WPCode_Library_Auth();
}
// Use the library's search method.
if ( method_exists( wpcode()->library, 'search_snippets' ) ) {
$results = wpcode()->library->search_snippets( $keyword );
} else {
$data = wpcode()->library->get_data();
$all_snippets = $data['snippets'];
$results = array();
foreach ( $all_snippets as $snippet ) {
if (
stripos( $snippet['title'], $keyword ) !== false ||
( isset( $snippet['note'] ) && stripos( $snippet['note'], $keyword ) !== false )
) {
$results[] = $snippet;
}
}
}
// Format results for output.
$formatted_results = array();
foreach ( $results as $snippet ) {
$formatted_results[] = array(
'id' => isset( $snippet['id'] ) ? (string) $snippet['id'] : '',
'title' => isset( $snippet['title'] ) ? $snippet['title'] : '',
'description' => isset( $snippet['note'] ) ? $snippet['note'] : '',
'category' => isset( $snippet['categories'][0] ) ? $snippet['categories'][0] : '',
'tags' => isset( $snippet['tags'] ) ? $snippet['tags'] : array(),
);
}
return $formatted_results;
}
/**
* Execute get settings.
*
* @param array|null $input Input parameters (optional, not used).
*
* @return array
*/
public function execute_get_settings( $input = null ) {
return array(
'version' => WPCODE_VERSION,
'error_logging' => wpcode()->logger->is_enabled(),
'safe_mode_active' => $this->is_safe_mode_active(),
);
}
/**
* Check if WPCode Safe Mode is currently active.
*
* Safe Mode in WPCode is a per-request feature activated via the 'wpcode-safe-mode'
* query parameter. When active, all snippet execution is disabled for that request.
* It's primarily used for debugging when a snippet causes issues.
*
* @return bool
*/
private function is_safe_mode_active() {
// Safe Mode is determined by the presence of the query param and user capability.
// phpcs:ignore WordPress.Security.NonceVerification.Recommended
if ( ! isset( $_GET['wpcode-safe-mode'] ) ) {
return false;
}
// Only authenticated users with proper capability can use safe mode.
return current_user_can( 'wpcode_activate_snippets' );
}
}
new WPCode_Abilities_API();
@@ -0,0 +1,499 @@
<?php
/**
* This class adds the WPCode info to the admin bar for logged-in administrator users
* that can manage snippets (wpcode_activate_snippets capability).
* The class will gather info about the header & footer items added and all the active snippets
* and display a count of scripts/snippets added by wpcode after the page is fully loaded.
*/
/**
* Class WPCode_Admin_Bar_Info
*/
abstract class WPCode_Admin_Bar_Info {
/**
* The global locations disabled for the current page through the Page Scripts settings.
*
* @var array
*/
protected $global_disabled = array();
/**
* The snippets loaded on this page.
*
* @var array
*/
public $loaded_snippets = array();
/**
* The WPCode_Admin_Bar_Info constructor.
*/
public function __construct() {
add_action( 'plugins_loaded', array( $this, 'maybe_init' ), 1 );
}
/**
* Check if we should be tracking for the current session.
*
* @return bool
*/
public function should_track() {
if ( ! is_user_logged_in() ) {
return false;
}
if ( ! current_user_can( 'wpcode_activate_snippets' ) ) {
return false;
}
// Don't load the admin bar menu in headers & footers mode.
if ( wpcode()->settings->get_option( 'headers_footers_mode' ) ) {
return false;
}
$show_menu = wpcode()->settings->get_option( 'admin_bar_info', true );
if ( ! $show_menu ) {
return false;
}
return true;
}
/**
* Early on the plugins_loaded hook we check if we should be tracking for the current session.
*
* @return void
*/
public function maybe_init() {
if ( $this->should_track() ) {
$this->hooks();
}
}
/**
* Add hooks needed to track the way WPCode loads scripts and snippets.
*/
public function hooks() {
// Use the snippet output to more accurately track the snippets loaded.
add_filter( 'wpcode_snippet_output', array( $this, 'track_snippet_output' ), 999, 2 );
// Add an admin menu item to display the results.
add_action( 'admin_bar_menu', array( $this, 'add_admin_bar_info' ), 999 );
add_action( 'admin_bar_menu', array( $this, 'add_admin_bar_quick_links' ), 1200 );
// Output results at the end of the page and use JS to populate the admin menu item.
add_action( 'wp_footer', array( $this, 'add_footer_info' ), 15 );
add_action( 'admin_footer', array( $this, 'add_footer_info' ), 999999 );
add_action( 'admin_init', array( $this, 'enqueue_scripts' ), - 5 );
add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_scripts' ), 15 );
add_action( 'template_redirect', array( $this, 'enqueue_scripts' ), - 5 );
}
/**
* Load the scripts used by the admin bar.
*
* @return void
*/
public function enqueue_scripts() {
if ( ! is_admin_bar_showing() ) {
return;
}
// Allow other plugins to modify the screens where the admin bar scripts are loaded.
if ( apply_filters( 'wpcode_load_admin_bar_scripts', false ) ) {
return;
}
$admin_asset_file = WPCODE_PLUGIN_PATH . 'build/admin-bar.asset.php';
if ( ! file_exists( $admin_asset_file ) ) {
return;
}
$asset = require $admin_asset_file;
wp_enqueue_style( 'wpcode-admin-bar-css', WPCODE_PLUGIN_URL . 'build/admin-bar.css', null, $asset['version'] );
wp_enqueue_script( 'wpcode-admin-bar-js', WPCODE_PLUGIN_URL . 'build/admin-bar.js', null, $asset['version'], true );
}
/**
* Add the WPCode info to the admin bar.
*
* @param WP_Admin_Bar $wp_admin_bar The WP_Admin_Bar instance.
*/
public function add_admin_bar_info( $wp_admin_bar ) {
// Let's see if we have any errors.
$error_count = wpcode()->error->get_error_count();
$indicator = '';
if ( $error_count > 0 ) {
$indicator = ' <div class="wp-core-ui wp-ui-notification wpcode-menu-notification-counter">' . $error_count . '</div>';
}
// Add an admin menu item to append our count to.
$wp_admin_bar->add_menu(
array(
'id' => 'wpcode-admin-bar-info',
'title' => 'WPCode' . $indicator,
'meta' => array(
'class' => 'wpcode-admin-bar-info menupop',
),
'href' => add_query_arg( 'page', 'wpcode', admin_url( 'admin.php' ) ),
)
);
do_action( 'wpcode_admin_bar_info_top', $wp_admin_bar );
if ( ! empty( $error_count ) ) {
$wp_admin_bar->add_menu(
array(
'id' => 'wpcode-error-count',
'parent' => 'wpcode-admin-bar-info',
'title' => esc_html__( 'Snippets With Errors', 'insert-headers-and-footers' ) . $indicator,
'meta' => array(
'class' => 'wpcode-admin-bar-info-submenu',
),
'href' => add_query_arg(
array(
'page' => 'wpcode',
'view' => 'has_error',
),
admin_url( 'admin.php' )
),
)
);
}
$wp_admin_bar->add_menu(
array(
'id' => 'wpcode-description',
'parent' => 'wpcode-admin-bar-info',
'title' => esc_html__( 'Loaded on this page', 'insert-headers-and-footers' ),
'meta' => array(
'class' => 'wpcode-admin-bar-info-submenu wpcode-admin-bar-description',
),
)
);
$global_scripts_data = $this->get_global_scripts_data();
if ( ! empty( $global_scripts_data ) ) {
// Calculate total by adding up the "count" property of each item.
$total = array_sum( wp_list_pluck( $global_scripts_data, 'count' ) );
$wp_admin_bar->add_menu(
array(
'id' => 'wpcode-global-scripts',
'parent' => 'wpcode-admin-bar-info',
'title' => esc_html(
sprintf(
// translators: %d is the total number of global scripts.
__( 'Global Scripts (%d)', 'insert-headers-and-footers' ),
$total
)
),
'meta' => array(
'class' => 'wpcode-admin-bar-info-submenu',
),
'href' => add_query_arg( 'page', 'wpcode-headers-footers', admin_url( 'admin.php' ) ),
)
);
foreach ( $global_scripts_data as $id => $global_scripts_area ) {
$wp_admin_bar->add_menu(
array(
'id' => 'wpcode-global-' . $id,
'parent' => 'wpcode-global-scripts',
'title' => esc_html( $global_scripts_area['label'] ),
'meta' => array(
'class' => 'wpcode-admin-bar-info-submenu',
),
'href' => $global_scripts_area['href'],
)
);
}
}
$wp_admin_bar->add_menu(
array(
'id' => 'wpcode-loaded-on-this-page',
'parent' => 'wpcode-admin-bar-info',
'title' => esc_html__( 'Code Snippets', 'insert-headers-and-footers' ),
'meta' => array(
'class' => 'wpcode-admin-bar-info-submenu',
),
'href' => add_query_arg( 'page', 'wpcode', admin_url( 'admin.php' ) ),
)
);
$wp_admin_bar->add_menu(
array(
'id' => 'wpcode-admin-bar-info-replace',
'parent' => 'wpcode-loaded-on-this-page',
'title' => '',
'meta' => array(
'class' => 'wpcode-admin-bar-info-submenu',
),
)
);
}
/**
* Use the filter called in each location to keep tabs of which snippets were actually loaded in each location.
*
* @param WPCode_Snippet[] $snippets Array of snippets.
* @param string $location The location.
*
* @return mixed
*/
public function track_used_snippets( $snippets, $location ) {
foreach ( $snippets as $snippet ) {
if ( ! isset( $this->loaded_snippets[ $location ] ) ) {
$this->loaded_snippets[ $location ] = array();
}
$this->loaded_snippets[ $location ][] = $snippet;
}
return $snippets;
}
/**
* Output a script that builds the admin bar menu with the snippet/scripts info using JS after the page has loaded.
*
* @return void
*/
public function add_footer_info() {
if ( ! is_admin_bar_showing() ) {
return;
}
$footer_info = array();
foreach ( $this->loaded_snippets as $location => $snippets ) {
$location_label = wpcode()->auto_insert->get_location_label( $location );
if ( 'shortcode' === $location ) {
$location_label = esc_html__( 'Shortcode', 'insert-headers-and-footers' );
}
if ( 'block' === $location ) {
$location_label = esc_html__( 'Gutenberg Block', 'insert-headers-and-footers' );
}
if ( 0 === strpos( $location, 'shortcode-' ) ) {
$location_label = esc_html__( 'Custom Shortcode', 'insert-headers-and-footers' );
}
$location_info = array(
'label' => $location_label . ' (' . count( $snippets ) . ')',
'location_id' => $location,
'snippets' => array(),
'href' => $this->get_location_filter_link( $location ),
);
foreach ( $snippets as $snippet ) {
$location_info['snippets'][] = array(
'id' => $snippet->get_id(),
'title' => esc_html( $snippet->get_title() ),
'edit_link' => $this->get_snippet_edit_link( $snippet ),
);
}
$location_info['count'] = count( $snippets );
$footer_info[] = $location_info;
}
$total_count = 0;
foreach ( $footer_info as $location ) {
$total_count += $location['count'];
}
// Output $footer_info as a JSON in a JS variable to be used in the script to populate the admin bar.
?>
<script>
var wpcode_admin_bar_info = <?php echo wp_json_encode( $footer_info ); ?>;
var wpcode_admin_bar_info_count = <?php echo absint( $total_count ); ?>;
</script>
<?php
}
/**
* Get the snippet edit link based on the snippet id.
*
* @param WPCode_Snippet $snippet The snippet object.
*
* @return string
*/
public function get_snippet_edit_link( $snippet ) {
return apply_filters( 'wpcode_admin_bar_edit_snippet_link', admin_url( 'admin.php?page=wpcode-snippet-manager&snippet_id=' . $snippet->get_id() ), $snippet );
}
/**
* Get data related to the global Header & Footer scripts.
*
* @return array
*/
public function get_global_scripts_data() {
if ( is_admin() ) {
// Global scripts are never loaded in the admin.
return array();
}
$data = array();
$global_locations = array(
'header' => array(
'label' => __( 'Global Header', 'insert-headers-and-footers' ),
),
);
if ( function_exists( 'wp_body_open' ) && version_compare( get_bloginfo( 'version' ), '5.2', '>=' ) ) {
$global_locations['body'] = array(
'label' => __( 'Global Body', 'insert-headers-and-footers' ),
);
}
$global_locations['footer'] = array(
'label' => __( 'Global Footer', 'insert-headers-and-footers' ),
);
$disabled_label = esc_html__( 'Disabled via Page Scripts', 'insert-headers-and-footers' );
foreach ( $global_locations as $location => $location_texts ) {
$scripts = get_option( 'ihaf_insert_' . $location );
$count = ! empty( $scripts ) ? 1 : 0;
if ( in_array( $location, $this->global_disabled, true ) ) {
$count = 0;
$location_texts['label'] .= ' (' . $disabled_label . ')';
} else {
$location_texts['label'] .= ' (' . $count . ')';
}
$data[ $location ] = array(
'label' => $location_texts['label'],
'href' => admin_url( 'admin.php?page=wpcode-headers-footers#wpcode-global-' . $location ),
'count' => $count,
);
}
return $data;
}
/**
* Add the WPCode info to the admin bar.
*
* @param WP_Admin_Bar $wp_admin_bar The WP_Admin_Bar instance.
*/
public function add_admin_bar_quick_links( $wp_admin_bar ) {
$wp_admin_bar->add_menu(
array(
'id' => 'wpcode-admin-bar-info-add-new',
'parent' => 'wpcode-admin-bar-info',
'title' => esc_html__( '+ Add Snippet', 'insert-headers-and-footers' ),
'href' => admin_url( 'admin.php?page=wpcode-snippet-manager' ),
'meta' => array(
'class' => 'wpcode-admin-bar-info-submenu wpcode-admin-bar-info-separator-top',
),
)
);
$wp_admin_bar->add_menu(
array(
'id' => 'wpcode-admin-bar-info-settings',
'parent' => 'wpcode-admin-bar-info',
'title' => esc_html__( 'Settings', 'insert-headers-and-footers' ),
'href' => add_query_arg( 'page', 'wpcode-settings', admin_url( 'admin.php' ) ),
'meta' => array(
'class' => 'wpcode-admin-bar-info-submenu',
),
)
);
// If error logging is enabled add a direct link here.
if ( wpcode()->settings->get_option( 'error_logging' ) ) {
$wp_admin_bar->add_menu(
array(
'id' => 'wpcode-admin-bar-info-error-logs',
'parent' => 'wpcode-admin-bar-info',
'title' => esc_html__( 'Logs', 'insert-headers-and-footers' ),
'href' => add_query_arg(
array(
'page' => 'wpcode-tools',
'view' => 'logs',
),
admin_url( 'admin.php' )
),
'meta' => array(
'class' => 'wpcode-admin-bar-info-submenu',
),
)
);
}
$wp_admin_bar->add_menu(
array(
'id' => 'wpcode-admin-bar-info-help',
'parent' => 'wpcode-admin-bar-info',
'title' => esc_html__( 'Help Docs', 'insert-headers-and-footers' ),
'href' => wpcode_utm_url( 'https://wpcode.com/docs/', 'admin-bar', 'help' ),
'meta' => array(
'class' => 'wpcode-admin-bar-info-submenu',
'target' => '_blank',
'rel' => 'noopener noreferrer',
),
)
);
}
/**
* Track a snippet output for the admin bar.
*
* @param string $output The snippet output (we don't use this).
* @param WPCode_Snippet $snippet The snippet object.
*
* @return string
*/
public function track_snippet_output( $output, $snippet ) {
$location = $snippet->get_location();
if ( ! isset( $this->loaded_snippets[ $location ] ) ) {
$this->loaded_snippets[ $location ] = array();
}
$this->loaded_snippets[ $location ][] = $snippet;
return $output;
}
/**
* Method for the location link.
*
* @param string $location The location slug.
*
* @return string
*/
public function get_location_filter_link( $location ) {
if ( in_array( $location, array( 'shortcode', 'block' ), true ) ) {
// If this is for a shortcode or a block let's try to link to the edit page of the currently loaded post.
return get_edit_post_link();
}
return esc_url(
add_query_arg(
array(
'page' => 'wpcode',
'location' => $location,
'filter_action' => 'filter',
),
admin_url( 'admin.php' )
)
);
}
}
@@ -0,0 +1,163 @@
<?php
/**
* Central handler of auto-inserting snippets.
* Loads the different types and processes them.
*
* @package WPCode
*/
/**
* Class WPCode_Auto_Insert.
*/
class WPCode_Auto_Insert {
/**
* The auto-insert types.
*
* @var array
*/
public $types = array();
/**
* The auto-insert categories.
*
* @var array
*/
public $type_categories = array();
public $categories_with_labels;
/**
* Constructor.
*/
public function __construct() {
$this->hooks();
}
/**
* Add hooks.
*
* @return void
*/
private function hooks() {
add_action( 'plugins_loaded', array( $this, 'load_types' ), 1 );
}
/**
* Define the categories of auto-insert types.
*
* @return void
*/
public function define_category_label() {
$categories_labels = array(
'global' => __( 'Global', 'insert-headers-and-footers' ),
'page' => __( 'Page-Specific', 'insert-headers-and-footers' ),
'ecommerce' => __( 'eCommerce', 'insert-headers-and-footers' ),
);
// Add the labels to the $this->type_categories array.
foreach ( $categories_labels as $key => $category ) {
$this->type_categories[ $key ]['label'] = $category;
}
$this->categories_with_labels = true;
}
/**
* Load and initialize the different types of auto-insert types.
*
* @return void
*/
public function load_types() {
require_once WPCODE_PLUGIN_PATH . 'includes/auto-insert/class-wpcode-auto-insert-type.php';
require_once WPCODE_PLUGIN_PATH . 'includes/auto-insert/class-wpcode-auto-insert-everywhere.php';
require_once WPCODE_PLUGIN_PATH . 'includes/auto-insert/class-wpcode-auto-insert-site-wide.php';
require_once WPCODE_PLUGIN_PATH . 'includes/auto-insert/class-wpcode-auto-insert-single.php';
require_once WPCODE_PLUGIN_PATH . 'includes/auto-insert/class-wpcode-auto-insert-archive.php';
require_once WPCODE_PLUGIN_PATH . 'includes/auto-insert/class-wpcode-auto-insert-admin.php';
}
/**
* Register an auto-insert type.
*
* @param WPCode_Auto_Insert_Type $type The type to add to the available types.
*
* @return void
*/
public function register_type( $type ) {
$type_name = $type->name ?? '';
$this->types[ $type_name ] = $type;
if ( isset( $type->category ) ) {
$type_category = $type->category ?? '';
$this->type_categories[ $type_category ]['types'][ $type_name ] = $type;
}
}
/**
* Get the types of auto-insert options.
*
* @return WPCode_Auto_Insert_Type[]
*/
public function get_types() {
return $this->types;
}
/**
* Get the categories of auto-insert options.
*
* @return array
*/
public function get_type_categories() {
if ( ! isset( $this->categories_with_labels ) ) {
$this->define_category_label();
}
return $this->type_categories;
}
/**
* Get the categories info for the sidebar admin view.
*
* @return array
*/
public function get_type_categories_for_sidebar() {
$sidebar_categories = array();
$categories = $this->get_type_categories();
foreach ( $categories as $key => $category ) {
$sidebar_categories[] = array(
'slug' => $key,
'name' => $category['label'],
);
}
return $sidebar_categories;
}
/**
* Get a location label from the class not the term.
*
* @param string $location The location slug/name.
*
* @return string
*/
public function get_location_label( $location ) {
foreach ( $this->types as $type ) {
/**
* Added for convenience.
*
* @var WPCode_Auto_Insert_Type $type
*/
$locations = $type->get_locations();
if ( isset( $locations[ $location ] ) ) {
if ( isset( $locations[ $location ]['label'] ) ) {
return $locations[ $location ]['label'];
} else {
return $locations[ $location ];
}
}
}
return '';
}
}
@@ -0,0 +1,58 @@
<?php
/**
* Manage custom capabilities for WPCode.
*
* @package WPCode
*/
/**
* The WPCode_Capabilities class.
*/
class WPCode_Capabilities {
/**
* Function to call on plugin activation.
*
* @return void
*/
public static function add_capabilities() {
foreach ( self::get_roles() as $role ) {
if ( $role->has_cap( 'manage_options' ) ) {
$role->add_cap( 'wpcode_edit_snippets' );
$role->add_cap( 'wpcode_activate_snippets' );
}
}
}
/**
* Get roles as WP_Role objects.
*
* @return WP_Role[]
*/
public static function get_roles() {
$roles = wp_roles()->roles;
$role_array = array();
foreach ( array_keys( $roles ) as $role_key ) {
$role_array[] = get_role( $role_key );
}
return $role_array;
}
/**
* Remove custom capabilities.
*
* @return void
*/
public static function uninstall() {
foreach ( self::get_roles() as $role ) {
if ( $role->has_cap( 'wpcode_edit_snippets' ) ) {
$role->remove_cap( 'wpcode_edit_snippets' );
}
if ( $role->has_cap( 'wpcode_activate_snippets' ) ) {
$role->remove_cap( 'wpcode_activate_snippets' );
}
}
}
}
@@ -0,0 +1,188 @@
<?php
/**
* Handle logic for the conditional loading of snippets.
* You'll find here the available logic options and how they apply to snippets.
*
* @package WPCode
*/
/**
* The main conditional logic class that loads all the types.
*/
class WPCode_Conditional_Logic {
/**
* Types of conditional logic.
*
* @var WPCode_Conditional_Type[]
*/
private $types = array();
/**
* Constructor.
*/
public function __construct() {
add_action( 'plugins_loaded', array( $this, 'load_types' ), 0 );
}
/**
* Load the different conditional logic types.
*
* @return void
*/
public function load_types() {
require_once WPCODE_PLUGIN_PATH . 'includes/conditional-logic/class-wpcode-conditional-type.php';
require_once WPCODE_PLUGIN_PATH . 'includes/conditional-logic/class-wpcode-conditional-user.php';
require_once WPCODE_PLUGIN_PATH . 'includes/conditional-logic/class-wpcode-conditional-page.php';
}
/**
* Register an auto-insert type.
*
* @param WPCode_Conditional_Type $type The type to add to the available types.
*
* @return void
*/
public function register_type( $type ) {
$type_name = $type->name ?? '';
$this->types[ $type_name ] = $type;
}
/**
* Get all the admin options for the conditional logic form.
*
* @param bool $for_js Whether to return the options for JS or not.
*
* @return array
*/
public function get_all_admin_options( $for_js = false ) {
$options = array();
foreach ( $this->types as $type ) {
$type->load_type_options(); // Reload the options in case a global snippet made them get loaded before some post types were registered, for example.
$options[ $type->get_name() ] = array(
'label' => $type->get_label(),
'name' => $type->get_name(),
'category' => $type->get_category(),
'options' => $type->get_type_options(),
);
}
// Sort options so the unavailable ones are at the end.
$available_options = array();
$unavailable_options = array();
foreach ( $options as $key => $option ) {
if ( empty( $option['options'] ) ) {
continue;
}
$first_option = reset( $option['options'] );
if ( ! empty( $first_option['upgrade'] ) ) {
$unavailable_options[ $key ] = $option;
} else {
$available_options[ $key ] = $option;
}
}
// For the user logged_in option let's run esc_attr on the option values to save the values correctly.
if ( $for_js && isset( $available_options['user']['options']['logged_in']['options'] ) ) {
foreach ( $available_options['user']['options']['logged_in']['options'] as $key => $option ) {
$available_options['user']['options']['logged_in']['options'][ $key ]['value'] = esc_attr( $option['value'] );
}
}
return apply_filters( 'wpcode_conditional_logic_admin_options', array_merge( $available_options, $unavailable_options ) );
}
/**
* Goes through a list of snippets and filters out the ones
* that don't match the conditional logic rules.
*
* @param WPCode_Snippet[] $snippets An array of snippets.
*
* @return WPCode_Snippet[]
*/
public function check_snippets_conditions( $snippets ) {
// If there's nothing to evaluate just return an empty array.
if ( empty( $snippets ) ) {
return array();
}
$filtered_snippets = array();
foreach ( $snippets as $snippet ) {
if ( ! $snippet->conditional_rules_enabled() ) {
// If rules are disabled, ignore.
$filtered_snippets[] = $snippet;
continue;
}
$rules = $snippet->get_conditional_rules();
if ( ! isset( $rules['show'] ) ) {
continue;
}
$show = 'show' === $rules['show'];
$rules_are_met = $this->are_snippet_rules_met( $snippet );
if ( $show && ! $rules_are_met ) {
// If we should show based on conditions, and conditions
// are not met, skip.
continue;
}
if ( ! $show && $rules_are_met ) {
// If we should hide based on conditions, and conditions
// are met, skip.
continue;
}
$filtered_snippets[] = $snippet;
}
return $filtered_snippets;
}
/**
* Takes a snippet and evaluates if conditional logic rules
* are met.
*
* @param WPCode_Snippet $snippet The snippet instance.
*
* @return bool
*/
public function are_snippet_rules_met( $snippet ) {
$rules = $snippet->get_conditional_rules();
if ( empty( $rules ) || ! is_array( $rules ) || empty( $rules['groups'] ) ) {
return true;
}
// Go through all rule groups.
foreach ( $rules['groups'] as $rule_group ) {
// If any of the groups are met return true.
if ( $this->are_group_rules_met( $rule_group, $snippet ) ) {
return true;
}
}
// If no group rules satisfy the conditions, return false.
return false;
}
/**
* Evaluate all the rows of rules in a group.
*
* @param array $rule_group An array of rows.
* @param WPCode_Snippet $snippet The snippet we are evaluating the rules for.
*
* @return bool
*/
public function are_group_rules_met( $rule_group, $snippet ) {
foreach ( $rule_group as $rule_row ) {
if ( ! isset( $rule_row['type'] ) || ! isset( $this->types[ $rule_row['type'] ] ) ) {
continue;
}
$rule_type = $this->types[ $rule_row['type'] ];
if ( ! $rule_type->evaluate_rule_row( $rule_row, $snippet ) ) {
// If this row doesn't match, the whole group fails.
return false;
}
}
// If none of the rows failed the group matches.
return true;
}
}
@@ -0,0 +1,338 @@
<?php
/**
* This class handles PHP errors, keeping tabs of errors thrown
* and the messages displayed back to the user.
*
* @package wpcode
*/
/**
* WPCode_Error class.
*/
class WPCode_Error {
/**
* An array of errors already caught.
*
* @var array
*/
private $errors = array();
/**
* The error count.
*
* @var int
*/
private $error_count;
/**
* The snippets that have errors.
*
* @var int[]
*/
private $snippets_with_errors;
/**
* The previous exception handler.
*
* @var callable
*/
private $previous_exception_handler;
/**
* WPCode_Error constructor.
*/
public function __construct() {
// When the admin is loaded let's check if there were any errors recorded.
add_action( 'admin_init', array( $this, 'gather_errors' ) );
$this->previous_exception_handler = set_exception_handler( array( $this, 'track_errors' ) );
}
/**
* The error object caught when running the code.
*
* @param ParseError|Exception|Error|array $error The caught error.
*
* @return void
*/
public function add_error( $error ) {
$this->errors[] = $error;
$this->write_error_to_log( $error );
}
/**
* Check if an error has been recorded.
*
* @return bool
*/
public function has_error() {
return ! empty( $this->errors );
}
/**
* Empty the errors record, useful if you want to
* make sure the last error was thrown by your code.
*
* @return void
*/
public function clear_errors() {
$this->errors = array();
}
/**
* Store the error in the logs.
*
* @param array|Exception $error The error object.
*
* @return void
*/
private function write_error_to_log( $error ) {
$handle = 'error';
if ( is_array( $error ) && isset( $error['snippet'] ) ) {
$this->track_snippet_error( $error );
}
wpcode()->logger->handle( time(), $this->get_error_message( $error ), $handle );
}
/**
* Log the error in the snippet specific log and mark the snippet as having an error.
*
* @param array $error The error object.
*
* @return void
*/
private function track_snippet_error( $error ) {
if ( ! isset( $error['snippet'] ) ) {
return;
}
if ( is_int( $error['snippet'] ) ) {
$snippet = new WPCode_Snippet( absint( $error['snippet'] ) );
} else {
$snippet = $error['snippet'];
}
// Let's see if the snippet is currently marked as having an error.
if ( ! isset( $snippet->id ) ) {
return;
}
if ( empty( $error['wpc_type'] ) ) {
$error['wpc_type'] = 'error';
}
$last_error = $snippet->get_last_error();
// If we already have an error and the type of the current error is not deactivated let's not log it.
if ( ! empty( $last_error ) && 'deactivated' === $last_error['wpc_type'] || ! empty( $last_error ) && $last_error['wpc_type'] === $error['wpc_type'] ) {
return;
}
if ( ! isset( $error['time'] ) ) {
$error['time'] = time();
}
$handle = 'snippet-' . $snippet->get_id();
// Log to snippet specific log.
wpcode()->logger->handle( time(), $this->get_error_message( $error ), $handle );
// Store the error details in the snippet meta.
$snippet->set_last_error( $error );
do_action( 'wpcode_snippet_error_tracked', $error, $snippet );
// Reset the error count.
$this->clear_snippets_errors();
}
/**
* Get the last error message.
*
* @return string
*/
public function get_last_error_message() {
if ( empty( $this->errors ) ) {
return '';
}
$last_error = end( $this->errors );
return $this->get_error_message( $last_error );
}
/**
* Get the error message from the error object, either an array or an Exception object.
*
* @param array|Exception $error The error object.
*
* @return string
*/
public function get_error_message( $error ) {
if ( is_array( $error ) && isset( $error['message'] ) ) {
return $error['message'];
}
if ( ! is_array( $error ) && method_exists( $error, 'getMessage' ) ) {
return $error->getMessage();
}
return '';
}
/**
* Get the short version of the error message without the file and line number.
*
* @param string $message The error message.
*
* @return string
*/
public function get_error_message_short( $message ) {
$pattern = '/^([^:]+: .+?) in/';
if ( preg_match( $pattern, $message, $matches ) ) {
$message = $matches[1];
}
return $message;
}
/**
* Set the error count.
*
* @param int $count The error count.
*
* @return void
*/
private function set_error_count( $count ) {
$this->error_count = $count;
}
/**
* Set the snippets that have errors.
*
* @param int[] $snippets Ids of the snippets with errors.
*
* @return void
*/
private function set_snippets_with_errors( $snippets ) {
update_option( 'wpcode_snippets_errors', $snippets );
}
/**
* Clear the persistent error count.
*
* @return void
*/
public function clear_snippets_errors() {
unset( $this->error_count );
delete_option( 'wpcode_snippets_errors' );
$this->snippets_with_errors = false;
$this->gather_errors();
}
/**
* Get the error count.
*
* @return int
*/
public function get_error_count() {
if ( ! isset( $this->error_count ) ) {
$snippets_with_errors = $this->get_snippets_with_errors();
$this->error_count = is_array( $snippets_with_errors ) ? count( $snippets_with_errors ) : 0;
}
return $this->error_count;
}
/**
* Get the snippets that have errors.
*
* @return int[]
*/
public function get_snippets_with_errors() {
if ( ! isset( $this->snippets_with_errors ) ) {
$this->snippets_with_errors = get_option( 'wpcode_snippets_errors' );
}
return $this->snippets_with_errors;
}
/**
* Let's query all the snippets that have an error set to them.
*
* @return void
*/
public function gather_errors() {
// If we already have an error count, no need to query the db.
if ( false !== $this->get_snippets_with_errors() ) {
return;
}
$snippets = get_posts(
array(
'post_type' => 'wpcode',
'posts_per_page' => - 1,
'post_status' => 'any',
'meta_query' => array( // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query
'relation' => 'OR',
array(
'key' => '_wpcode_last_error',
'compare' => 'EXISTS',
),
),
'fields' => 'ids',
)
);
$this->set_snippets_with_errors( $snippets );
$this->set_error_count( count( $snippets ) );
}
/**
* Track errors thrown by PHP.
*
* @param Throwable $e The error or exception object.
*
* @return void
*/
public function track_errors( $e ) {
$error = array(
'line' => $e->getLine(),
'file' => $e->getFile(),
'message' => $e->getMessage(),
'type' => 'error',
);
if ( wpcode()->execute->is_error_from_wpcode( $error ) && ! empty( $error['line'] ) ) {
$snippet = wpcode()->execute->snippet_executed;
if ( ! empty( $snippet ) && ! wpcode()->execute->snippet_location_disable( $snippet ) ) {
$error['snippet'] = $snippet;
$error['error_line'] = $error['line'];
// Let's try to determine on which page we are and potentially save that URL in the error details.
global $wp;
if ( isset( $wp->request ) ) {
$error['url'] = home_url( $wp->request );
}
wpcode()->error->add_error( $error );
}
}
$this->call_previous_exception_handler( $e );
}
/**
* Call the previous exception handler.
*
* @param Throwable $e The error or exception object.
*
* @return void
* @throws Throwable The error or exception object.
*/
private function call_previous_exception_handler( $e ) {
if ( isset( $this->previous_exception_handler ) ) {
call_user_func( $this->previous_exception_handler, $e );
} else {
throw $e;
}
exit();
}
}
@@ -0,0 +1,226 @@
<?php
/**
* File cache class. Store files in the uploads folder.
* Use the expiration in the get function to control how often a file should be refreshed.
*
* @package WPCode
*/
/**
* WPCode_File_Cache class.
*/
class WPCode_File_Cache {
/**
* Name of the base folder in the Uploads folder.
*
* @var string
*/
private $basedir = 'wpcode';
/**
* Name of the module-specific folder in the base folder.
*
* @var string
*/
private $dirname = 'cache';
/**
* Full upload path, created form the WP uploads folder.
*
* @var string
*/
private $upload_path;
/**
* Write a file to the server with an expiration date.
*
* @param string $name The key by which to retrieve the data.
* @param mixed $data The data to save - if it's a JSON it should be decoded first as it gets encoded here.
*
* @return void
*/
public function set( $name, $data ) {
$this->write_file( $this->get_cache_filename_by_key( $name ), wp_json_encode( $data ) );
}
/**
* Get some data by its name. Checks if the data is expired and if so
* returns false so you can update it.
*
* @param string $name The key of the data to save.
* @param int $ttl For how long since creation should this file be used.
*
* @return array|false
*/
public function get( $name, $ttl = 0 ) {
$file = $this->get_directory_path( $this->get_cache_filename_by_key( $name ) );
/**
* Filter the $ttl for a file if you want to change it.
*
* @param int $ttl The time to live for the cache.
* @param string $name The name of the file.
*
* @return int
* @since 2.2.2
*/
$ttl = apply_filters( 'wpcode_file_cache_ttl', $ttl, $name );
// If the file doesn't exist there's not much to do.
if ( ! file_exists( $file ) ) {
// Let's see if we have it in the database.
$option = get_option( 'wpcode_alt_cache_' . $name, false );
if ( false !== $option ) {
// Let's check if the time since the option was saved is less than the TTL.
if ( empty( $option['time'] ) || $ttl > 0 && (int) $option['time'] + $ttl < time() ) {
// If the option expired let's delete it, so we clean up in case the file will now work.
delete_option( 'wpcode_alt_cache_' . $name );
return false;
}
return json_decode( $option['data'], true );
}
return false;
}
// If TTL is 0, always return the file.
if ( $ttl > 0 && (int) filemtime( $file ) + $ttl < time() ) {
return false;
}
return json_decode( file_get_contents( $file ), true ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents
}
/**
* Delete a cached file by its key.
*
* @param string $key The key to find the file by.
*
* @return void
*/
public function delete( $key ) {
$file = $this->get_directory_path( $this->get_cache_filename_by_key( $key ) );
wp_delete_file( $file );
delete_option( 'wpcode_alt_cache_' . $key );
}
/**
* Basically just adds JSON to the end of the key but we should use this
* to also make sure it's a proper filename.
*
* @param string $name The key.
*
* @return string
*/
private function get_cache_filename_by_key( $name ) {
return $name . '.json';
}
/**
* Write a file to the cache folder. Data should already be processed when using this.
*
* @param string $name The name of the file.
* @param string $data The data to write to the file.
*
* @return void
*/
private function write_file( $name, $data ) {
$written = file_put_contents( $this->get_directory_path( $name ), $data ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_file_put_contents
if ( false === $written ) {
// If we can't save the file to the file cache let's try to save it to the database.
// This is not ideal but it prevents having endless requests.
// phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_read_file_put_contents
$option = array(
'time' => time(),
'data' => $data,
);
// $name is the file name, in order to save it in the db we should remove the file extension.
$name = str_replace( '.json', '', $name );
update_option( 'wpcode_alt_cache_' . $name, $option, false );
}
}
/**
* Get a reliable path to write files to, it also creates the folders needed if they don't exist.
*
* @param string $filename The file path.
*
* @return string
*/
private function get_directory_path( $filename ) {
if ( ! isset( $this->upload_path ) ) {
$uploads = wp_upload_dir();
$base_path = trailingslashit( $uploads['basedir'] ) . $this->basedir;
$this->upload_path = $base_path . '/' . $this->dirname;
if ( ! file_exists( $this->upload_path ) || ! wp_is_writable( $this->upload_path ) ) {
wp_mkdir_p( $this->upload_path );
$this->create_index_html_file( $this->upload_path );
}
// Ensure the base path has an index file.
$this->create_index_html_file( $base_path );
}
$filepath = trailingslashit( $this->upload_path ) . $filename;
$directory = dirname( $filepath );
if ( $directory !== $this->upload_path && ! file_exists( $directory ) ) {
wp_mkdir_p( $directory );
$this->create_index_html_file( $directory );
}
$this->create_index_html_file( $this->upload_path );
return $filepath;
}
/**
* Create index.html file in the specified directory if it doesn't exist.
*
* @param string $path The path to the directory.
*
* @return false|int
*/
public static function create_index_html_file( $path ) {
if ( ! is_dir( $path ) || is_link( $path ) ) {
return false;
}
$index_file = wp_normalize_path( trailingslashit( $path ) . 'index.html' );
// Do nothing if index.html exists in the directory.
if ( file_exists( $index_file ) ) {
return false;
}
// Create empty index.html.
return file_put_contents( $index_file, '' ); // phpcs:ignore WordPress.WP.AlternativeFunctions
}
/**
* Create .htaccess file in the specified directory if it doesn't exist.
*
* @param string $path The path to the directory.
*
* @return false|int
*/
public static function create_htaccess_file( $path ) {
if ( ! is_dir( $path ) || is_link( $path ) ) {
return false;
}
$htaccess_file = wp_normalize_path( trailingslashit( $path ) . '.htaccess' );
// Do nothing if index.html exists in the directory.
if ( file_exists( $htaccess_file ) ) {
return false;
}
// Create empty index.html.
return file_put_contents( $htaccess_file, 'deny from all' ); // phpcs:ignore WordPress.WP.AlternativeFunctions
}
}
@@ -0,0 +1,400 @@
<?php
/**
* This class handles logging errors to files.
*
* @package WPCode
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly.
}
/**
* WPCode_File_Logger class.
*/
class WPCode_File_Logger {
/**
* Open file handlers.
*
* @var array
*/
protected $handles = array();
/**
* Limit for log file size.
*
* @var int
*/
public $log_size_limit;
/**
* Cache logs that could not be written directly for writing them later.
*
* @var array
*/
protected $cached_logs = array();
/**
* Whether logging is enabled.
*
* @var bool
*/
public $enabled;
/**
* Constructor.
*
* @param int $log_size_limit File size limit for log files in bytes.
*/
public function __construct( $log_size_limit = null ) {
if ( null === $log_size_limit ) {
$log_size_limit = 5 * 1024 * 1024;
}
$this->log_size_limit = apply_filters( 'wpcode_log_file_size_limit', $log_size_limit );
add_action( 'plugins_loaded', array( $this, 'write_cached_logs' ) );
}
/**
* Close all open file handles.
*/
public function __destruct() {
foreach ( $this->handles as $handle ) {
if ( is_resource( $handle ) ) {
fclose( $handle ); // @codingStandardsIgnoreLine.
}
}
}
/**
* Write cached logs.
*/
public function write_cached_logs() {
foreach ( $this->cached_logs as $log ) {
$this->write( $log['entry'], $log['handle'] );
}
}
/**
* Format an entry for the log file.
*
* @param int $timestamp The timestamp for the log entry.
* @param string $message The error message.
*
* @return mixed|void
*/
public function format_entry( $timestamp, $message ) {
$time_string = date( 'c', $timestamp );// phpcs:ignore WordPress.DateTime.RestrictedFunctions.date_date
$entry = "{$time_string} {$message}";
return apply_filters(
'wpcode_format_log_entry',
$entry,
array(
'timestamp' => $timestamp,
'message' => $message,
)
);
}
/**
* Handle a direct request to log something & format it before writing.
*
* @param int $timestamp The timestamp for the log entry.
* @param string $message The error message.
* @param string $handle The log handle.
*
* @return void
*/
public function handle( $timestamp, $message, $handle ) {
if ( ! $this->is_enabled() ) {
return;
}
$entry = $this->format_entry( $timestamp, $message );
$this->write( $entry, $handle );
}
/**
* Write an entry to a log file by its handle.
*
* @param string $entry The entry text.
* @param string $handle The log handle.
*
* @return bool
*/
public function write( $entry, $handle ) {
$result = false;
if ( $this->should_rotate( $handle ) ) {
$this->log_rotate( $handle );
}
if ( $this->open( $handle ) && is_resource( $this->handles[ $handle ] ) ) {
$result = fwrite( $this->handles[ $handle ], $entry . PHP_EOL ); // @codingStandardsIgnoreLine.
} else {
$this->cache_log( $entry, $handle );
}
return false !== $result;
}
/**
* Should the log file be rotated? Returns true if the file is above the size limit.
*
* @param string $handle Log handle.
*
* @return bool
*/
public function should_rotate( $handle ) {
$file = self::get_file_path( $handle );
if ( $file ) {
if ( $this->is_open( $handle ) ) {
$file_stat = fstat( $this->handles[ $handle ] );
return $file_stat['size'] > $this->log_size_limit;
} elseif ( file_exists( $file ) ) {
return filesize( $file ) > $this->log_size_limit;
} else {
return false;
}
} else {
return false;
}
}
/**
* Rotate log files by adding a suffix up to 10.
*
* @param string $handle Log handle.
*/
protected function log_rotate( $handle ) {
for ( $i = 8; $i >= 0; $i -- ) {
$this->increment_log_infix( $handle, $i );
}
$this->increment_log_infix( $handle );
}
/**
* Increment a log file suffix.
*
* @param string $handle Log handle.
* @param null|int $number Optional. Default null. Log suffix number to be incremented.
*
* @return bool True if increment was successful, otherwise false.
*/
protected function increment_log_infix( $handle, $number = null ) {
if ( null === $number ) {
$suffix = '';
$next_suffix = '.0';
} else {
$suffix = '.' . $number;
$next_suffix = '.' . ( $number + 1 );
}
$rename_from = self::get_file_path( "{$handle}{$suffix}" );
$rename_to = self::get_file_path( "{$handle}{$next_suffix}" );
if ( $this->is_open( $rename_from ) ) {
$this->close( $rename_from );
}
if ( is_writable( $rename_from ) ) { // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_is_writable
return rename( $rename_from, $rename_to ); // phpcs:ignore WordPress.WP.AlternativeFunctions.rename_rename
} else {
return false;
}
}
/**
* Open a log file for writing.
*
* @param string $handle Log handle.
*
* @return bool
*/
public function open( $handle = 'log' ) {
if ( $this->is_open( $handle ) ) {
return true;
}
$file = self::get_file_path( $handle );
if ( $file ) {
if ( ! file_exists( $file ) ) {
$temphandle = @fopen( $file, 'w+' ); // @codingStandardsIgnoreLine.
if ( is_resource( $temphandle ) ) {
@fclose( $temphandle ); // @codingStandardsIgnoreLine.
if ( defined( 'FS_CHMOD_FILE' ) ) {
@chmod( $file, FS_CHMOD_FILE ); // @codingStandardsIgnoreLine.
}
}
}
$resource = @fopen( $file, 'a' ); // @codingStandardsIgnoreLine.
if ( $resource ) {
$this->handles[ $handle ] = $resource;
return true;
}
}
return false;
}
/**
* Close a log file.
*
* @param string $handle Log handle.
*
* @return void
*/
public function close( $handle = 'log' ) {
if ( $this->is_open( $handle ) ) {
@fclose( $this->handles[ $handle ] ); // @codingStandardsIgnoreLine.
unset( $this->handles[ $handle ] );
}
}
/**
* Check if a handle is open.
*
* @param string $handle Log handle.
*
* @return bool True if $handle is open.
*/
protected function is_open( $handle ) {
return array_key_exists( $handle, $this->handles ) && is_resource( $this->handles[ $handle ] );
}
/**
* Get the file path for a log handle.
*
* @param string $handle Log handle.
*
* @return string
*/
public static function get_file_path( $handle ) {
$date_suffix = date( 'Y-m-d', time() );// phpcs:ignore WordPress.DateTime.RestrictedFunctions.date_date
$hash_suffix = wp_hash( $handle );
$filename = sanitize_file_name( implode( '-', array( $handle, $date_suffix, $hash_suffix ) ) . '.log' );
return self::get_log_dir() . $filename;
}
/**
* Get the log directory path while also making sure it exists & we have an index.html and a .htaccess file in it.
*
* The existence checks run once per request for each path, keyed by path so multisite uploads switches stay correct.
*
* @return string
*/
public static function get_log_dir() {
static $ensured = array();
$uploads = wp_upload_dir();
$base_path = trailingslashit( $uploads['basedir'] ) . 'wpcode-logs/';
if ( isset( $ensured[ $base_path ] ) ) {
return $base_path;
}
$ensured[ $base_path ] = true;
wp_mkdir_p( $base_path );
// Only loaded upfront in admin/cron requests, needed here on any request.
if ( ! class_exists( 'WPCode_File_Cache', false ) ) {
require_once WPCODE_PLUGIN_PATH . 'includes/class-wpcode-file-cache.php';
}
if ( wp_is_writable( $base_path ) ) {
// Both no-op if the file exists; the unslashed path keeps their is_link() check working.
WPCode_File_Cache::create_index_html_file( untrailingslashit( $base_path ) );
WPCode_File_Cache::create_htaccess_file( untrailingslashit( $base_path ) );
}
return $base_path;
}
/**
* Store a log entry in the cache for writing later.
*
* @param string $entry Log entry.
* @param string $handle Log handle.
*
* @return void
*/
public function cache_log( $entry, $handle ) {
$this->cached_logs[] = array(
'entry' => $entry,
'handle' => $handle,
);
}
/**
* Is logging errors enabled?
*
* @return bool
*/
public function is_enabled() {
if ( ! isset( $this->enabled ) ) {
$this->enabled = boolval( wpcode()->settings->get_option( 'error_logging', false ) );
}
return $this->enabled;
}
/**
* Go through the logs folder and return a list of all .log files.
*
* @return array
*/
public function get_logs() {
$logs = array();
$files = glob( self::get_log_dir() . '*.log' );
if ( ! empty( $files ) ) {
foreach ( $files as $file ) {
$logs[] = array(
'filename' => basename( $file ),
'path' => $file,
'size' => filesize( $file ),
);
}
}
return $logs;
}
/**
* Delete a log file by its name.
*
* @param string $name Log name.
*
* @return void
*/
public function delete_log( $name ) {
// If the file doesn't include the .log extension, add it.
if ( ! preg_match( '/\.log$/', $name ) ) {
$name .= '.log';
}
$real_file_path = realpath( self::get_log_dir() . $name );
$real_base_path = realpath( self::get_log_dir() ) . DIRECTORY_SEPARATOR;
if ( false === $real_file_path || strpos( $real_file_path, $real_base_path ) !== 0 ) {
// Traversal attempt.
return;
}
// Delete the file from the server.
@unlink( $real_file_path ); // @codingStandardsIgnoreLine.
}
}
@@ -0,0 +1,189 @@
<?php
/**
* Load all generator types and expose them to the admin.
*
* @package WPCode
*/
/**
* The WPCode_Generator class.
*/
class WPCode_Generator {
/**
* The type of generators available.
*
* @var array
*/
public $types = array();
/**
* The available categories.
*
* @var array
*/
public $categories;
/**
* Constructor.
*/
public function __construct() {
$this->load_types();
}
/**
* Require and load all the generators.
*
* @return void
*/
public function load_types() {
require_once WPCODE_PLUGIN_PATH . 'includes/generator/class-wpcode-generator-type.php';
require_once WPCODE_PLUGIN_PATH . 'includes/generator/class-wpcode-generator-post-status.php';
require_once WPCODE_PLUGIN_PATH . 'includes/generator/class-wpcode-generator-post-type.php';
require_once WPCODE_PLUGIN_PATH . 'includes/generator/class-wpcode-generator-admin-bar.php';
require_once WPCODE_PLUGIN_PATH . 'includes/generator/class-wpcode-generator-contact-methods.php';
require_once WPCODE_PLUGIN_PATH . 'includes/generator/class-wpcode-generator-taxonomy.php';
require_once WPCODE_PLUGIN_PATH . 'includes/generator/class-wpcode-generator-script.php';
require_once WPCODE_PLUGIN_PATH . 'includes/generator/class-wpcode-generator-style.php';
require_once WPCODE_PLUGIN_PATH . 'includes/generator/class-wpcode-generator-hooks.php';
require_once WPCODE_PLUGIN_PATH . 'includes/generator/class-wpcode-generator-cronjob.php';
require_once WPCODE_PLUGIN_PATH . 'includes/generator/class-wpcode-generator-menu.php';
require_once WPCODE_PLUGIN_PATH . 'includes/generator/class-wpcode-generator-sidebar.php';
require_once WPCODE_PLUGIN_PATH . 'includes/generator/class-wpcode-generator-query.php';
require_once WPCODE_PLUGIN_PATH . 'includes/generator/class-wpcode-generator-widget.php';
require_once WPCODE_PLUGIN_PATH . 'includes/generator/class-wpcode-generator-schema-base.php';
// Schema generators.
require_once WPCODE_PLUGIN_PATH . 'includes/generator/class-wpcode-generator-schema-article.php';
require_once WPCODE_PLUGIN_PATH . 'includes/generator/class-wpcode-generator-schema-book.php';
require_once WPCODE_PLUGIN_PATH . 'includes/generator/class-wpcode-generator-schema-car.php';
require_once WPCODE_PLUGIN_PATH . 'includes/generator/class-wpcode-generator-schema-course.php';
require_once WPCODE_PLUGIN_PATH . 'includes/generator/class-wpcode-generator-schema-dataset.php';
require_once WPCODE_PLUGIN_PATH . 'includes/generator/class-wpcode-generator-schema-event.php';
require_once WPCODE_PLUGIN_PATH . 'includes/generator/class-wpcode-generator-schema-faq.php';
require_once WPCODE_PLUGIN_PATH . 'includes/generator/class-wpcode-generator-schema-fact-check.php';
require_once WPCODE_PLUGIN_PATH . 'includes/generator/class-wpcode-generator-schema-how-to.php';
require_once WPCODE_PLUGIN_PATH . 'includes/generator/class-wpcode-generator-schema-job-posting.php';
require_once WPCODE_PLUGIN_PATH . 'includes/generator/class-wpcode-generator-schema-movie.php';
require_once WPCODE_PLUGIN_PATH . 'includes/generator/class-wpcode-generator-schema-music.php';
require_once WPCODE_PLUGIN_PATH . 'includes/generator/class-wpcode-generator-schema-person.php';
require_once WPCODE_PLUGIN_PATH . 'includes/generator/class-wpcode-generator-schema-product.php';
require_once WPCODE_PLUGIN_PATH . 'includes/generator/class-wpcode-generator-schema-product-review.php';
require_once WPCODE_PLUGIN_PATH . 'includes/generator/class-wpcode-generator-schema-recipe.php';
require_once WPCODE_PLUGIN_PATH . 'includes/generator/class-wpcode-generator-schema-service.php';
require_once WPCODE_PLUGIN_PATH . 'includes/generator/class-wpcode-generator-schema-software.php';
require_once WPCODE_PLUGIN_PATH . 'includes/generator/class-wpcode-generator-schema-video.php';
$generators = array(
'WPCode_Generator_Admin_Bar',
'WPCode_Generator_Contact_Methods',
'WPCode_Generator_Cronjob',
'WPCode_Generator_Hooks',
'WPCode_Generator_Menu',
'WPCode_Generator_Post_Status',
'WPCode_Generator_Post_Type',
'WPCode_Generator_Script',
'WPCode_Generator_Sidebar',
'WPCode_Generator_Style',
'WPCode_Generator_Taxonomy',
'WPCode_Generator_Widget',
'WPCode_Generator_Query',
'WPCode_Generator_Schema',
// Schema generators.
'WPCode_Generator_Schema_Article',
'WPCode_Generator_Schema_Book',
'WPCode_Generator_Schema_Car',
'WPCode_Generator_Schema_Course',
'WPCode_Generator_Schema_Dataset',
'WPCode_Generator_Schema_Event',
'WPCode_Generator_Schema_FAQ',
'WPCode_Generator_Schema_Fact_Check',
'WPCode_Generator_Schema_How_To',
'WPCode_Generator_Schema_Job_Posting',
'WPCode_Generator_Schema_Movie',
'WPCode_Generator_Schema_Music',
'WPCode_Generator_Schema_Person',
'WPCode_Generator_Schema_Product',
'WPCode_Generator_Schema_Product_Review',
'WPCode_Generator_Schema_Recipe',
'WPCode_Generator_Schema_Service',
'WPCode_Generator_Schema_Software',
'WPCode_Generator_Schema_Video',
);
foreach ( $generators as $generator_class ) {
if ( ! class_exists( $generator_class ) ) {
continue;
}
$instance = new $generator_class();
$instance_name = $instance->name ?? '';
$this->types[ $instance_name ] = $instance;
}
// Sort by displayed title.
uasort(
$this->types,
function ( $a, $b ) {
return strcmp( $a->title, $b->title );
}
);
}
/**
* Load all the categories with their labels.
*
* @return void
*/
private function load_categories() {
$categories = array(
'admin' => __( 'Admin', 'insert-headers-and-footers' ),
'content' => __( 'Content', 'insert-headers-and-footers' ),
'core' => __( 'Core', 'insert-headers-and-footers' ),
'design' => __( 'Design', 'insert-headers-and-footers' ),
'query' => __( 'Query', 'insert-headers-and-footers' ),
'schema' => __( 'Schema', 'insert-headers-and-footers' ),
);
$this->categories = array();
foreach ( $categories as $slug => $name ) {
$this->categories[] = array(
'slug' => $slug,
'name' => $name,
);
}
}
/**
* Get categories.
*
* @return array
*/
public function get_categories() {
if ( ! isset( $this->categories ) ) {
$this->load_categories();
}
return $this->categories;
}
/**
* Get all the generator instances.
*
* @return WPCode_Generator_Type[]
*/
public function get_all_generators() {
return $this->types;
}
/**
* Get a generator by its name. If not found it returns false.
*
* @param string $name The name of the generator.
*
* @return WPCode_Generator_Type|false
*/
public function get_type( $name ) {
$types = $this->get_all_generators();
return isset( $types[ $name ] ) ? $types[ $name ] : false;
}
}
@@ -0,0 +1,251 @@
<?php
/**
* Logic to run on plugin install.
*
* @package WPCode
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Class WPCode_Install.
*/
class WPCode_Install {
/**
* WPCode_Install constructor.
*/
public function __construct() {
register_activation_hook( WPCODE_FILE, array( $this, 'activate' ) );
add_action( 'admin_init', array( $this, 'maybe_run_install' ) );
}
/**
* Activation hook.
*
* @return void
*/
public function activate() {
// Add capabilities on activation as deleting the plugin removes them
// but the option used in the `maybe_run_install` method below is not
// removed so the capabilities are not added back.
WPCode_Capabilities::add_capabilities();
// Use an action to have a single activation hook plugin-wide.
do_action( 'wpcode_plugin_activation' );
set_transient( 'wpcode_just_activated', class_exists( 'WPCode_License' ) ? 'pro' : 'lite', 60 );
}
/**
* Install routine to run on plugin activation.
* Runs on admin_init so that we also handle updates.
* The ihaf_activated option was used by IHAF 1.6 and the key "lite" is for the activation date
* of that version of the plugin. In the WPCode plugin we use the "wpcode" key, so we have the update date
* and install the demo data.
*
* @return void
*/
public function maybe_run_install() {
if ( ! is_admin() ) {
return;
}
$activated = get_option( 'ihaf_activated', array() );
if ( ! is_array( $activated ) ) {
$activated = array();
}
if ( empty( $activated['wpcode'] ) ) {
$activated['wpcode'] = time();
update_option( 'ihaf_activated', $activated );
// Add custom capabilities.
WPCode_Capabilities::add_capabilities();
// The option was empty so let's add the demo data.
$this->add_demo_data();
do_action( 'wpcode_install' );
}
// Maybe run manually just one time.
$install = get_option( 'wpcode_install', false );
if ( ! empty( $install ) ) {
$this->activate();
delete_option( 'wpcode_install' );
}
// Let's run an upgrade routine.
if ( empty( $activated['version'] ) ) {
$this->update_2_1_0();
}
if ( isset( $activated['version'] ) && version_compare( $activated['version'], WPCODE_VERSION, '=' ) ) {
// If the version is identical just skip.
return;
}
if ( isset( $activated['version'] ) && version_compare( $activated['version'], '2.1.4', '<' ) ) {
$this->update_2_1_4();
}
if ( isset( $activated['version'] ) && version_compare( $activated['version'], '2.1.5', '<' ) ) {
$this->update_2_1_5();
}
// Give other plugins a chance to run an upgrade routine.
do_action( 'wpcode_before_version_update', $activated );
$activated['version'] = WPCODE_VERSION;
update_option( 'ihaf_activated', $activated );
}
/**
* Upgrade routine for 2.1.0.
* Empty the library cache to get the new snippets.
*
* @return void
*/
public function update_2_1_0() {
if ( isset( wpcode()->library ) ) {
wpcode()->library->delete_cache();
}
}
/**
* Upgrade routine for 2.1.4.
* Convert recently deactivated to the new error system.
*
* @return void
*/
public function update_2_1_4() {
// Let's find all the snippets with the _wpcode_recently_deactivated meta key set.
$snippets = get_posts(
array(
'post_type' => 'wpcode',
'posts_per_page' => - 1,
'post_status' => 'any',
'meta_query' => array( // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query
array(
'key' => '_wpcode_recently_deactivated',
'compare' => 'EXISTS',
),
),
)
);
// Let's loop through the snippets and convert them to the new error system.
foreach ( $snippets as $snippet ) {
$snippet = new WPCode_Snippet( $snippet->ID );
$error = array(
'message' => esc_html__( 'Snippet was deactivated due to an error.', 'insert-headers-and-footers' ),
'time' => get_post_meta( $snippet->get_id(), '_wpcode_recently_deactivated', true ),
'wpc_type' => 'deactivated',
);
$error_line = get_post_meta( $snippet->get_id(), '_wpcode_recently_deactivated_error_line', true );
if ( ! empty( $error_line ) ) {
$error['error_line'] = $error_line;
}
$snippet->set_last_error( $error );
// Remove the old meta keys.
delete_post_meta( $snippet->get_id(), '_wpcode_recently_deactivated' );
delete_post_meta( $snippet->get_id(), '_wpcode_recently_deactivated_error_line' );
wpcode()->error->clear_snippets_errors();
}
$this->add_columns_to_hidden( array( 'id', 'code_type', 'shortcode' ) );
}
/**
* Upgrade routine for 2.1.5.
* Add the priority column to the hidden columns.
*
* @return void
*/
public function update_2_1_5() {
$this->add_columns_to_hidden( array( 'priority' ) );
}
/**
* Add columns to the hidden columns for users that set their screen settings.
*
* @param array $new_columns The columns to add.
*
* @return void
*/
public function add_columns_to_hidden( $new_columns ) {
// Let's add the new columns to the hidden array for users that set their screen settings.
$meta_key = 'managetoplevel_page_wpcodecolumnshidden';
$users = get_users(
array(
'meta_key' => $meta_key, // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key
'meta_compare' => 'EXISTS',
'fields' => 'ID',
)
);
foreach ( $users as $user_id ) {
$columns = get_user_meta( $user_id, $meta_key, true );
if ( ! is_array( $columns ) ) {
$columns = array();
}
$columns = array_merge( $columns, $new_columns );
update_user_meta( $user_id, $meta_key, $columns );
}
}
/**
* Add some example snippets in a new installation.
*
* @return void
*/
public function add_demo_data() {
$snippets = array(
array(
'title' => __( 'Display a message after the 1st paragraph of posts', 'insert-headers-and-footers' ),
'code' => 'Thank you for reading this post, don\'t forget to subscribe!',
'code_type' => 'text',
'auto_insert' => 1,
'location' => 'after_paragraph',
'insert_number' => 1,
'tags' => array(
'sample',
'message',
),
),
array(
'title' => __( 'Completely Disable Comments', 'insert-headers-and-footers' ),
'code' => "add_action('admin_init', function () {\r\n \/\/ Redirect any user trying to access comments page\r\n global \$pagenow;\r\n \r\n if (\$pagenow === 'edit-comments.php') {\r\n wp_safe_redirect(admin_url());\r\n exit;\r\n }\r\n\r\n \/\/ Remove comments metabox from dashboard\r\n remove_meta_box('dashboard_recent_comments', 'dashboard', 'normal');\r\n\r\n \/\/ Disable support for comments and trackbacks in post types\r\n foreach (get_post_types() as \$post_type) {\r\n if (post_type_supports(\$post_type, 'comments')) {\r\n remove_post_type_support(\$post_type, 'comments');\r\n remove_post_type_support(\$post_type, 'trackbacks');\r\n }\r\n }\r\n});\r\n\r\n\/\/ Close comments on the front-end\r\nadd_filter('comments_open', '__return_false', 20, 2);\r\nadd_filter('pings_open', '__return_false', 20, 2);\r\n\r\n\/\/ Hide existing comments\r\nadd_filter('comments_array', '__return_empty_array', 10, 2);\r\n\r\n\/\/ Remove comments page in menu\r\nadd_action('admin_menu', function () {\r\n remove_menu_page('edit-comments.php');\r\n});\r\n\r\n\/\/ Remove comments links from admin bar\r\nadd_action('init', function () {\r\n if (is_admin_bar_showing()) {\r\n remove_action('admin_bar_menu', 'wp_admin_bar_comments_menu', 60);\r\n }\r\n});",
'code_type' => 'php',
'auto_insert' => 1,
'location' => 'everywhere',
'tags' => array(
'sample',
'disable',
'comments',
),
'library_id' => 12,
),
);
// The activation hook runs after `init` so our plugin's custom
// post type and custom taxonomies didn't have a chance to be registered.
wpcode_register_post_type();
wpcode_register_taxonomies();
foreach ( $snippets as $snippet ) {
$new_snippet = new WPCode_Snippet( $snippet );
$new_snippet->save();
}
}
}
new WPCode_Install();
@@ -0,0 +1,291 @@
<?php
/**
* Class for handling the WPCode library authentication.
*
* @package WPCode
*/
/**
* Class WPCode_Library_Auth.
*/
class WPCode_Library_Auth {
/**
* The base api URL.
*
* @var string
*/
public $library_url = 'https://library.wpcode.com';
/**
* Is the current plugin authenticated with the WPCode Library?
*
* @var bool
*/
private $has_auth;
/**
* The api key used for authenticated requests to the library.
*
* @var string
*/
private $auth_key;
/**
* The auth data from the db.
*
* @var array
*/
private $auth_data;
/**
* Library auth constructor.
*/
public function __construct() {
add_action( 'wp_ajax_wpcode_library_store_auth', array( $this, 'store_auth_key' ) );
add_action( 'wp_ajax_wpcode_library_delete_auth', array( $this, 'delete_auth' ) );
}
/**
* Ajax handler that returns the auth url used to start the Connect process.
*
* @return string
*/
public function auth_url() {
if ( $this->has_auth() ) {
return '';
}
$site_name = get_bloginfo( 'name' );
if ( empty( $site_name ) ) {
$site_name = __( 'Your WordPress Site', 'insert-headers-and-footers' );
}
// This is needed, so we don't run into issues with special characters.
// Base64 encode without padding for better compatibility between PHP versions.
$site_name = rtrim( strtr( base64_encode( $site_name ), '+/', '-_' ), '=' );
$ajax_url = rtrim( strtr( base64_encode( admin_url( 'admin-ajax.php' ) ), '+/', '-_' ), '=' );
$auth_url = add_query_arg(
array(
'site' => $site_name,
'version' => WPCODE_VERSION,
'ajax' => $ajax_url,
),
$this->get_api_url( 'connect' )
);
return $auth_url;
}
/**
* Get the full URL to an API endpoint by passing the path.
*
* @param string $path The path for the API endpoint.
*
* @return string
*/
public function get_api_url( $path ) {
return trailingslashit( $this->library_url ) . 'api/' . $path;
}
/**
* Ajax handler to save the auth API key.
*
* @return void
*/
public function store_auth_key() {
check_ajax_referer( 'wpcode_admin' );
if ( ! current_user_can( 'wpcode_activate_snippets' ) ) {
wp_send_json_error( esc_html__( 'You do not have permissions to connect WPCode to the library.', 'insert-headers-and-footers' ) );
}
$key = ! empty( $_POST['key'] ) ? sanitize_key( $_POST['key'] ) : false;
$username = ! empty( $_POST['username'] ) ? sanitize_user( wp_unslash( $_POST['username'] ) ) : false;
$origin = ! empty( $_POST['origin'] ) ? esc_url_raw( wp_unslash( $_POST['origin'] ) ) : false;
$deploy_snippet_id = ! empty( $_POST['deploy_snippet_id'] ) ? sanitize_key( $_POST['deploy_snippet_id'] ) : false;
$webhook_secret = ! empty( $_POST['webhook_secret'] ) ? sanitize_key( $_POST['webhook_secret'] ) : '';
$client_id = ! empty( $_POST['client_id'] ) ? sanitize_key( $_POST['client_id'] ) : false;
if ( ! $key || $this->library_url !== $origin ) {
wp_send_json_error();
}
$this->save_auth_data( $key, $username, $webhook_secret, $client_id );
if ( ! empty( $deploy_snippet_id ) ) {
// If we have a snippet id from the deployment process, set that as a transient to show a notice, so they can pick up where they started.
set_transient( 'wpcode_deploy_snippet_id', $deploy_snippet_id, HOUR_IN_SECONDS );
}
// Reset the auth data.
unset( $this->auth_data );
unset( $this->auth_key );
unset( $this->has_auth );
do_action( 'wpcode_library_api_auth_connected' );
wp_send_json_success(
array(
'title' => __( 'Authentication successfully completed', 'insert-headers-and-footers' ),
'text' => __( 'Reloading page, please wait.', 'insert-headers-and-footers' ),
)
);
}
/**
* Save the auth data to the db.
*
* @param string $key The auth key.
* @param string $username The username.
* @param string $webhook_secret The webhook secret.
* @param string $client_id The client id.
*
* @return void
*/
public function save_auth_data( $key, $username, $webhook_secret, $client_id ) {
// Don't autoload this as we'll only need it on some pages and in specific requests.
update_option(
'wpcode_library_api_auth',
array(
'key' => $key,
'username' => $username,
'webhook_secret' => $webhook_secret,
'client_id' => $client_id,
'connected_at' => time(),
),
false
);
}
/**
* Ajax handler to delete the auth data and disconnect the site from the WPCode Library.
*
* @return void
*/
public function delete_auth() {
check_ajax_referer( 'wpcode_admin' );
if ( ! current_user_can( 'wpcode_activate_snippets' ) ) {
wp_send_json_error( esc_html__( 'You do not have permissions to connect WPCode to the library.', 'insert-headers-and-footers' ) );
}
if ( $this->delete_auth_data() ) {
do_action( 'wpcode_library_api_auth_deleted' );
wp_send_json_success();
}
wp_send_json_error();
}
/**
* Delete the auth data from the db.
*
* @return bool
*/
public function delete_auth_data() {
return delete_option( 'wpcode_library_api_auth' );
}
/**
* Check if the site is authenticated.
*
* @return bool
*/
public function has_auth() {
if ( ! isset( $this->has_auth ) ) {
$auth_key = $this->get_auth_key();
$this->has_auth = ! empty( $auth_key );
}
return $this->has_auth;
}
/**
* The auth key.
*
* @return bool|string
*/
public function get_auth_key() {
if ( ! isset( $this->auth_key ) ) {
$data = $this->get_auth_data();
$this->auth_key = isset( $data['key'] ) ? $data['key'] : false;
}
return $this->auth_key;
}
/**
* The webhook secret.
*
* @return bool|string
*/
public function get_webhook_secret() {
$data = $this->get_auth_data();
return isset( $data['webhook_secret'] ) ? $data['webhook_secret'] : false;
}
/**
* The client id.
*
* @return bool|string
*/
public function get_client_id() {
$data = $this->get_auth_data();
return isset( $data['client_id'] ) ? $data['client_id'] : false;
}
/**
* Get the auth data from the db.
*
* @return array|bool
*/
public function get_auth_data() {
if ( ! isset( $this->auth_data ) ) {
$this->auth_data = $this->load_auth_data();
}
return $this->auth_data;
}
/**
* Get the auth data from the db.
*
* @return array|bool
*/
public function load_auth_data() {
return get_option( 'wpcode_library_api_auth', false );
}
/**
* The auth username.
*
* @return bool|string
*/
public function get_auth_username() {
$data = $this->get_auth_data();
return isset( $data['username'] ) ? $data['username'] : false;
}
/**
* Use the API key saved in the db to sign a value, used for authenticating requests from the library to the plugin.
*
* @param string $string The string to sign.
*
* @return string
*/
public function sign( $string ) {
$api_key = $this->get_webhook_secret();
if ( empty( $api_key ) ) {
return false;
}
return hash_hmac( 'sha256', (string) $string, $api_key );
}
}

Some files were not shown because too many files have changed in this diff Show More