diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 0000000..56d996e Binary files /dev/null and b/.DS_Store differ diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..3c3629e --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +node_modules diff --git a/README.md b/README.md new file mode 100644 index 0000000..32ecc85 --- /dev/null +++ b/README.md @@ -0,0 +1,192 @@ + +![PHPagebuilder](https://user-images.githubusercontent.com/5946444/67637466-445d4400-f8db-11e9-86ce-6e62ce7ede8a.png) + +# PHPagebuilder +> PHPagebuilder is a drag and drop pagebuilder to manage pages in any PHP project. + +PHPagebuilder can be used as an ultra lightweight CMS to quickly spin up new websites, or can be integrated into existing projects or your favorite frameworks (such as [this version](https://github.com/HansSchouten/Laravel-Pagebuilder) for Laravel). The server-side code does not depend on any other libraries and is blazing fast. It includes an optional website manager with a [Bootstrap UI](https://getbootstrap.com) and integrates the most popular open source drag and drop pagebuilder: [GrapesJS](https://grapesjs.com/). This package is made with customization in mind, allowing you to configure, disable or replace any of its modules. + +## Table of Contents +- [How does it help me?](#how-does-it-help-me) +- [Features](#features) +- [Installation](#installation) +- [Customization](#customization) + +## How does it help me? +Whether you are a novice or an experienced web developer, PHPagebuilder can make your life easier if you find yourself in any of the following: + +- You just want to create a basic website that you can easily manage from any device. +- You get lost installing, configuring, updating or simply using feature abundant CMS systems like Wordpress, Drupal. +- You don't like the limited page editors in CMSs you've tried. +- You want to build a custom website for a client within a few hours. +- Your clients get lost in feature abundant admin panels like Drupal. +- You hate to rely on messy plugins for features you can write in no-time in plain PHP yourself, but still want to have some admin functionality to allow other people to manage the websites you create. +- You would like to have advanced functionality (search functionality, views displaying data of remote sources, etc.) easily manageable by your clients. + +## Features + +### Page Builder +PHPagebuilder features a page builder built on [GrapesJS](https://grapesjs.com/). +![PageBuilder](https://user-images.githubusercontent.com/5946444/70818285-97c81a80-1dd3-11ea-84b0-2a6ff3a8765a.png) + +### Website Manager +A basic website manager is included with a [Bootstrap](https://getbootstrap.com/) UI. This website manager offers basic functionality to add or remove pages and to edit page settings like page title or URL. Clicking the edit button will open the page builder. +![Website Manager](https://user-images.githubusercontent.com/5946444/67484882-4029f000-f669-11e9-9a1f-8a0e1c53e308.jpg) + +You don't want to use the website manager? No worries, it is included for people who want to use PHPagebuilder directly out of the box. Read [here](#customize-the-website-manager) how to disable or replace the website manager. + +## Installation + +To install PHPagebuilder you either follow the quick start path, for quickly spinning up a new website, or you integrate it in your own framework or favorite project structure. + +### Requirements + +- PHP version >= 7 +- A cool project + +### Quick start :rocket: + +If you want to quickly start a new project with drag and drop page management functionality, you can download the [boilerplate](https://github.com/HansSchouten/PHPagebuilder-boilerplate) project structure and follow the steps over there. + +### Integrate into existing project or framework + +#### Add code with Composer +If you are using Composer for managing PHP dependencies, you can simply run: +``` +composer require hansschouten/phpagebuilder +``` + +Next, the PHPagebuilder can be initialised using the following PHP code: +```PHP +require_once __DIR__ . '/vendor/autoload.php'; + +$config = require __DIR__ . '/config.php'; + +$builder = new PHPageBuilder\PHPageBuilder($config); +$builder->handleRequest(); +``` + +`config.php` should contain a copy of `config/config.example.php`, filled with your settings. + +#### Add code without Composer +Are you not using Composer? No worries, this project is written in plain PHP without any dependencies, so it can be directly included in any PHP project! + +Just download the latest release into a separate folder inside your project (we named the folder: `phpagebuilder`). + +Next, you simply include the following code in the PHP file that should launch the page builder: + +```PHP +$installationFolder = __DIR__ . '/phpagebuilder'; +require_once $installationFolder . '/src/Core/helpers.php'; +spl_autoload_register('phpb_autoload'); + +$config = require __DIR__ . '/config.php'; + +$builder = new PHPageBuilder\PHPageBuilder($config); +$builder->handleRequest(); +``` + +`config.php` should contain a copy of `config/config.example.php`, filled with your settings. + +### Configure a database +If you use PHPagebuilder out of the box, it requires a database for storing your pages. Just create a database and run the queries from `config/create-tables.sql`. Next, add the database credentials to your config file. + +## Create a theme +The `config.php` contains a config key `theme` in which a `themes_folder` and `active_theme` are specified. To create a new theme, add a new folder to the configured themes folder. The name of this folder will be the identifier of the theme, which can be used to select the theme in the `theme > active_theme` configuration. + +A theme should have the following folder structure: + +- **/blocks** +The blocks folder contains a sub folder for each block that can be used in the page builder. The folder of a single block contains a `view.php` or a `view.html`. If a `view.html` is used, the block content (the html elements) are fully editable inside the page builder. If `view.php` is used, the block can be rendered with server-side logic (PHP) and hence the html content itself cannot be changed from within the page builder. +- **/layouts** +The layouts folder contains a sub folder for each page layout. A page layout contains a `view.php` file which defines the base html structure with all stylesheets and scripts needed for the blocks dragged on this type of page. Each layout requires the string: `` on the location at which the html blocks need to be added in the page layout. +- **/public** +The public folder contains all assets (css, javascript, images, etc) that should be publicly accessible. The `[theme-url]` shortcode can be used to point to a file in the public folder of the currently active theme. For instance the file `public/css/style.css` can be loaded via ``. + +### Blocks inside blocks +#### Include a block into a block or layout file +A shortcode can be used to include a block inside another block or into a layout file. For instance, adding the shortcode: `[block slug="header"]` to `layouts/master/view.php` includes the block: `blocks/header/view.php` inside each page that uses the `master` layout. + +#### Nested blocks in the page builder +To allow dropping blocks into a block in the page builder, a blocks container should be added. To add a blocks container, simply add `[blocks-container]` at the desired location in a block view file. The following html syntax allows dropping blocks inside a bootstrap container element: +```html +
+ [blocks-container] +
+``` +An alternative method is adding the `phpb-blocks-container` attribute to a html element, as shown in this example: +```html +
+
+
+
+
+
+``` + +## Extending PHPageBuilder + +PHPageBuilder allows you to create new blocks and layouts for your theme very easily. This is great for building specific websites & templates, however if you use PHPageBuilder in a CMS environment, you probably want to provide Plugins / Modules the ability to create their own blocks without modifying your theme's pre-existing components. + +PHPageBuilder allows you to register blocks, layouts and assets (CSS, JS) from Plugins, Composer Packages or through any other environment. + +### Adding a New Block + +```php +/** + * @param string $slug - A Unique identifier for the block. Prefix author to avoid conflict. + * @param string $directoryPath - Path to the directory of the Block. + */ +\PHPageBuilder\Extensions::registerBlock($slug, $directoryPath); + +// Registering an example block: + +\PHPageBuilder\Extensions::registerBlock('foo-navbar', MY_PLUGIN_DIRECTORY . '/blocks/foo-navbar'); +``` + +### Adding a New Layout + +```php +/** + * @param string $slug - A Unique identifier for the layout. Prefix author to avoid conflict. + * @param string $directoryPath - Path to the directory of the Layout. + */ +\PHPageBuilder\Extensions::registerLayout($slug, $directoryPath); + +// Registering an example layout: + +\PHPageBuilder\Extensions::registerLayout('foo-master', MY_PLUGIN_DIRECTORY . '/layouts/foo-master'); +``` + +### Adding Assets (CSS & JS) +```php +/** + * @param string $src - URL of the Asset file. + * @param string $type - 'style' or 'script' + * @param string $location - 'header' or 'footer' + * @param array['$key' => '$value'] $attributes - Array of attributes to add to the tag. + */ +\PHPageBuilder\Extensions::registerAsset($src, $type, $location, $attributes = []); + +// Registering assets: + +\PHPageBuilder\Extensions::registerAsset('/assets/bootstrap.css', 'style', 'header'); +\PHPageBuilder\Extensions::registerAsset('/assets/alpine.min.js', 'script', 'header', [ + 'defer' => true +]); +``` + +Blocks & Layouts are created in the same manner as described in [Create A Theme](#create-a-theme), but they aren't limited to any theme directory. + +## Customize PHPageBuilder + +PHPagebuilder is build with customization in mind. It comes with an extensive example config file in wich you can easily adapt the pagebuilder to your needs. + +PHPagebuilder consists of four modules (Auth, Website Manager, Pagebuilder, Routing) each of which you can disable or replace with your own implementation. To replace a module with your own implementation, implement the corresponding Contract and replace the default class by your own class in the config file. + +### Customize the Website Manager +#### Disable the module +Do you already have admin login functionality in your project? Then you can disable the website manager module by setting `use_website_manager` to `false` in your config. Next, you use or implement the page create/edit/remove functionality in your project and then directly launch the pagebuilder. You can render the pagebuilder from your project by using the `PHPageBuilder\Modules\GrapesJS\PageBuilder` class. + +#### Replace the module +If you want to use the CMS routing functionality of PHPagebuilder, but you want to have a different website manager, you can replace the website manager for your own implementation. Make sure leave `use_website_manager` to `true` in your config, implement the WebsiteManagerContract and add your own class to your config file. diff --git a/build.js b/build.js new file mode 100644 index 0000000..0b56c0a --- /dev/null +++ b/build.js @@ -0,0 +1,34 @@ +import { build } from 'vite'; + +// libraries +const libraries = [ + { + entry: './src/Modules/WebsiteManager/resources/assets/entry.js', + name: 'WebsiteManager', + fileName: 'WebsiteManager', + }, + { + entry: './src/Modules/GrapesJS/resources/assets/entry.js', + name: 'GrapesJS', + fileName: 'GrapesJS', + }, +]; + +// build +libraries.forEach(async (libItem) => { + await build({ + configFile: false, + build: { + lib: libItem, + emptyOutDir: false, + rollupOptions: { + output: { + assetFileNames: (assetInfo) => { + if (assetInfo.name === 'style.css') return `${libItem.fileName}.css`; + return assetInfo.name; + }, + }, + }, + }, + }); +}); diff --git a/composer.json b/composer.json new file mode 100644 index 0000000..74b7c14 --- /dev/null +++ b/composer.json @@ -0,0 +1,27 @@ +{ + "name": "hansschouten/phpagebuilder", + "description": "A drag and drop pagebuilder to manage pages in any PHP project.", + "keywords": [ + "pagebuilder" + ], + "homepage": "https://github.com/HansSchouten/PHPagebuilder", + "type": "library", + "license": "MIT", + "authors": [ + { + "name": "Hans Schouten", + "email": "hans@falcosolutions.nl" + } + ], + "require": { + "php": ">=7.0" + }, + "autoload": { + "psr-4": { + "PHPageBuilder\\": "src/" + }, + "files": [ + "src/Core/helpers.php" + ] + } +} diff --git a/config/.DS_Store b/config/.DS_Store new file mode 100644 index 0000000..316544d Binary files /dev/null and b/config/.DS_Store differ diff --git a/config/config.example.php b/config/config.example.php new file mode 100644 index 0000000..f77ca96 --- /dev/null +++ b/config/config.example.php @@ -0,0 +1,180 @@ + '/vendor/hansschouten/phpagebuilder/dist', + | + */ + 'general' => [ + 'base_url' => 'http://localhost', + 'language' => 'en', + 'assets_url' => '/assets', + 'uploads_url' => '/uploads' + ], + + /* + |-------------------------------------------------------------------------- + | Storage settings + |-------------------------------------------------------------------------- + | + | Database and file storage settings. + | + */ + 'storage' => [ + 'use_database' => true, + 'database' => [ + 'driver' => 'mysql', + 'host' => 'localhost', + 'database' => '', + 'username' => '', + 'password' => '', + 'charset' => 'utf8', + 'collation' => 'utf8_unicode_ci', + 'prefix' => '', + ], + 'uploads_folder' => __DIR__ . '/uploads' + ], + + /* + |-------------------------------------------------------------------------- + | Auth settings + |-------------------------------------------------------------------------- + | + | By default an authentication class is provided which checks for the + | credentials configured in this setting block. + | + */ + 'auth' => [ + 'use_login' => true, + 'class' => PHPageBuilder\Modules\Auth\Auth::class, + 'url' => '/admin/auth', + 'username' => 'admin', + 'password' => 'changethispassword' + ], + + /* + |-------------------------------------------------------------------------- + | WebsiteManager settings + |-------------------------------------------------------------------------- + | + | By default a basic WebsiteManager is provided for creating/editing pages. + | + */ + 'website_manager' => [ + 'use_website_manager' => true, + 'class' => PHPageBuilder\Modules\WebsiteManager\WebsiteManager::class, + 'url' => '/admin' + ], + + /* + |-------------------------------------------------------------------------- + | Website settings + |-------------------------------------------------------------------------- + | + | By default a setting class is provided for accessing website settings. + | + */ + 'setting' => [ + 'class' => PHPageBuilder\Setting::class + ], + + /* + |-------------------------------------------------------------------------- + | PageBuilder settings + |-------------------------------------------------------------------------- + | + | By default a PageBuilder is provided based on GrapesJS. + | + */ + 'pagebuilder' => [ + 'class' => PHPageBuilder\Modules\GrapesJS\PageBuilder::class, + 'url' => '/admin/pagebuilder', + 'actions' => [ + 'back' => '/admin' + ] + ], + + /* + |-------------------------------------------------------------------------- + | Page settings + |-------------------------------------------------------------------------- + | + | By default a Page class is provided with knowledge about its layout and URL. + | + */ + 'page' => [ + 'class' => PHPageBuilder\Page::class, + 'table' => 'pages', + 'translation' => [ + 'class' => PHPageBuilder\PageTranslation::class, + 'table' => 'page_translations', + 'foreign_key' => 'page_id', + ] + ], + + /* + |-------------------------------------------------------------------------- + | Cache settings + |-------------------------------------------------------------------------- + | + | Faster load time by skipping block parsing if the page has been requested before. + | A page will be cached, except if it contains a block with caching set to false. + | This can be used to prevent caching pages with content that varies per page load. + | The cached html is removed if the page is saved again in the page builder. + | + */ + 'cache' => [ + 'enabled' => false, + 'folder' => __DIR__ . '/cache', + 'class' => PHPageBuilder\Cache::class + ], + + /* + |-------------------------------------------------------------------------- + | Theme settings + |-------------------------------------------------------------------------- + | + | PageBuilder requires a themes folder in which for each theme the individual + | theme blocks are defined. A theme block is a sub folder in the themes folder + | containing a view, model (optional) and controller (optional). + | + */ + 'theme' => [ + 'class' => PHPageBuilder\Theme::class, + 'folder' => __DIR__ . '/themes', + 'folder_url' => '/themes', + 'active_theme' => 'demo' + ], + + /* + |-------------------------------------------------------------------------- + | Routing settings + |-------------------------------------------------------------------------- + | + | Settings for resolving pages based on the current URI. + | + */ + 'router' => [ + 'class' => PHPageBuilder\Modules\Router\DatabasePageRouter::class + ], + + /* + |-------------------------------------------------------------------------- + | Class replacements + |-------------------------------------------------------------------------- + | + | Allows mapping a class namespace to an alternative namespace, + | useful for replacing implementations of specific pagebuilder classes. + | Example: PHPageBuilder\UploadedFile::class => Alternative\UploadedFile::class + | Important: when overriding a class always extend the original class. + | + */ + 'class_replacements' => [ + ], +]; diff --git a/config/create-tables.sql b/config/create-tables.sql new file mode 100644 index 0000000..eb92ac6 --- /dev/null +++ b/config/create-tables.sql @@ -0,0 +1,208 @@ +-- phpMyAdmin SQL Dump +-- version 5.2.1 +-- https://www.phpmyadmin.net/ +-- +-- Host: mysql +-- Erstellungszeit: 05. Jun 2023 um 09:11 +-- Server-Version: 8.0.31 +-- PHP-Version: 8.2.6 + +SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; +START TRANSACTION; +SET time_zone = "+00:00"; + + +/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; +/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; +/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; +/*!40101 SET NAMES utf8mb4 */; + +-- +-- Datenbank: `phpagebuilder` +-- + +-- -------------------------------------------------------- + +-- +-- Tabellenstruktur für Tabelle `menus` +-- + +CREATE TABLE `menus` ( + `id` int NOT NULL, + `name` varchar(50) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL, + `pages` mediumtext CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3; + +-- +-- Daten für Tabelle `menus` +-- + +INSERT INTO `menus` (`id`, `name`, `pages`) VALUES +(1, 'Main', '1,3'), +(2, 'Footer', '1'); + +-- -------------------------------------------------------- + +-- +-- Tabellenstruktur für Tabelle `pages` +-- + +CREATE TABLE `pages` ( + `id` int NOT NULL, + `name` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci NOT NULL, + `layout` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci NOT NULL, + `data` longtext CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci, + `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3; + +-- +-- Daten für Tabelle `pages` +-- + +INSERT INTO `pages` (`id`, `name`, `layout`, `data`, `updated_at`, `created_at`) VALUES +(1, 'Home', 'master', NULL, '2023-06-05 07:10:09', '2023-06-05 07:10:09'), +(2, 'Sitemap', 'sitemap', NULL, '2023-06-05 07:11:15', '2023-06-05 07:10:41'), +(3, 'About', 'master', NULL, '2023-06-05 07:10:57', '2023-06-05 07:10:57'); + +-- -------------------------------------------------------- + +-- +-- Tabellenstruktur für Tabelle `page_translations` +-- + +CREATE TABLE `page_translations` ( + `id` int NOT NULL, + `page_id` int NOT NULL, + `locale` varchar(50) NOT NULL, + `title` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci NOT NULL, + `meta_title` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci NOT NULL, + `meta_description` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci NOT NULL, + `route` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci NOT NULL, + `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3; + +-- +-- Daten für Tabelle `page_translations` +-- + +INSERT INTO `page_translations` (`id`, `page_id`, `locale`, `title`, `meta_title`, `meta_description`, `route`, `updated_at`, `created_at`) VALUES +(1, 1, 'de', 'Home', 'Home', 'Home', '/', '2023-06-05 07:10:09', '2023-06-05 07:10:09'), +(2, 2, 'de', 'Sitemap', '', '', '/sitemap.xml', '2023-06-05 07:10:41', '2023-06-05 07:10:41'), +(3, 3, 'de', 'About', 'About', 'Description', '/about', '2023-06-05 07:10:57', '2023-06-05 07:10:57'); + +-- -------------------------------------------------------- + +-- +-- Tabellenstruktur für Tabelle `settings` +-- + +CREATE TABLE `settings` ( + `id` int NOT NULL, + `setting` varchar(50) NOT NULL, + `value` mediumtext NOT NULL, + `is_array` tinyint(1) NOT NULL +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3; + +-- -------------------------------------------------------- + +-- +-- Tabellenstruktur für Tabelle `uploads` +-- + +CREATE TABLE `uploads` ( + `id` int NOT NULL, + `public_id` varchar(50) NOT NULL, + `original_file` varchar(512) NOT NULL, + `mime_type` varchar(50) NOT NULL, + `server_file` varchar(512) NOT NULL +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3; + +-- +-- Indizes der exportierten Tabellen +-- + +-- +-- Indizes für die Tabelle `menus` +-- +ALTER TABLE `menus` + ADD PRIMARY KEY (`id`), + ADD UNIQUE KEY `menu` (`name`); + +-- +-- Indizes für die Tabelle `pages` +-- +ALTER TABLE `pages` + ADD PRIMARY KEY (`id`); + +-- +-- Indizes für die Tabelle `page_translations` +-- +ALTER TABLE `page_translations` + ADD PRIMARY KEY (`id`), + ADD UNIQUE KEY `page_id` (`page_id`,`locale`); + +-- +-- Indizes für die Tabelle `settings` +-- +ALTER TABLE `settings` + ADD PRIMARY KEY (`id`), + ADD UNIQUE KEY `setting` (`setting`); + +-- +-- Indizes für die Tabelle `uploads` +-- +ALTER TABLE `uploads` + ADD PRIMARY KEY (`id`), + ADD UNIQUE KEY `public_id` (`public_id`), + ADD UNIQUE KEY `server_file` (`server_file`); + +-- +-- AUTO_INCREMENT für exportierte Tabellen +-- + +-- +-- AUTO_INCREMENT für Tabelle `menus` +-- +ALTER TABLE `menus` + MODIFY `id` int NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5; + +-- +-- AUTO_INCREMENT für Tabelle `pages` +-- +ALTER TABLE `pages` + MODIFY `id` int NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4; + +-- +-- AUTO_INCREMENT für Tabelle `page_translations` +-- +ALTER TABLE `page_translations` + MODIFY `id` int NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4; + +-- +-- AUTO_INCREMENT für Tabelle `settings` +-- +ALTER TABLE `settings` + MODIFY `id` int NOT NULL AUTO_INCREMENT; + +-- +-- AUTO_INCREMENT für Tabelle `uploads` +-- +ALTER TABLE `uploads` + MODIFY `id` int NOT NULL AUTO_INCREMENT; + +-- +-- Constraints der exportierten Tabellen +-- + +-- +-- Constraints der Tabelle `page_translations` +-- +ALTER TABLE `page_translations` + ADD CONSTRAINT `page_translations_ibfk_1` FOREIGN KEY (`page_id`) REFERENCES `pages` (`id`) ON DELETE CASCADE ON UPDATE CASCADE; +COMMIT; + +/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; +/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; +/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; diff --git a/dist/GrapesJS.css b/dist/GrapesJS.css new file mode 100644 index 0000000..00edc56 --- /dev/null +++ b/dist/GrapesJS.css @@ -0,0 +1 @@ +html,body,#gjs{height:100%!important;margin:0;overflow:hidden}*{box-shadow:none!important}.form-control,.form-control:focus{color:#e1e1e1}.cursor-pointer{cursor:pointer}.gjs-editor{font-size:.9rem}.toast{opacity:1!important;border:none;right:15px;box-shadow:none}.toast.toast-success{background:#2dc837}#phpb-loading{position:absolute;height:100%;width:100%;background-color:#fff;z-index:10000;transition:opacity .3s,visibility .3s}#phpb-loading.loaded{visibility:hidden;opacity:0}#phpb-loading .circle{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);width:150px;height:150px}#phpb-loading .circle .text{font-size:20px;margin:20px -30px 0;text-align:center;color:#0091d1}#phpb-loading .loader{width:calc(100% + -0px);height:calc(100% + -0px);border:8px solid #0091d1;border-top:8px solid #004a6c;border-radius:50%;animation:rotate 5s linear infinite}@keyframes rotate{to{transform:rotate(360deg)}}.btn.focus,.btn:focus{box-shadow:none}.gjs-cv-canvas{height:100%;top:0;width:calc(100% - 325px)}.gjs-toolbar{z-index:100!important}.gjs-pn-panel{padding:0}.gjs-pn-panel .gjs-pn-buttons{justify-content:center}.gjs-pn-commands,.gjs-pn-options,.gjs-pn-devices-c{display:none}.gjs-devices-c{padding:0}.gjs-one-bg{background-color:#313844;border-bottom:none;color:#c4c7ce}.gjs-two-color,.gjs-four-color,.gjs-four-color-h:hover{color:#e1e1e1}.gjs-pn-commands{width:100%;box-shadow:none}::-webkit-scrollbar{width:7px;height:7px}::-webkit-scrollbar-track{background:#313844!important}::-webkit-scrollbar-thumb{background-color:#a5acb9!important;border-radius:3px}::-webkit-scrollbar-thumb:hover{background-color:#0091d1!important}.gjs-pn-views{top:40px}.gjs-pn-views .gjs-pn-btn{width:33.33%;margin-right:0;padding:16px 15px;border-radius:0;background:#3a3f4a;color:#e3e3e3;border-bottom:1px solid #3a3f4a;font-size:16px}.gjs-pn-views .gjs-pn-btn.gjs-pn-active{padding:15px;background-color:#515664;border-bottom-left-radius:unset;border-bottom-right-radius:unset;box-shadow:none;color:#fff;border-bottom:3px solid #0091d1}.gjs-pn-options{right:0}.gjs-pn-views,.gjs-pn-views-container{left:0;box-shadow:none;width:325px;padding-bottom:0;margin-bottom:0;margin-left:0;margin-right:0;padding-left:0;padding-right:0}.gjs-pn-views-container{padding-top:89px;background:#22272e;height:calc(100% - 40px);overflow:hidden}.gjs-pn-views-container>div:first-of-type{margin-top:44px}.gjs-pn-views-container>div{height:100%;overflow-y:auto}.gjs-pn-views-container>div>div{background:#22272e;border:none}.gjs-cv-canvas,.gjs-pn-devices-c{left:325px}.gjs-pn-panel #gjs-sm-caret{padding-right:0!important}.gjs-pn-panel .fa-caret-down{margin-right:5px!important}.gjs-pn-panel .fa-caret-right{margin-right:8px!important}.gjs-three-bg{background-color:#0091d1}.gjs-clm-tags #gjs-clm-close,.gjs-clm-tags #gjs-clm-checkbox{color:#fff}.gjs-field{background-color:#22272e;border-radius:0;padding:2px}.gjs-field input,.gjs-field select,.gjs-field textarea{padding:5px}.gjs-field .gjs-d-s-arrow{border-top:4px solid rgb(100,100,100)}#sidebar-header{position:absolute;box-shadow:none;width:325px;padding-bottom:0;margin-bottom:0;margin-left:0;margin-right:0;padding-left:0;padding-right:0;background:#22272e;height:40px;z-index:100}#sidebar-header #language-selector{float:right}#sidebar-header #language-selector .dropdown-item.active,#sidebar-header #language-selector .dropdown-item:active{background:#22272e!important}#sidebar-header #language-selector .dropdown-menu.show{padding:0}#sidebar-header #language-selector .dropdown-toggle{margin-top:2px;color:#fff!important;background:none!important;border:none;box-shadow:none;outline:none!important}#sidebar-header #language-selector .flag-icon{background-size:contain;background-position:50%;background-repeat:no-repeat;position:relative;display:inline-block;width:1.33333333em;height:12px;line-height:1em}#toggle-sidebar{position:absolute;left:0;top:0;z-index:100;color:#c4c7ce;background:#22272e;border-radius:0;transition-duration:unset}#block-search{position:fixed;background:#22272e;border-color:#3a3f4a;border-radius:0;width:325px;margin-top:-44px}#block-search i.fa-search{position:absolute;top:14px;left:9px;font-size:15px;color:#515664}#block-search input{background:#181b1e;padding:22px 20px 22px 30px;border-radius:0;border:none}#block-search input::-moz-placeholder{color:#515664}#block-search input::placeholder{color:#515664}.gjs-block{border:none;box-shadow:none;padding-bottom:8px;margin:5px;width:calc(50% - 10px)}.gjs-block.fa{padding:8px}.gjs-block:hover{color:#0091d1!important}.gjs-block .block-thumb{height:70px;overflow:hidden;margin-bottom:5px;opacity:.8}.gjs-block .block-thumb img{width:100%}.gjs-blocks-c{background:#22272e;padding:4px}.gjs-block-categories{background:#22272e;padding-bottom:45px}.gjs-block-label{font-size:.8rem;height:100%;display:grid}.gjs-block-label b{display:contents;font-weight:800}.gjs-block-category{background:#5a6371}.gjs-block-category.gjs-open{border-bottom:none!important;margin-bottom:10px}.gjs-blocks-cs{border-bottom:none!important}.gjs-layer .gjs-layer-title{background:#5a6371!important}.gjs-layer.gjs-selected .gjs-layer-title{background-color:#0091d1!important}.gjs-layer.gjs-hovered .gjs-layer-title{background-color:#0091d170!important}.gjs-category-title,.gjs-sm-sector .gjs-sm-title,.gjs-clm-tags .gjs-sm-title,.gjs-block-category .gjs-title,.gjs-layer-title{background:#424853!important;border-bottom:2px solid #363d48!important;letter-spacing:0;font-size:16px;font-weight:400}.gjs-sm-sector.gjs-sm-open .gjs-sm-title,.gjs-clm-tags.gjs-open .gjs-sm-title,.gjs-block-category.gjs-open .gjs-title{background:#545d6c!important}.gjs-layer-name{padding-top:2px;padding-bottom:13px}.gjs-layer-count{display:none}.gjs-layer-vis{padding-top:11px}.gjs-sm-sector.gjs-sm-open{border-bottom:1px solid rgba(0,0,0,.1)}.gjs-trt-trait{display:block}.gjs-trt-header{font-weight:400}.gjs-trt-trait .gjs-label,.gjs-trt-trait .gjs-field{width:100%}.gjs-field-checkbox{height:17px!important;width:17px!important}.gjs-traits-label{font-weight:400;font-size:16px;border-bottom:none}.gjs-sm-sector #gjs-sm-caret,.gjs-clm-tags #gjs-sm-caret{font-size:initial}.gjs-trt-traits .gjs-label-wrp{width:100%}.gjs-trt-traits p.no-settings{padding-top:10px;padding-bottom:10px}.gjs-trt-trait__wrp:first-of-type{padding-top:8px}.gjs-trt-trait__wrp:last-of-type{padding-bottom:8px}.gjs-trt-trait{padding-bottom:10px}.gjs-trt-trait .gjs-field-image{background:none;padding:0}.gjs-trt-trait .gjs-field-image .image__preview-container{text-align:center}.gjs-trt-trait .gjs-field-image .image__preview-container .image__remove-button{position:absolute;right:0;top:0;border-radius:0;background-color:#e9eef2;border-color:#e9eef2;color:#515664;padding:2px 6px}.gjs-trt-trait .gjs-field-image .image__preview-container img{max-width:100%;max-height:150px}#sidebar-bottom-buttons{position:absolute;left:0;bottom:0;height:40px;width:325px;margin:0;padding:0;box-shadow:none;background:#474c57;border-top:none}#sidebar-bottom-buttons button,#sidebar-bottom-buttons a{float:right;height:100%;width:33.33%;border-left:1px solid #343944;border-radius:0;color:#e3e3e3;font-size:15px;padding:8px 0}#sidebar-bottom-buttons button:hover,#sidebar-bottom-buttons a:hover{background:#017eb5;color:#fff}#sidebar-bottom-buttons button:last-child,#sidebar-bottom-buttons a:last-child{border-left:none}#sidebar-bottom-buttons button.waiting{background:#0091d1;color:#fff!important}#sidebar-bottom-buttons button.waiting i.fa{display:none}#sidebar-bottom-buttons #go-back:hover{background:#b03541}#sidebar-bottom-buttons #save-page:hover{background:#419147}.gjs-field{background-color:#22272e}.gjs-field select option{background-color:#fff;color:#000}.gjs-input-unit,.gjs-field-arrows,.gjs-sm-field select.gjs-input-unit{color:#e1e1e1}.gjs-sm-field select.gjs-input-unit option{background-color:#22272e;color:#fff}.gjs-field-arrow-d{border-top:4px solid #e1e1e1}.gjs-field-arrow-u{border-bottom:4px solid #e1e1e1}.gjs-field-radio{padding:0!important}.gjs-radio-item .gjs-radio-item-label{padding-top:10px;margin-bottom:0;padding-bottom:10px;width:100%}.gjs-radio-item input:checked+.gjs-radio-item-label{background-color:#545d6c}.gjs-sm-header,.gjs-trt-header{font-weight:400;color:#8c909d}.gjs-clm-tags{width:100%;padding-top:0;padding-bottom:0}.gjs-clm-tags #gjs-clm-status-c,.gjs-clm-tags #gjs-clm-sel-help{display:none}.gjs-clm-tags #gjs-clm-new{color:#e1e1e1}.gjs-clm-tags #gjs-clm-add-tag{background-color:#0091d1;border:none;box-shadow:1px 1px #fff3 inset;color:#fff}.gjs-clm-tags #gjs-clm-add-tag:hover{background-color:#004a6c}.gjs-sm-sectors .gjs-four-color,.gjs-sm-sectors .gjs-color-warn{color:#e1e1e1}.gjs-sm-sectors .gjs-sm-field.gjs-sm-composite{background-color:#c3e2ec24;border:1px solid rgba(121,147,155,.14)}.gjs-sm-sectors .gjs-sm-layers{background-color:#3a3f4a}.gjs-sm-sectors .gjs-sm-layers .gjs-sm-btn{background:#fff;color:#000;text-shadow:none}.gjs-sm-sectors .gjs-sm-layers .gjs-field{padding:0;background-color:#3a3f4a}.gjs-sm-sectors .gjs-sm-layers .gjs-field select{color:#fff;background:#424853}.gjs-sm-sectors .gjs-sm-stack #gjs-sm-add{color:#fff}.gjs-sm-sectors .gjs-sm-stack #gjs-sm-add:hover{color:#aaa}.gjs-am-assets-header{display:none}.gjs-am-assets-cont{background:none;padding-top:0}.gjs-am-assets{height:325px}.gjs-am-asset{-webkit-touch-callout:none;-webkit-user-select:none;-moz-user-select:none;user-select:none}.gjs-btn-prim{display:inline-block;margin-top:10px;padding:.375rem .75rem;font-weight:400;text-align:center;vertical-align:middle;-webkit-user-select:none;-moz-user-select:none;user-select:none;font-size:1rem;line-height:1.5;border-radius:.25rem;transition:color .15s ease-in-out,background-color .15s ease-in-out,border-color .15s ease-in-out,box-shadow .15s ease-in-out;color:#fff;border:1px solid #0091d1;background-color:#0091d1}.gjs-am-add-asset button{float:left;width:auto}.gjs-am-add-asset .gjs-am-add-field{width:100%}.gjs-am-file-uploader>form{background-color:#c3e2ec24;border:2px dashed rgb(189,194,200)}.gjs-am-file-uploader #gjs-am-title{color:#7e8793;text-shadow:none}.cke_dialog_body .cke_dialog_ui_vbox_child{padding:0}.cke_dialog_body input.cke_dialog_ui_input_text,.cke_dialog_body input.cke_dialog_ui_input_password,.cke_dialog_body input.cke_dialog_ui_input_tel,.cke_dialog_body textarea.cke_dialog_ui_input_textarea,.cke_dialog_body div.cke_dialog_ui_input_select{margin-bottom:10px}.cke_dialog_body .cke_dialog_ui_input_select{width:100%!important}.sidebar-collapsed .gjs-cv-canvas{width:calc(100% + -0px)}.sidebar-collapsed .gjs-pn-panels{display:none}.sidebar-collapsed .gjs-cv-canvas,.sidebar-collapsed .gjs-pn-devices-c{left:0}.sidebar-collapsed #toggle-sidebar{padding:14px 18px;font-size:18px;box-shadow:2px 3px 10px 2px #0000004d;border-bottom-right-radius:4px}html,body{overflow-x:initial!important}form{-webkit-margin-after:0;margin-block-end:0}[data-cursor=default]{cursor:default}[data-cursor=text]{cursor:text}span[draggable=true]{display:inline-flex}[phpb-hide-if-not-editable]{background:rgba(253,227,193,.4901960784);border:1px dashed rgba(185,142,87,.4901960784);padding:7px;font-size:1.1rem;font-style:italic;font-weight:400;text-align:center;color:#5e5e5e}[phpb-hide-if-not-editable]:not(.editable){display:none}[data-gjs-type].gjs-comp-selected{outline:1px solid #0091d1!important;outline-offset:0!important}div[data-gjs-type].gjs-comp-selected{outline:1px solid #0091d1!important;outline-offset:-1px!important}[phpb-content-container],[phpb-blocks-container]{min-height:50px;width:100%}[phpb-blocks-container]{border:1px dashed #0091d1}html ::-webkit-scrollbar,body ::-webkit-scrollbar{width:11px;height:11px}html ::-webkit-scrollbar-track,body ::-webkit-scrollbar-track{background:#f5f5f5}html ::-webkit-scrollbar-thumb,body ::-webkit-scrollbar-thumb{background-color:#ccc}html ::-webkit-scrollbar-thumb:hover,body ::-webkit-scrollbar-thumb:hover{background-color:#bbb}.gjs-waiting{opacity:.5;pointer-events:none} diff --git a/dist/GrapesJS.js b/dist/GrapesJS.js new file mode 100644 index 0000000..21ceb48 --- /dev/null +++ b/dist/GrapesJS.js @@ -0,0 +1,689 @@ +$(document).ready(function() { + $(".gjs-editor").append($("#toggle-sidebar")), $(".gjs-pn-panels").prepend($("#sidebar-header")), $(".gjs-pn-panels").append($("#sidebar-bottom-buttons")), $("#toggle-sidebar").click(function() { + $("#gjs").toggleClass("sidebar-collapsed"), f(); + }), w(), window.editor.on("run:open-sm", function(u) { + $(".gjs-trt-traits").parent().parent().css("display", "none"), $(".gjs-sm-sectors").parent().parent().css("display", "block"), $("#gjs-sm-advanced .gjs-sm-properties").append($(".gjs-clm-tags")); + }), window.editor.on("run:open-tm", function(u) { + $(".gjs-sm-sectors").parent().parent().css("display", "none"), $(".gjs-trt-traits").parent().parent().css("display", "block"); + }), window.editor.on("block:drag:start", function(u) { + w(); + }), window.editor.on("rteToolbarPosUpdate", function(u) { + !window.editor || !window.editor.getSelected() || !window.editor.getSelected().getEl() || setTimeout(function() { + let b = $(".gjs-rte-toolbar").first(); + if (b.offset().top < u.elementTop + 0.5 * u.elementHeight) { + let C = u.elementTop - b.height(); + C > 0 && b.css("top", C + "px"); + } + }, 0); + }); + function w() { + $(window).width() < 1e3 && ($("#gjs").addClass("sidebar-collapsed"), f()); + } + function f() { + window.editor.trigger("change:canvasOffset canvasScroll"); + } + let d = !1; + $(document).keydown(function(u) { + u.which === 8 && (d = !0); + }).keyup(function(u) { + u.which === 8 && (d = !1); + }), $(window).on("beforeunload", function(u) { + d && u.preventDefault(); + }); +}); +function I() { + $(".gjs-blocks-cs").prepend($("#block-search")); +} +window.addEventListener("message", W, !1); +function W(w) { + w.data === "page-loaded" ? ($("#phpb-loading").addClass("loaded"), I(), window.isLoaded = !0, $(window).trigger("pagebuilder-page-loaded")) : w.data === "touch-start" && window.touchStart(); +} +$(document).on("input", "#block-search input", function() { + let w = $(this).val().toLowerCase(); + $(".gjs-block-category").each(function() { + let f = !1; + $(this).find(".gjs-block").each(function() { + $(this).data("original-html") || $(this).data("original-html", $(this).html()); + let d = $(this).text(); + if (d.toLowerCase().includes(w)) { + $(this).removeClass("d-none"), f = !0; + let u = new RegExp("(" + w + ")", "gi"), o = d.replace(u, "$1"); + $(this).find(".gjs-block-label").html( + $(this).data("original-html").replace(d.trim(), o) + ); + } else + $(this).addClass("d-none"); + }), $(this).removeClass("d-none"), f || $(this).addClass("d-none"); + }); +}); +(function() { + window.customBuilderScripts = {}, window.editor.on("component:create", (f) => { + if (f.components().length) { + let d = f.components().models[f.components().length - 1]; + if (d.attributes.type === "script") { + let u = f.attributes.attributes["block-id"]; + u === void 0 && (u = f.attributes.attributes.id); + let o = d, b = !1; + for (; o.parent(); ) + if (o = o.parent(), o.attributes.attributes["phpb-content-container"]) { + b = !0; + break; + } + b && (window.customBuilderScripts[u] = d.toHTML(), d.remove()); + } + } + }), window.editor.on("component:add", function(f) { + if (f.attributes["run-builder-script"] !== void 0) { + let d = customBuilderScripts; + window.customBuilderScripts[f.attributes["block-id"]] = customBuilderScripts[f.attributes["run-builder-script"]], runScriptsOfComponentAndChildren(f), window.customBuilderScripts = d, delete f.attributes["run-builder-script"]; + } + }), window.editor.on("sorter:drag:end", function(f) { + let d = f.modelToDrop; + d && d.attributes && (d.attributes["block-id"] || d.attributes.id) && window.runScriptsOfComponentAndChildren(d); + for (let u in CKEDITOR.instances) + CKEDITOR.instances[u].destroy(!0); + }), window.runScriptsOfComponentAndChildren = function(f) { + w(f), f.components().each(function(d) { + runScriptsOfComponentAndChildren(d); + }); + }; + function w(f) { + let d = f.attributes["block-id"]; + if (d === void 0 && (d = f.attributes.attributes.id), d && window.customBuilderScripts[d] !== void 0) { + let u = f.attributes["style-identifier"], o = $("").append(window.customBuilderScripts[d]); + o.find("script").prepend("let inPageBuilder = true;"), o.find("script").prepend('let blockSelector = ".' + u + '";'), o.find("script").prepend('let block = document.getElementsByClassName("' + u + '")[0];'), o.find("script").prepend("(function(){"), o.find("script").append("})();"); + let b = document.createElement("script"); + b.type = "text/javascript", b.innerHTML = o.find("script").html(), window.editor.Canvas.getDocument().body.appendChild(b); + } + } +})(); +(function() { + function w() { + d(); + let t = document.createElement("script"); + t.type = "text/javascript", t.src = window.injectionScriptUrl; + let e = t.outerHTML + "'; + } + } + } +} diff --git a/src/Extensions.php b/src/Extensions.php new file mode 100644 index 0000000..72b712e --- /dev/null +++ b/src/Extensions.php @@ -0,0 +1,251 @@ + [], + 'footer' => [], + 'admin-header' => [], + 'admin-footer' => [], + ]; + + /** + * Register an asset. + * @param string $src + * @param string $type + * @param string $location + * @param array['$key' => '$value'] $attributes + */ + public static function registerAsset(string $src, string $type, string $location = 'header', array $attributes = []) { + self::$assets[$location][] = [ + 'src' => $src, + 'type' => $type, + 'attributes' => $attributes + ]; + } + + /** + * Register a single extension-config. + * @param string $slug + * @param array $config + * @return void + */ + public static function registerConfig(string $slug, array $config) { + self::$configs[$slug] = $config; + } + + /** + * Register a single extension-config. + * @param string $slug + * @param array $backend + * @return void + */ + public static function registerBackend(string $slug, array $backend) { + self::$backends['ext--'.$slug] = $backend; + } + + /** + * Register a single route. + * @param string $slug + * @param string $includePath + * @return void + */ + public static function registerRoute(string $slug, string $includePath) { + self::$routes[$slug] = $includePath; + } + + /** + * Register multiple routes at once. + * @param array['$slug' => '$includePath'] $routes + * @return void + */ + + public static function addRoutes(array $routes) { + self::$routes = array_merge(self::$routes, $routes); + } + + /** + * Register multiple settings at once. + * @param array $settings + * @return void + */ + + public static function addSettings(array $settings) { + self::$settings = array_merge(self::$settings, $settings); + } + + /** + * Register a single block. + * @param string $slug + * @param string $directoryPath + */ + public static function registerBlock(string $slug, string $directoryPath) { + self::$blocks[$slug] = $directoryPath; + } + + /** + * Register a single layout. + * @param string $slug + * @param string $directoryPath + */ + public static function registerLayout(string $slug, string $directoryPath) { + self::$layouts[$slug] = $directoryPath; + } + + /** + * Register multiple blocks at once. + * @param array['$slug' => '$directoryPath'] $blocks + */ + + public static function addBlocks(array $blocks) { + self::$blocks = array_merge(self::$blocks, $blocks); + } + + /** + * Register multiple blocks at once. + * @param array['$slug' => '$directoryPath'] $layouts + */ + public static function addLayouts(array $layouts) { + self::$layouts = array_merge(self::$layouts, $layouts); + } + + /** + * Get all routes. + */ + public static function getRoutes() : array { + return self::$routes; + } + + /** + * Get all settings. + */ + public static function getSettings($ext = null) : array { + $settingIns = phpb_instance('setting'); + $hydrSettings = []; + foreach (self::$settings as $setting) { + if($ext !== null && !str_starts_with($setting['key'], 'ext--'.$ext.'--')){ + continue; + } + $setting['value'] = $settingIns::get($setting['key']) ?: $setting['default']; + $hydrSettings[] = $setting; + } + return $hydrSettings; + } + + /** + * Get all blocks. + */ + public static function getBlocks() : array { + return self::$blocks; + } + + /** + * Get all layouts. + */ + public static function getLayouts() : array { + return self::$layouts; + } + + /** + * Get all backends. + */ + public static function getBackends() : array { + return self::$backends; + } + + /** + * Get a single extension Config. + */ + public static function getConfig(string $id) { + return self::$configs[$id] ?? null; + } + + /** + * Get all extension Configs. + */ + public static function getConfigs() { + return self::$configs; + } + + /** + * Get a single route. + */ + public static function getRoute(string $id) { + return self::$routes[$id] ?? null; + } + + /** + * Get a single block. + */ + public static function getBlock(string $id) { + return self::$blocks[$id] ?? null; + } + + /** + * Get a single layout. + */ + public static function getLayout(string $id) { + return self::$layouts[$id] ?? null; + } + + /** + * Get all header assets. + */ + public static function getHeaderAssets() { + return self::$assets['header']; + } + + /** + * Get all footer assets. + */ + public static function getFooterAssets() { + return self::$assets['footer']; + } + + /** + * Get all admin header assets. + */ + public static function getAdminHeaderAssets() { + return self::$assets['admin-header']; + } + + /** + * Get all admin footer assets. + */ + public static function getAdminFooterAssets() { + return self::$assets['admin-footer']; + } +} diff --git a/src/Modules/Auth/Auth.php b/src/Modules/Auth/Auth.php new file mode 100644 index 0000000..6ba365a --- /dev/null +++ b/src/Modules/Auth/Auth.php @@ -0,0 +1,63 @@ + 'warning', + 'message' => phpb_trans('auth.invalid-credentials') + ]); + } + } elseif ($action === 'logout') { + unset($_SESSION['phpb_logged_in']); + phpb_redirect(phpb_url('website_manager')); + } + } + } + + /** + * Return whether the current request has an authenticated session. + * + * @return bool + */ + public function isAuthenticated() + { + return isset($_SESSION['phpb_logged_in']); + } + + /** + * If the user is not authenticated, show the login form. + */ + public function requireAuth() + { + if (! $this->isAuthenticated()) { + $this->renderLoginForm(); + exit(); + } + } + + /** + * Render the login form. + */ + public function renderLoginForm() + { + $viewFile = 'login-form'; + require __DIR__ . '/resources/views/layout.php'; + } +} diff --git a/src/Modules/Auth/resources/views/layout.php b/src/Modules/Auth/resources/views/layout.php new file mode 100644 index 0000000..fa5c5e6 --- /dev/null +++ b/src/Modules/Auth/resources/views/layout.php @@ -0,0 +1,24 @@ + + + + + + <?= phpb_trans('auth.title') ?> + + + + + + +
+ + + +
+ + + diff --git a/src/Modules/Auth/resources/views/login-form.php b/src/Modules/Auth/resources/views/login-form.php new file mode 100644 index 0000000..ab2e894 --- /dev/null +++ b/src/Modules/Auth/resources/views/login-form.php @@ -0,0 +1,20 @@ +
+

+
+ +
+ +
+ +
+ + + + + + +
diff --git a/src/Modules/GrapesJS/Block/BaseController.php b/src/Modules/GrapesJS/Block/BaseController.php new file mode 100644 index 0000000..567f12f --- /dev/null +++ b/src/Modules/GrapesJS/Block/BaseController.php @@ -0,0 +1,45 @@ +model = $model; + $this->page = $page; + $this->forPageBuilder = $forPageBuilder; + } + + /** + * Handle the current request. + */ + public function handleRequest() + { + } + +} diff --git a/src/Modules/GrapesJS/Block/BaseModel.php b/src/Modules/GrapesJS/Block/BaseModel.php new file mode 100644 index 0000000..aa073ca --- /dev/null +++ b/src/Modules/GrapesJS/Block/BaseModel.php @@ -0,0 +1,99 @@ +block = $block; + $this->data = is_array($data) ? $data : []; + $this->page = $page; + $this->forPageBuilder = $forPageBuilder; + + if (phpb_in_editmode() && method_exists($this, 'initEdit')) { + $this->initEdit(); + } else { + $this->init(); + } + } + + /** + * Initialize the model. + */ + protected function init() + { + } + + /** + * Return the given setting stored for this block instance using the page builder. + * + * @param $setting + * @param bool $allowHtml + * @return string + */ + public function setting($setting, $allowHtml = false) + { + $value = $this->block->get('settings.' . $setting . '.value'); + + if (isset($this->data['settings']['attributes'][$setting])) { + $value = $this->data['settings']['attributes'][$setting]; + } + + return $allowHtml ? $value : phpb_e($value); + } + + /** + * Return data of this block, passed as argument by a parent block. + * + * @param $key + * @return string + */ + public function data($key) + { + return $this->data[$key] ?? null; + } + + /** + * Return data of the child block with the given relative ID. + * + * @param $childBlockId + * @return string + */ + public function childData($childBlockId) + { + return $this->data['blocks'][$childBlockId] ?? null; + } + +} diff --git a/src/Modules/GrapesJS/Block/BlockAdapter.php b/src/Modules/GrapesJS/Block/BlockAdapter.php new file mode 100644 index 0000000..a396efa --- /dev/null +++ b/src/Modules/GrapesJS/Block/BlockAdapter.php @@ -0,0 +1,150 @@ +pageRenderer = $pageRenderer; + $this->block = $block; + } + + /** + * Return the slug identifying this type of theme block. + * + * @return string + */ + public function getSlug() + { + return $this->block->getSlug(); + } + + /** + * Return the visible title of this block. + * + * @return string + */ + public function getTitle() + { + if ($this->block->get('title')) { + return $this->block->get('title'); + } + return str_replace('-', ' ', ucfirst($this->getSlug())); + } + + /** + * Return the category this block belongs to. + * + * @return string|null + */ + public function getCategory() + { + if ($this->block->get('category')) { + return $this->block->get('category'); + } + return phpb_trans('pagebuilder.default-category'); + } + + /** + * Return an array representation of the theme block, for adding as a block to GrapesJS. + * + * @return array + * @throws Exception + */ + public function getBlockManagerArray() + { + $content = $this->pageRenderer->renderBlock($this->block->getSlug()); + + $img = ''; + if (file_exists($this->block->getThumbPath())) { + $img = '
'; + } + + $data = [ + 'label' => $img . $this->getTitle(), + 'category' => $this->getCategory(), + 'content' => $content + ]; + + if (! $img) { + $iconClass = 'fa fa-bars'; + if ($this->block->get('icon')) { + $iconClass = $this->block->get('icon'); + } + $data['attributes'] = ['class' => $iconClass]; + } + + return $data; + } + + /** + * Return the array of settings of the theme block, for populating the settings tab in the GrapesJS sidebar. + * + * @return array + */ + public function getBlockSettingsArray() + { + $blockSettings = $this->block::getDynamicConfig($this->getSlug())['settings'] ?? $this->block->get('settings'); + if ($this->block->isHtmlBlock() || ! is_array($blockSettings)) { + return []; + } + + $settings = []; + foreach ($blockSettings as $name => $blockSetting) { + if (! isset($blockSetting['label'])) { + continue; + } + $type = $blockSetting['type'] ?? 'text'; + + $setting = [ + 'type' => $type, + 'name' => $name, + 'label' => $blockSetting['label'], + 'default-value' => $blockSetting['value'] ?? '', + 'placeholder' => $blockSetting['placeholder'] ?? '', + ]; + + if ($type === 'select') { + $setting['options'] = $blockSetting['options'] ?? []; + } elseif ($type === 'yes_no') { + $setting['type'] = 'select'; + $setting['options'] = [ + ['id' => 0, 'name' => phpb_trans('pagebuilder.no')], + ['id' => 1, 'name' => phpb_trans('pagebuilder.yes')] + ]; + } + + $settings[] = $setting; + } + + return $settings; + } +} diff --git a/src/Modules/GrapesJS/Block/BlockRenderer.php b/src/Modules/GrapesJS/Block/BlockRenderer.php new file mode 100644 index 0000000..78dbc00 --- /dev/null +++ b/src/Modules/GrapesJS/Block/BlockRenderer.php @@ -0,0 +1,273 @@ +theme = $theme; + $this->page = $page; + $this->forPageBuilder = $forPageBuilder; + } + + /** + * Change this BlockRenderer to render not editable blocks. + * + * @return $this + */ + public function notEditable() + { + $this->forPageBuilder = false; + return $this; + } + + /** + * Change this BlockRenderer to render editable blocks. + * + * @return $this + */ + public function editable() + { + $this->forPageBuilder = true; + return $this; + } + + /** + * Render a theme block with the given slug using the given block data. + * + * @param string $blockSlug + * @param array|null $blockData + * @param null $id id of the specific block instance + * @return string + */ + public function renderWithSlug(string $blockSlug, $blockData = null, $id = null) + { + $block = ($path = Extensions::getBlock($blockSlug)) + ? new ThemeBlock($this->theme, $path, true, $blockSlug) + : new ThemeBlock($this->theme, $blockSlug); + + return $this->render($block, $blockData, $id); + } + + /** + * Render the given theme block with the given stored block data. + * + * @param ThemeBlock $themeBlock + * @param array|null $blockData + * @param null $id id of the specific block instance + * @return string + */ + public function render(ThemeBlock $themeBlock, $blockData = null, $id = null) + { + $blockData = $blockData ?? []; + + if ($themeBlock->isHtmlBlock()) { + $html = $this->renderHtmlBlock($themeBlock, $blockData); + } else { + $html = $this->renderDynamicBlock($themeBlock, $blockData); + } + + $wrapperElement = $themeBlock->getWrapperElement(); + if ($this->forPageBuilder) { + $id = $id ?? $themeBlock->getSlug(); + $html = '' + . $html . $this->renderBuilderScript($themeBlock) + . ''; + } else { + if (! $themeBlock->isHtmlBlock() && isset($blockData['settings']['attributes']['style-identifier'])) { + // add wrapper element around dynamic pagebuilder blocks, which receives the style identifier class if additional styling is added to the block via the pagebuilder + $html = '<' . $wrapperElement . ' class="' . phpb_e($blockData['settings']['attributes']['style-identifier']) . '">' + . $html . $this->renderScript($themeBlock) + . ''; + } else { + $html .= $this->renderScript($themeBlock); + } + } + return $html; + } + + /** + * Render the pagebuilder script of the given block. + * + * @param ThemeBlock $themeBlock + * @return string + */ + public function renderBuilderScript(ThemeBlock $themeBlock) + { + $builderScriptFilePath = $themeBlock->getBuilderScriptFile(); + if ($builderScriptFilePath) { + if (pathinfo($builderScriptFilePath)['extension'] === 'php') { + ob_start(); + require $builderScriptFilePath; + $scriptHtmlString = ob_get_contents(); + ob_end_clean(); + } else { + $scriptHtmlString = file_get_contents($builderScriptFilePath); + } + return ''; + } + // if no builder script was specified, fallback to using the general script (if provided) + return $this->renderScript($themeBlock, true); + } + + /** + * Render the script of the given block for rendering the block on a publicly accessible web page. + * + * @param ThemeBlock $themeBlock + * @param bool $forPageBuilder + * @return string + */ + public function renderScript(ThemeBlock $themeBlock, bool $forPageBuilder = false) + { + $scriptFilePath = $themeBlock->getScriptFile(); + if ($scriptFilePath) { + if (pathinfo($scriptFilePath)['extension'] === 'php') { + ob_start(); + require $scriptFilePath; + $scriptHtmlString = ob_get_contents(); + ob_end_clean(); + } else { + $scriptHtmlString = file_get_contents($scriptFilePath); + } + + $script = $this->removeWrappedScriptTags($scriptHtmlString); + if ($forPageBuilder) { + return ''; + } else { + return $this->wrapScriptWithScopeAndContextData($script); + } + } + return ''; + } + + /** + * Remove script tags wrapped around to given JavaScript string, if they are present. + * This is necessary if the script is coming from a .html or .php file. + * + * @param $scriptHtmlString + * @return string + */ + protected function removeWrappedScriptTags($scriptHtmlString) + { + return str_replace('', '', $scriptHtmlString)); + } + + /** + * Wrap the given javascript with a script tag that has a unique id, + * add a scope around the script and add context data giving the script access to the exact block instance in the DOM. + * + * @param $script + * @return string + */ + protected function wrapScriptWithScopeAndContextData($script) + { + $scriptId = 'script' . rand(0, 10000000000); + $html = ''; + return $html; + } + + /** + * Render the given html theme block with the given stored block data. + * + * @param ThemeBlock $themeBlock + * @param $blockData + * @return string + */ + protected function renderHtmlBlock(ThemeBlock $themeBlock, $blockData) + { + if ($themeBlock->getControllerFile()) { + require_once $themeBlock->getControllerFile(); + $controllerClass = $themeBlock->getControllerClass(); + $controller = new $controllerClass; + + $model = new BaseModel($themeBlock, $blockData, $this->page, $this->forPageBuilder); + $controller->init($model, $this->page, $this->forPageBuilder); + $controller->handleRequest(); + } + + if (isset($blockData['html'])) { + $html = $blockData['html']; + } else { + $html = file_get_contents($themeBlock->getViewFile()); + } + return $html; + } + + /** + * Render the given dynamic theme block with the given stored block data. + * + * @param ThemeBlock $themeBlock + * @param $blockData + * @return string + */ + protected function renderDynamicBlock(ThemeBlock $themeBlock, $blockData) + { + $blockData = $blockData ?? []; + $controller = new BaseController; + $model = new BaseModel($themeBlock, $blockData, $this->page, $this->forPageBuilder); + + if ($themeBlock->getModelFile()) { + require_once $themeBlock->getModelFile(); + $modelClass = $themeBlock->getModelClass(); + $model = new $modelClass($themeBlock, $blockData, $this->page, $this->forPageBuilder); + } + + if ($themeBlock->getControllerFile()) { + require_once $themeBlock->getControllerFile(); + $controllerClass = $themeBlock->getControllerClass(); + $controller = new $controllerClass; + } + $controller->init($model, $this->page, $this->forPageBuilder); + $controller->handleRequest(); + + // init additional variables that should be accessible in the view + $renderer = $this; + $page = $this->page; + $block = $model; + + // unset variables that should be inaccessible inside the view + unset($controller, $model, $blockData); + + ob_start(); + require $themeBlock->getViewFile(); + $html = ob_get_contents(); + ob_end_clean(); + + return $html; + } +} diff --git a/src/Modules/GrapesJS/PageBuilder.php b/src/Modules/GrapesJS/PageBuilder.php new file mode 100644 index 0000000..6947ac8 --- /dev/null +++ b/src/Modules/GrapesJS/PageBuilder.php @@ -0,0 +1,387 @@ +theme = phpb_instance('theme', [ + phpb_config('theme'), + phpb_config('theme.active_theme') + ]); + } + + /** + * Set the theme used while rendering pages in the page builder. + * + * @param ThemeContract $theme + */ + public function setTheme(ThemeContract $theme) + { + $this->theme = $theme; + } + + /** + * Process the current GET or POST request and redirect or render the requested page. + * + * @param $route + * @param $action + * @param PageContract|null $page + * @return bool + * @throws Exception + */ + public function handleRequest($route, $action, PageContract $page = null) + { + phpb_set_in_editmode(); + + if ($route === 'thumb_generator') { + $thumbGenerator = new ThumbGenerator($this->theme); + return $thumbGenerator->handleThumbRequest($action); + } + + if (is_null($page)) { + $pageId = $_GET['page'] ?? null; + $pageRepository = new PageRepository; + $page = $pageRepository->findWithId($pageId); + } + if (! ($page instanceof PageContract)) { + return false; + } + + switch ($action) { + case null: + case 'edit': + $this->renderPageBuilder($page); + exit(); + break; + case 'store': + if (isset($_POST) && isset($_POST['data'])) { + $data = json_decode($_POST['data'], true); + $this->updatePage($page, $data); + exit(); + } + break; + case 'upload': + if (isset($_FILES)) { + $this->handleFileUpload(); + } + break; + case 'upload_delete': + if (isset($_POST['id'])) { + $this->handleFileDelete(); + } + break; + case 'renderBlock': + if (isset($_POST['language']) && isset($_POST['data']) && isset(phpb_active_languages()[$_POST['language']])) { + $this->renderPageBuilderBlock($page, $_POST['language'], json_decode($_POST['data'], true)); + exit(); + } + break; + case 'renderLanguageVariant': + if (isset($_POST['language']) && isset($_POST['data']) && isset(phpb_active_languages()[$_POST['language']])) { + $this->renderLanguageVariant($page, $_POST['language'], json_decode($_POST['data'], true)); + exit(); + } + break; + } + + return false; + } + + /** + * Handle uploading of the posted file. + * + * @throws Exception + */ + public function handleFileUpload() + { + $publicId = sha1(uniqid(rand(), true)); + $uploader = phpb_instance(Uploader::class, ['files']); + $uploader + ->file_name($publicId . '/' . str_replace(' ', '-', $uploader->file_src_name)) + ->upload_to(phpb_config('storage.uploads_folder') . '/') + ->run(); + + if (! $uploader->was_uploaded) { + die("Upload error: {$uploader->error}"); + } else { + $originalFile = str_replace(' ', '-', $uploader->file_src_name); + $originalMime = $uploader->file_src_mime; + $serverFile = $uploader->final_file_name; + + $uploadRepository = new UploadRepository; + $uploadedFile = $uploadRepository->create([ + 'public_id' => $publicId, + 'original_file' => $originalFile, + 'mime_type' => $originalMime, + 'server_file' => $serverFile + ]); + + echo json_encode([ + 'data' => [ + 'public_id' => $publicId, + 'src' => $uploadedFile->getUrl(), + 'type' => 'image' + ] + ]); + exit(); + } + } + + /** + * Handle deleting of the posted previously uploaded file. + */ + public function handleFileDelete() + { + $uploadRepository = new UploadRepository; + $uploadedFileResult = $uploadRepository->findWhere('public_id', $_POST['id']); + if (empty($uploadedFileResult)) { + echo json_encode([ + 'success' => false, + 'message' => 'File not found' + ]); + exit(); + } + + $uploadedFile = $uploadedFileResult[0]; + $uploadRepository->destroy($uploadedFile->id); + + $serverFilePath = realpath(phpb_config('storage.uploads_folder') . '/' . $uploadedFile->server_file); + if ($serverFilePath) { + unlink($serverFilePath); + } + + $parentDirectory = realpath(phpb_config('storage.uploads_folder') . '/' . dirname($uploadedFile->server_file)); + if ($parentDirectory && dirname($uploadedFile->server_file) !== '.') { + rmdir($parentDirectory); + } + + echo json_encode([ + 'success' => true + ]); + exit(); + } + + /** + * Render the PageBuilder for the given page. + * + * @param PageContract $page + * @throws Exception + */ + public function renderPageBuilder(PageContract $page) + { + phpb_set_in_editmode(); + + // init variables that should be accessible in the view + $pageBuilder = $this; + $pageRenderer = phpb_instance(PageRenderer::class, [$this->theme, $page, true]); + if (! empty($_SESSION['phpagebuilder_language'])) { + $pageRenderer->setLanguage($_SESSION['phpagebuilder_language']); + } + + // create an array of theme blocks and theme block settings for in the page builder sidebar + $blocks = []; + $blockSettings = []; + foreach ($this->theme->getThemeBlocks() as $themeBlock) { + $slug = phpb_e($themeBlock->getSlug()); + $adapter = phpb_instance(BlockAdapter::class, [$pageRenderer, $themeBlock]); + if ($themeBlock->get('hidden') !== true) { + $blocks[$slug] = $adapter->getBlockManagerArray(); + } + $blockSettings[$slug] = $adapter->getBlockSettingsArray(); + } + + // create an array of all uploaded assets + $assets = []; + foreach ((new UploadRepository)->getAll() as $file) { + $assets[] = [ + 'src' => $file->getUrl(), + 'public_id' => $file->public_id + ]; + } + + require __DIR__ . '/resources/views/layout.php'; + } + + /** + * Render the given page. + * + * @param PageContract $page + * @param null $language + * @return string + */ + public function renderPage(PageContract $page, $language = null): string + { + $pageRenderer = phpb_instance(PageRenderer::class, [$this->theme, $page]); + if (! is_null($language)) { + $pageRenderer->setLanguage($language); + } + return $pageRenderer->render(); + } + + /** + * Render in context of the given page, the given block with the passed settings, for updating the page builder. + * + * @param PageContract $page + * @param string $language + * @param array $blockData + * @throws Exception + */ + public function renderPageBuilderBlock(PageContract $page, string $language, $blockData = []) + { + phpb_set_in_editmode(); + + $blockData = is_array($blockData) ? $blockData : []; + $page->setData(['data' => $blockData], false); + + $pageRenderer = phpb_instance(PageRenderer::class, [$this->theme, $page, true]); + $pageRenderer->setLanguage($language); + echo $pageRenderer->parseShortcodes($blockData['html'], $blockData['blocks']); + } + + /** + * Render the given page in the given language using the given block data. + * + * @param PageContract $page + * @param string $language + * @param array $blockData + * @throws Exception + */ + public function renderLanguageVariant(PageContract $page, string $language, $blockData = []) + { + phpb_set_in_editmode(); + $_SESSION['phpagebuilder_language'] = $language; + + $blockData = is_array($blockData) ? $blockData : []; + $page->setData(['data' => $blockData], false); + + $pageRenderer = phpb_instance(PageRenderer::class, [$this->theme, $page, true]); + $pageRenderer->setLanguage($language); + echo json_encode([ + 'dynamicBlocks' => $pageRenderer->getPageBlocksData()[$language] + ]); + } + + /** + * Update the given page with the given data (an array of html blocks). + * + * @param PageContract $page + * @param $data + * @return bool|object|null + */ + public function updatePage(PageContract $page, $data) + { + $pageRepository = new PageRepository; + return $pageRepository->updatePageData($page, $data); + } + + /** + * Return the list of all pages, used in CKEditor link editor. + * + * @return array + */ + public function getPages() + { + $pages = []; + + $pageRepository = new PageRepository; + foreach ($pageRepository->getAll() as $page) { + $pages[] = [ + phpb_e($page->getName()), + phpb_e($page->getId()) + ]; + } + + return $pages; + } + + /** + * Return this page's components in the format passed to GrapesJS. + * + * @param PageContract $page + * @return array + */ + public function getPageComponents(PageContract $page) + { + $data = $page->getBuilderData(); + $components = $data['components'] ?? [0 => []]; + // backwards compatibility, components are now stored for each main container (@todo: remove this at the first mayor version) + if (isset($components[0]) && ! empty($components[0]) && ! isset($components[0][0])) { + $components = [0 => $components]; + } + return $components; + } + + /** + * Return this page's style in the format passed to GrapesJS. + * + * @param PageContract $page + * @return array + */ + public function getPageStyleComponents(PageContract $page) + { + $data = $page->getBuilderData(); + if (isset($data['style'])) { + return $data['style']; + } + return []; + } + + /** + * Get or set custom css for customizing layout of the page builder. + * + * @param string|null $css + * @return string + */ + public function customStyle(string $css = null) + { + if (! is_null($css)) { + $this->css = $css; + } + return $this->css; + } + + /** + * Get or set custom scripts for customizing behaviour of the page builder. + * + * @param string $location head|body + * @param string|null $scripts + * @return string + */ + public function customScripts(string $location, string $scripts = null) + { + if (! is_null($scripts)) { + $this->scripts[$location] = $scripts; + } + return $this->scripts[$location] ?? ''; + } +} diff --git a/src/Modules/GrapesJS/PageRenderer.php b/src/Modules/GrapesJS/PageRenderer.php new file mode 100644 index 0000000..5e2f900 --- /dev/null +++ b/src/Modules/GrapesJS/PageRenderer.php @@ -0,0 +1,325 @@ +theme = $theme; + $this->page = $page; + $this->pageData = $page->getBuilderData(); + $this->shortcodeParser = phpb_instance(ShortcodeParser::class, [$this]); + $this->setLanguage(phpb_current_language()); + $this->forPageBuilder = $forPageBuilder; + } + + /** + * Set which page language variant to use while rendering. + * + * @param $language + */ + public function setLanguage($language) + { + // if the given language is unknown, default the set language to the first available language + $blockKeysAreLanguages = true; + $supportedLanguages = array_keys($this->pageData['blocks'] ?? []); + // check whether keys are valid languages (renderPageBuilderBlock uses pageData without language data) + foreach ($supportedLanguages as $supportedLanguage) { + if (strlen($supportedLanguage) > 5) { + $blockKeysAreLanguages = false; + break; + } + } + if ($blockKeysAreLanguages) { + if (! in_array($language, $supportedLanguages)) { + $language = $supportedLanguages[0] ?? $language; + } + } + + $this->language = $language; + $this->pageBlocksData = $this->getStoredPageBlocksData(); + $this->shortcodeParser->setLanguage($language); + } + + /** + * Return the absolute path to the layout view of this page. + * + * @return string|null + */ + public function getPageLayoutPath() + { + $layout = basename($this->page->getLayout()); + $layoutPath = $this->theme->getFolder() . '/layouts/' . $layout . '/view.php'; + + if ($path = Extensions::getLayout($layout)) { + $layoutPath = $path . '/view.php'; + } + + return file_exists($layoutPath) ? $layoutPath : null; + } + + /** + * Set whether the currently rendered page can be cached. + * + * @param bool $canBeCached + * @param string|null $cacheLifetime + */ + public static function setCanBeCached(bool $canBeCached, $cacheLifetime = null) + { + if (! $canBeCached || ($cacheLifetime && intval($cacheLifetime) <= 0)) { + static::$canBeCached = false; + } elseif ($cacheLifetime) { + static::$cacheLifetime = min(static::$cacheLifetime, intval($cacheLifetime)); + } + } + + /** + * Return whether the rendered page can be cached. + * I.e. no blocks were encountered with content that varies per page load. + * + * @return bool + */ + public static function canBeCached(): bool + { + return static::$canBeCached ?? true; + } + + /** + * Return the maximum number of minutes the rendered page should be cached. + * + * @return int + */ + public static function getCacheLifetime(): int + { + if (! static::canBeCached()) { + return 0; + } + return static::$cacheLifetime; + } + + /** + * Return an array with for each block of this page the stored html and settings data. + * + * @return array + */ + public function getStoredPageBlocksData() + { + return $this->pageData['blocks'][$this->language] ?? $this->pageData['blocks'] ?? []; + } + + /** + * Return the rendered version of the page. + * + * @return string + * @throws Exception + */ + public function render() + { + // init variables that should be accessible in the view + $renderer = $this; + $page = $this->page; + if ($this->forPageBuilder) { + $body = '
'; + } else { + $body = $this->renderBody(); + } + + $layoutPath = $this->getPageLayoutPath(); + if ($layoutPath) { + ob_start(); + require $layoutPath; + $pageHtml = ob_get_contents(); + ob_end_clean(); + } else { + $pageHtml = $body; + } + + // parse any shortcodes present in the page layout + $pageHtml = $this->parseShortcodes($pageHtml); + + return $pageHtml; + } + + /** + * Return the page body for display on the website. + * The body contains all blocks which are put into the selected layout. + * + * @param int $mainContainerIndex + * @return string + * @throws Exception + */ + public function renderBody($mainContainerIndex = 0) + { + $html = ''; + $data = $this->pageData; + + if (isset($data['html']) && is_array($data['html'])) { + $html = $this->parseShortcodes($data['html'][$mainContainerIndex]); + // render html for each content container, to ensure all rendered blocks are accessible in the pagebuilder + if (phpb_in_editmode()) { + foreach ($data['html'] as $contentContainerHtml) { + $this->parseShortcodes($contentContainerHtml); + } + } + } + // backwards compatibility, html stored for only one layout container (@todo: remove this at the first mayor version) + if (isset($data['html']) && is_string($data['html'])) { + $html = $this->parseShortcodes($data['html']); + } + + // include any style changes made via the page builder + if (isset($data['css'])) { + $html .= ''; + } + + return $html; + } + + /** + * Return a fully rendered theme block (including children blocks) with the given slug, data instance id and data context. + * This method is called while parsing shortcodes. + * + * @param $slug + * @param null $id the id with which data for this block is stored + * @param null $context + * @param int $maxDepth + * @return string + * @throws Exception + */ + public function renderBlock($slug, $id = null, $context = null, $maxDepth = 25) + { + $themeBlock = ($blockPath = Extensions::getBlock($slug)) + ? new ThemeBlock($this->theme, $blockPath, true, $slug) + : new ThemeBlock($this->theme, $slug); + + $id = $id ?? $themeBlock->getSlug(); + $context = $context[$id] ?? $this->pageBlocksData[$id] ?? []; + + $blockRenderer = new BlockRenderer($this->theme, $this->page, $this->forPageBuilder); + $renderedBlock = $blockRenderer->render($themeBlock, $context ?? [], $id); + + // determine the context for rendering nested blocks + // if the current block is a html block, the context starts again at full page data + // if the current block is a dynamic block, use the nested block data inside the current block's context + $context = $context['blocks'] ?? []; + if ($themeBlock->isHtmlBlock()) { + $context = $this->pageBlocksData; + } + + return $this->shortcodeParser->doShortcodes($renderedBlock, $context, $maxDepth - 1); + } + + /** + * Parse the given html with shortcodes to fully rendered html. + * + * @param string $htmlWithShortcodes + * @param array $context the data for each block to be used while parsing the shortcodes + * @return string + * @throws Exception + */ + public function parseShortcodes(string $htmlWithShortcodes, $context = null) + { + $context = $context ?? $this->pageBlocksData; + return $this->shortcodeParser->doShortcodes($htmlWithShortcodes, $context); + } + + /** + * Return this page's blocks data to be loaded into the page edited inside GrapesJS. + * + * @return array + * @throws Exception + */ + public function getPageBlocksData() + { + $initialLanguage = $this->language; + + // remove the already rendered blocks + $this->shortcodeParser->resetRenderedBlocks(); + + // create the structure of page blocks data for each language + $pageBlocks = []; + foreach (phpb_active_languages() as $languageCode => $languageTranslation) { + $this->setLanguage($languageCode); + + // for the current language build up a structure of rendered versions and use the stored data for the other languages + if ($languageCode === $initialLanguage) { + $this->renderBody(); + $pageBlocks[$languageCode] = $this->shortcodeParser->getRenderedBlocks()[$languageCode] ?? []; + } else { + $pageBlocks[$languageCode] = $this->pageBlocksData; + } + + if (empty($pageBlocks[$languageCode])) { + $pageBlocks[$languageCode] = null; + } + } + + // revert to initial language + $this->setLanguage($initialLanguage); + + // return the rendered html and settings for each block + return $pageBlocks; + } +} diff --git a/src/Modules/GrapesJS/ShortcodeParser.php b/src/Modules/GrapesJS/ShortcodeParser.php new file mode 100644 index 0000000..4a27deb --- /dev/null +++ b/src/Modules/GrapesJS/ShortcodeParser.php @@ -0,0 +1,276 @@ +pageRenderer = $pageRenderer; + $this->renderedBlocks = []; + + $pageRepository = new PageRepository; + foreach ($pageRepository->getAll(['id']) as $page) { + $this->pages[$page->getId()] = $page->getRoute(); + } + } + + /** + * Set the current language. + * + * @param $language + */ + public function setLanguage($language) + { + $this->language = $language; + } + + /** + * Perform the tasks for all shortcodes in the given html string. + * + * @param $html + * @param array $context + * @param int $maxDepth + * @return mixed|string + * @throws Exception + */ + public function doShortcodes($html, array $context = [], $maxDepth = 25) + { + if ($maxDepth === 0) { + throw new Exception("Maximum doShortcodes depth has been reached, " + . "probably due to a circular shortcode reference in one of the theme blocks."); + } + + $html = $this->doBlockShortcodes($html, $context, $maxDepth); + $html = $this->doPageShortcodes($html); + $html = $this->doThemeUrlShortcodes($html); + $html = $this->doBlocksContainerShortcodes($html); + return $html; + } + + /** + * Render all blocks defined with shortcodes in the given html string. + * + * @param string $html + * @param array $context + * @param int $maxDepth + * @return string + * @throws Exception + */ + protected function doBlockShortcodes($html, array $context, $maxDepth) + { + $matches = self::findMatches('block', $html); + if (empty($matches)) { + return $html; + } + + foreach ($matches as $match) { + if (! isset($match['attributes']['slug'])) { + continue; + } + $slug = $match['attributes']['slug']; + $id = $match['attributes']['id'] ?? $slug; + if (isset($context[$id]['settings']['attributes'])) { + foreach ($match['attributes'] as $attribute => $value) { + if (in_array($attribute, ['id', 'slug'])) { + continue; + } + $context[$id]['settings']['attributes'][$attribute] = $value; + } + } + $blockHtml = $this->pageRenderer->renderBlock($slug, $id, $context, $maxDepth); + + // store rendered block in a structure used for outputting all blocks to the pagebuilder + if (phpb_in_editmode() && strpos($id, 'ID') === 0) { + $this->renderedBlocks[$this->language][$id] = $context[$id] ?? []; + $this->renderedBlocks[$this->language][$id]['html'] = $blockHtml; + } + + // replace shortcode match with the $blockHtml (note: this replaces only the first match) + $pos = strpos($html, $match['shortcode']); + if ($pos !== false) { + $html = substr_replace($html, $blockHtml, $pos, strlen($match['shortcode'])); + } + } + + return $html; + } + + /** + * Replace all page shortcodes for the corresponding absolute page url. + * @todo this currently replaces the shortcode with page route instead of URL + * + * @param $html + * @return mixed + */ + protected function doPageShortcodes($html) + { + if (phpb_in_editmode()) { + return $html; + } + + $matches = self::findMatches('page', $html); + if (empty($matches)) { + return $html; + } + + foreach ($matches as $match) { + if (! isset($match['attributes']['id'])) { + continue; + } + $pageId = $match['attributes']['id']; + + $route = ''; + if (isset($this->pages[$pageId])) { + $route = $this->pages[$pageId]; + } + $html = str_replace($match['shortcode'], $route, $html); + } + + return $html; + } + + /** + * Replace all [theme-url] shortcodes for the absolute URL to the theme's public folder. + * + * @param $html + * @return mixed + */ + protected function doThemeUrlShortcodes($html) + { + $matches = self::findMatches('theme-url', $html); + + if (empty($matches)) { + return $html; + } + + foreach ($matches as $match) { + $themeUrl = phpb_config('theme.folder_url') . '/' . phpb_e(phpb_config('theme.active_theme')); + $html = str_replace($match['shortcode'], $themeUrl, $html); + } + + return $html; + } + + /** + * Replace all [blocks-container] shortcodes for a
+ * + * @param $html + * @return mixed + */ + protected function doBlocksContainerShortcodes($html) + { + $matches = self::findMatches('blocks-container', $html); + + if (empty($matches)) { + return $html; + } + + foreach ($matches as $match) { + $replacement = '
'; + $html = str_replace($match['shortcode'], $replacement, $html); + } + + return $html; + } + + /** + * Return all matches of the given shortcode in the given html string. + * + * @param $shortcode + * @param $html + * @return array an array with for each $shortcode occurrence an array of attributes + */ + public static function findMatches($shortcode, $html) + { + // RegEx: https://www.regextester.com/104625 + $regex = '/\[' . $shortcode . '(\s.*?)?\](?:([^\[]+)?\[\/' . $shortcode . '\])?/'; + preg_match_all($regex, $html, $pregMatchAll); + $fullMatches = $pregMatchAll[0]; + $matchAttributeStrings = $pregMatchAll[1]; + + // loop through the attribute strings of each $shortcode instance and add the parsed variants to $matches + $matches = []; + foreach ($matchAttributeStrings as $i => $matchAttributeString) { + $matchAttributeString = trim($matchAttributeString); + + // as long as there are attributes in the attributes string, add them to $attributes + $attributes = []; + while (strpos($matchAttributeString, '=') !== false) { + list($attribute, $remainingString) = explode('=', $matchAttributeString, 2); + $attribute = trim($attribute); + + // if first char is " and at least two " exist, get attribute value between "" + if (strpos($remainingString, '"') === 0 && strpos($remainingString, '"', 1) !== false) { + list($empty, $value, $remainingString) = explode('"', $remainingString, 3); + $attributes[$attribute] = $value; + } else { + // attribute value was not between "", get value until next whitespace or until end of $remainingString + if (strpos($remainingString, ' ') !== false) { + list($value, $remainingString) = explode(' ', $remainingString, 2); + $attributes[$attribute] = $value; + } else { + $attributes[$attribute] = $remainingString; + $remainingString = ''; + } + } + + $matchAttributeString = $remainingString; + } + + $matches[] = [ + 'shortcode' => $fullMatches[$i], + 'attributes' => $attributes + ]; + } + + return $matches; + } + + /** + * Reset the structure of all rendered blocks. + */ + public function resetRenderedBlocks() + { + $this->renderedBlocks = []; + } + + /** + * Return the array of all blocks rendered while parsing shortcodes. + * + * @return array + */ + public function getRenderedBlocks() + { + return $this->renderedBlocks; + } + +} diff --git a/src/Modules/GrapesJS/Thumb/ThumbGenerator.php b/src/Modules/GrapesJS/Thumb/ThumbGenerator.php new file mode 100644 index 0000000..b302deb --- /dev/null +++ b/src/Modules/GrapesJS/Thumb/ThumbGenerator.php @@ -0,0 +1,153 @@ +theme = $theme; + } + + /** + * Handle requests to render and store block thumbnails. + * + * @param $action + * @return bool + * @throws Exception + */ + public function handleThumbRequest($action) + { + phpb_set_in_editmode(); + + if ($action === 'renderNextBlockThumb') { + $this->renderNextBlockThumb(); + exit(); + } + if ($action === 'upload' && isset($_POST) && isset($_POST['block']) && isset($_POST['data'])) { + foreach ($this->theme->getThemeBlocks() as $block) { + if ($_POST['block'] === $block->getSlug()) { + $this->r_mkdir(dirname($block->getThumbPath())); + $file = fopen($block->getThumbPath(), "wb"); + fwrite($file, $this->getRawData($_POST['data'])); + fclose($file); + exit(); + } + } + } + return false; + } + + /** + * Create directories recursively. + * + * @param string $path Path to create + * @param integer $mode Optional permissions + * @return boolean Success + */ + protected function r_mkdir($path, $mode = 0777) { + return is_dir($path) || ( $this->r_mkdir(dirname($path), $mode) && $this->_mkdir($path, $mode) ); + } + + /** + * Create directory. + * + * @param string $path Path to create + * @param integer $mode Optional permissions + * @return boolean Success + */ + protected function _mkdir($path, $mode = 0777) { + $old = umask(0); + $res = @mkdir($path, $mode); + umask($old); + return $res; + } + + /** + * Return binary image data from the given base64 encoded string. + * + * @param $base64ImageData + * @return string + * @throws Exception + */ + protected function getRawData($base64ImageData) + { + if (preg_match('/^data:image\/(\w+);base64,/', $base64ImageData, $type)) { + $data = substr($base64ImageData, strpos($base64ImageData, ',') + 1); + $type = strtolower($type[1]); + if (! in_array($type, ['jpg', 'jpeg', 'png'])) { + throw new Exception('Invalid image type'); + } + + $data = base64_decode($data); + if ($data === false) { + throw new Exception('Decode failed'); + } + return $data; + } else { + throw new Exception('Invalid data URI'); + } + } + + /** + * Render the next missing or outdated thumb of the given theme. + * + * @throws Exception + */ + public function renderNextBlockThumb() + { + foreach ($this->theme->getThemeBlocks() as $block) { + $this->renderThumbForBlock($block); + } + } + + /** + * Render a thumbnail for the given block, if no thumb is present or if the thumb needs an update. + * + * @param ThemeBlock $block + * @throws Exception + */ + public function renderThumbForBlock(ThemeBlock $block) + { + phpb_set_in_editmode(); + + $thumbPath = $block->getThumbPath(); + if (file_exists($thumbPath)) { + return; + } + + $page = phpb_instance('page'); + $page->setData([ + 'layout' => 'master', + 'data' => [ + 'html' => [ + 0 => '[block slug="' . $block->getSlug() . '"]' + ] + ] + ]); + + $renderer = phpb_instance(PageRenderer::class, [$this->theme, $page]); + echo $renderer->render(); + + $blockSlug = $block->getSlug(); + require __DIR__ . '/generator-view.php'; + exit(); + } + +} diff --git a/src/Modules/GrapesJS/Thumb/generator-view.php b/src/Modules/GrapesJS/Thumb/generator-view.php new file mode 100644 index 0000000..f091453 --- /dev/null +++ b/src/Modules/GrapesJS/Thumb/generator-view.php @@ -0,0 +1,38 @@ + + + diff --git a/src/Modules/GrapesJS/Upload/ResizeImage.php b/src/Modules/GrapesJS/Upload/ResizeImage.php new file mode 100644 index 0000000..771535c --- /dev/null +++ b/src/Modules/GrapesJS/Upload/ResizeImage.php @@ -0,0 +1,236 @@ +setImage($filename); + } else { + throw new Exception('Image ' . $filename . ' can not be found, try another image.'); + } + } + + /** + * Set the image variable by using image create. + * + * @param string $filename the image filename + * @throws Exception + */ + protected function setImage($filename) { + $size = getimagesize($filename); + $this->ext = $size['mime']; + + switch ($this->ext) { + // Image is a JPG + case 'image/jpg': + case 'image/jpeg': + // create a jpeg extension + $this->image = imagecreatefromjpeg($filename); + break; + + // Image is a GIF + case 'image/gif': + $this->image = @imagecreatefromgif($filename); + break; + + // Image is a PNG + case 'image/png': + $this->image = @imagecreatefrompng($filename); + break; + + // Mime type not found + default: + throw new Exception("File is not an image, please use another file type.", 1); + } + + $this->origWidth = imagesx($this->image); + $this->origHeight = imagesy($this->image); + } + + /** + * Save the image as the image type the original image was. + * + * @param string $savePath the path to store the new image + * @param string $imageQuality the quality level of image to create + */ + public function saveImage($savePath, $imageQuality = "100") { + switch ($this->ext) { + case 'image/jpg': + case 'image/jpeg': + // Check PHP supports this file type + if (imagetypes() & IMG_JPG) { + imagejpeg($this->newImage, $savePath, $imageQuality); + } + break; + + case 'image/gif': + // Check PHP supports this file type + if (imagetypes() & IMG_GIF) { + imagegif($this->newImage, $savePath); + } + break; + + case 'image/png': + $invertScaleQuality = 9 - round(($imageQuality / 100) * 9); + + // Check PHP supports this file type + if (imagetypes() & IMG_PNG) { + imagepng($this->newImage, $savePath, $invertScaleQuality); + } + break; + } + + imagedestroy($this->newImage); + } + + /** + * Resize the image to the given dimensions. + * + * @param integer $width max width of the image + * @param integer $height max height of the image + * @param string $resizeOption scale option for the image + */ + public function resizeTo($width, $height, $resizeOption = 'default') { + switch (strtolower($resizeOption)) { + case 'exact': + $this->resizeWidth = $width; + $this->resizeHeight = $height; + break; + case 'maxwidth': + $this->resizeWidth = $width; + $this->resizeHeight = $this->resizeHeightByWidth($width); + break; + case 'maxheight': + $this->resizeWidth = $this->resizeWidthByHeight($height); + $this->resizeHeight = $height; + break; + case 'proportionally': + $ratio_orig = $this->origWidth / $this->origHeight; + $this->resizeWidth = $width; + $this->resizeHeight = $height; + if ($width / $height > $ratio_orig) + $this->resizeWidth = $height * $ratio_orig; + else + $this->resizeHeight = $width / $ratio_orig; + break; + default: + if ($this->origWidth > $width || $this->origHeight > $height) { + if ($this->origWidth > $this->origHeight) { + $this->resizeHeight = $this->resizeHeightByWidth($width); + $this->resizeWidth = $width; + } else if ($this->origWidth < $this->origHeight) { + $this->resizeWidth = $this->resizeWidthByHeight($height); + $this->resizeHeight = $height; + } else { + $this->resizeWidth = $width; + $this->resizeHeight = $height; + } + } else { + $this->resizeWidth = $width; + $this->resizeHeight = $height; + } + break; + } + + $this->newImage = imagecreatetruecolor($this->resizeWidth, $this->resizeHeight); + if ($this->ext == "image/gif" || $this->ext == "image/png") { + imagealphablending($this->newImage, false); + imagesavealpha($this->newImage, true); + $transparent = imagecolorallocatealpha($this->newImage, 255, 255, 255, 127); + imagefilledrectangle($this->newImage, 0, 0, $this->resizeWidth, $this->resizeHeight, $transparent); + } + imagecopyresampled($this->newImage, $this->image, 0, 0, 0, 0, $this->resizeWidth, $this->resizeHeight, $this->origWidth, $this->origHeight); + } + + /** + * Get the resized height from the width maintaining aspect ratio. + * + * @param integer $width max image width + * @return float + */ + protected function resizeHeightByWidth($width) { + return floor(($this->origHeight / $this->origWidth) * $width); + } + + /** + * Get the resized width from the height maintaining aspect ratio. + * + * @param int $height max image height + * @return float + */ + protected function resizeWidthByHeight($height) { + return floor(($this->origWidth / $this->origHeight) * $height); + } +} diff --git a/src/Modules/GrapesJS/Upload/Uploader.php b/src/Modules/GrapesJS/Upload/Uploader.php new file mode 100644 index 0000000..ee52518 --- /dev/null +++ b/src/Modules/GrapesJS/Upload/Uploader.php @@ -0,0 +1,483 @@ +file_max_size($value). + * + * @var double + */ + protected $get_file_max_size = 25000000; + + /** + * Set auto replace if the file already exist. + * Remember you can also set calling $Upload->auto_replace($value_boolean). + * + * @var boolean + */ + protected $get_auto_replace = true; + + /** + * Set auto create path if the folder not exist. + * Remember you can also set calling $Upload->auto_create_path($value_boolean). + * + * @var boolean + */ + protected $get_auto_create_path = true; + + /** + * Allowed MIME types. + * + * @var array + */ + public $MIME_allowed = [ + "application/arj", + "application/excel", + "application/gnutar", + "application/msword", + "application/mspowerpoint", + "application/octet-stream", + "application/pdf", + "application/powerpoint", + "application/postscript", + "application/plain", + "application/rtf", + "application/vnd.ms-excel", + "application/vocaltec-media-file", + "application/wordperfect", + "application/x-bzip", + "application/x-bzip2", + "application/x-compressed", + "application/x-excel", + "application/x-gzip", + "application/x-latex", + "application/x-midi", + "application/x-msexcel", + "application/x-rtf", + "application/x-sit", + "application/x-stuffit", + "application/x-shockwave-flash", + "application/x-troff-msvideo", + "application/x-zip-compressed", + "application/xml", + "application/zip", + "audio/aiff", + "audio/basic", + "audio/midi", + "audio/mod", + "audio/mpeg", + "audio/mpeg3", + "audio/wav", + "audio/x-aiff", + "audio/x-au", + "audio/x-mid", + "audio/x-midi", + "audio/x-mod", + "audio/x-mpeg-3", + "audio/x-wav", + "audio/xm", + "image/bmp", + "image/gif", + "image/jpeg", + "image/pjpeg", + "image/x-icon", + "image/png", + "image/x-png", + "image/tiff", + "image/x-tiff", + "image/x-windows-bmp", + "multipart/x-zip", + "multipart/x-gzip", + "music/crescendo", + "text/richtext", + "text/plain", + "text/xml", + "video/avi", + "video/mpeg", + "video/msvideo", + "video/quicktime", + "video/quicktime", + "video/x-mpeg", + "video/x-ms-wmv", + "video/x-ms-asf", + "video/x-ms-asf-plugin", + "video/x-msvideo", + "x-music/x-midi" + ]; + + /** + * Uploader constructor. + * + * @param string|array $source image source + * @param boolean $fromFiles read from $_FILE + * @return boolean + */ + public function __construct($source, $fromFiles = true) { + $file = $fromFiles ? $_FILES[$source] : $source; + if (! isset($file)) { + return false; + } + + // extract info from uploaded file + $this->file_src_name = $file["name"]; + $this->file_src_temp = $file["tmp_name"]; + $this->file_src_size = $file["size"]; + $this->file_src_errors = $file['error']; + $this->file_src_mime = $file['type']; + $this->file_src_name_ext = pathinfo($file["name"], PATHINFO_EXTENSION); + + $this->was_uploaded = true; + return true; + } + + /** + * Run the uploader. + * + * @return bool + * @throws Exception + */ + public function run() { + // check whether the final name is in random mode + if ($this->file_name !== true) { + // preserve file extension if provided + if (! pathinfo($this->file_name, PATHINFO_EXTENSION)) { + $file = $this->file_name . '.' . $this->file_src_name_ext; + } else { + $file = $this->file_name; + } + $path = $this->upload_to . $file; + $this->upload_to = dirname($path); + } else { + $hash = md5(uniqid(rand(), true)); + $file = $hash . '.' . $this->file_src_name_ext; + $path = $this->upload_to . $file; + } + + $get_mime = isset($this->mime_check) ? true : false; + + // check MIME type which are allowed + if ($get_mime && empty($this->file_src_mime)) { + $this->was_uploaded = false; + $this->error = "MIME type can't be detected!"; + } elseif ($get_mime && !empty($this->file_src_mime) && !in_array($this->file_src_mime, $this->MIME_allowed)) { + $this->was_uploaded = false; + $this->error = "Incorrect type of file"; + } + + // check file maximum size + if ($this->file_src_size > $this->get_file_max_size) { + $this->error = 'File too big Original Size : ' . $this->file_src_size . ' File size limit : ' . $this->get_file_max_size; + $this->was_uploaded = false; + return false; + } + + // check whether destination directory exists or attempt to create it + if ($this->get_auto_create_path) { + if (! $this->r_mkdir($this->upload_to)) { + $this->was_uploaded = false; + $this->error = "Destination directory can't be created. Can't carry on a process"; + return false; + } + } elseif (! is_dir($this->upload_to)) { + $this->error = "Destination directory doesn't exist. Can't carry on a process"; + return false; + } + + // check whether file already exists or if are replacing it + if (file_exists($path)) { + if (! $this->get_auto_replace) { + $this->was_uploaded = false; + $this->error = $this->file_src_name . ' already exists. Please change the file name'; + } + return false; + } + + // check common error types + switch ($this->file_src_errors) { + case 0: + // all is OK + break; + case 1: + $this->was_uploaded = false; + $this->error = "File upload error (the uploaded file exceeds the upload_max_filesize directive in php.ini)"; + break; + case 2: + $this->was_uploaded = false; + $this->error = "File upload error (the uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the html form)"; + break; + case 3: + $this->was_uploaded = false; + $this->error = "File upload error (the uploaded file was only partially uploaded)"; + break; + case 4: + $this->was_uploaded = false; + $this->error = "File upload error (no file was uploaded)"; + break; + default: + $this->was_uploaded = false; + $this->error = "File upload error (unknown error code)"; + } + + // move file if successfully uploaded + if ($this->was_uploaded) { + if (move_uploaded_file($this->file_src_temp, $path)) { + $this->final_file_name = $file; + + // extract image dimensions + list($w, $h) = getimagesize($path); + $this->file_width = $w; + $this->file_height = $h; + + // resize image if necessary + if (isset($this->resize)) { + $resize = new ResizeImage($path); + $resize->resizeTo($this->image_x, $this->image_y, $this->resize_option); + $resize->saveImage($path); + } + return true; + } else { + $this->was_uploaded = false; + $this->error = 'Moving uploaded file failed.'; + return false; + } + } + + return false; + } + + /** + * Create directories recursively. + * + * @param string $path Path to create + * @param integer $mode Optional permissions + * @return boolean Success + */ + protected function r_mkdir($path, $mode = 0777) { + return is_dir($path) || ( $this->r_mkdir(dirname($path), $mode) && $this->_mkdir($path, $mode) ); + } + + /** + * Create directory. + * + * @param string $path Path to create + * @param integer $mode Optional permissions + * @return boolean Success + */ + protected function _mkdir($path, $mode = 0777) { + $old = umask(0); + $res = @mkdir($path, $mode); + umask($old); + return $res; + } + + /** + * Set the variable this function to define final name of the uploaded file. + * Use the value true for generate unique name (random name). + * + * @param boolean|string $file_name Final name of the file uploaded + * @return Uploader + */ + public function file_name($file_name) { + $this->file_name = $file_name; + return $this; + } + + /** + * Set the variable this function to define auto replacement if the file already exist. + * + * @param boolean $bool + * @return Uploader + */ + public function auto_replace($bool) { + $this->get_auto_replace = $bool; + return $this; + } + + /** + * Set the variable this function to define max size file is allowed. + * + * @param integer $size Maximum size in Bytes (1 000 000 bytes is equal to 1 MB) + * @return Uploader + */ + public function file_max_size($size) { + $this->get_file_max_size = (int) $size; + return $this; + } + + /** + * Set the variable this function to false if you don't want to check the MIME against the allowed list. + * This variable is set to true by default for security reason. + * + * @param boolean $bool Set to false to not check + * @return Uploader + */ + public function mime_check($bool = true) { + $this->mime_check = $bool; + return $this; + } + + /** + * Set the variable this function to choose a new path location for the image. + * + * @param string $path Path location of the uploaded file, with an ending slash + * @return Uploader + */ + public function upload_to($path) { + $this->upload_to = $path; + return $this; + } + + /** + * Set the variable this function to true to resize the file if it is an image. + * You will probably want to set {@link image_x()} and {@link image_y()}, and maybe one of the ratio variables. + * + * @param boolean $bool Default value is false (no resizing) + * @return Uploader + */ + public function resize($bool = false) { + $this->resize = $bool; + return $this; + } + + /** + * Set the variable this function to the wanted (or maximum/minimum) width for the processed image, in pixels. + * + * @param integer $width Default value is 150 + * @return Uploader + */ + public function image_x($width) { + $this->image_x = $width; + return $this; + } + + /** + * Set the variable this function to the wanted (or maximum/minimum) height for the processed image, in pixels. + * + * @param integer $height Default value is 150 + * @return Uploader + */ + public function image_y($height = 150) { + $this->image_y = $height; + return $this; + } + + /** + * Set the variable this function to choose the scale option for the image. + * + * @param string $option Default value is default, but you can use: exact, maxwidth, maxheight or proportional + * @return Uploader + */ + public function resize_option($option = 'default') { + $this->resize_option = $option; + return $this; + } + + /** + * Alias for {@link resize()} instead of using both {@link image_x()} && {@link image_y()} && {@link resize_option()}. + * + * @param integer $width Max width of the image + * @param integer $height Max height of the image + * @param string $resizeOption Scale option for the image + * @return Uploader + */ + public function resize_to($width = 150, $height = 150, $resizeOption = 'default') { + self::resize(true); + self::image_x($width); + self::image_y($height); + self::resize_option($resizeOption); + return $this; + } + +} diff --git a/src/Modules/GrapesJS/resources/assets/entry.js b/src/Modules/GrapesJS/resources/assets/entry.js new file mode 100644 index 0000000..e95d12c --- /dev/null +++ b/src/Modules/GrapesJS/resources/assets/entry.js @@ -0,0 +1,5 @@ +import './sass/app.scss' +import './sass/page-injection.scss' + +import './js/app.js' +import './js/page-injection.js' diff --git a/src/Modules/GrapesJS/resources/assets/images/flags/de.svg b/src/Modules/GrapesJS/resources/assets/images/flags/de.svg new file mode 100644 index 0000000..1acf302 --- /dev/null +++ b/src/Modules/GrapesJS/resources/assets/images/flags/de.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/src/Modules/GrapesJS/resources/assets/images/flags/en.svg b/src/Modules/GrapesJS/resources/assets/images/flags/en.svg new file mode 100644 index 0000000..132dbed --- /dev/null +++ b/src/Modules/GrapesJS/resources/assets/images/flags/en.svg @@ -0,0 +1,7 @@ + + + + + + + diff --git a/src/Modules/GrapesJS/resources/assets/images/flags/es.svg b/src/Modules/GrapesJS/resources/assets/images/flags/es.svg new file mode 100644 index 0000000..576dd67 --- /dev/null +++ b/src/Modules/GrapesJS/resources/assets/images/flags/es.svg @@ -0,0 +1,544 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/Modules/GrapesJS/resources/assets/images/flags/fr.svg b/src/Modules/GrapesJS/resources/assets/images/flags/fr.svg new file mode 100644 index 0000000..712c8a5 --- /dev/null +++ b/src/Modules/GrapesJS/resources/assets/images/flags/fr.svg @@ -0,0 +1,7 @@ + + + + + + + diff --git a/src/Modules/GrapesJS/resources/assets/images/flags/it.svg b/src/Modules/GrapesJS/resources/assets/images/flags/it.svg new file mode 100644 index 0000000..5cb92aa --- /dev/null +++ b/src/Modules/GrapesJS/resources/assets/images/flags/it.svg @@ -0,0 +1,7 @@ + + + + + + + diff --git a/src/Modules/GrapesJS/resources/assets/images/flags/nl.svg b/src/Modules/GrapesJS/resources/assets/images/flags/nl.svg new file mode 100644 index 0000000..2026937 --- /dev/null +++ b/src/Modules/GrapesJS/resources/assets/images/flags/nl.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/src/Modules/GrapesJS/resources/assets/images/image-placeholder-small.jpg b/src/Modules/GrapesJS/resources/assets/images/image-placeholder-small.jpg new file mode 100644 index 0000000..0d6ddf0 Binary files /dev/null and b/src/Modules/GrapesJS/resources/assets/images/image-placeholder-small.jpg differ diff --git a/src/Modules/GrapesJS/resources/assets/images/image-placeholder.png b/src/Modules/GrapesJS/resources/assets/images/image-placeholder.png new file mode 100644 index 0000000..4d8a0a2 Binary files /dev/null and b/src/Modules/GrapesJS/resources/assets/images/image-placeholder.png differ diff --git a/src/Modules/GrapesJS/resources/assets/js/app.js b/src/Modules/GrapesJS/resources/assets/js/app.js new file mode 100644 index 0000000..2f6999d --- /dev/null +++ b/src/Modules/GrapesJS/resources/assets/js/app.js @@ -0,0 +1,7 @@ +import './pagebuilder'; +import './block-search'; +import './run-builder-scripts'; +import './manage-editable-components'; +import './save-page'; +import './ckeditor-hyperlinks'; +import './responsive'; diff --git a/src/Modules/GrapesJS/resources/assets/js/block-search.js b/src/Modules/GrapesJS/resources/assets/js/block-search.js new file mode 100644 index 0000000..47c6135 --- /dev/null +++ b/src/Modules/GrapesJS/resources/assets/js/block-search.js @@ -0,0 +1,34 @@ + +$(document).on("input", "#block-search input", function() { + let term = $(this).val().toLowerCase(); + + $(".gjs-block-category").each(function() { + let atLeastOneMatch = false; + + $(this).find(".gjs-block").each(function() { + if (! $(this).data('original-html')) { + $(this).data('original-html', $(this).html()); + } + + let label = $(this).text(); + if (label.toLowerCase().includes(term)) { + $(this).removeClass("d-none"); + atLeastOneMatch = true; + + let regEx = new RegExp('(' + term + ')', "gi"); + let highlightedText = label.replace(regEx, '$1'); + + $(this).find(".gjs-block-label").html( + $(this).data('original-html').replace(label.trim(), highlightedText) + ); + } else { + $(this).addClass("d-none"); + } + }); + + $(this).removeClass("d-none"); + if (! atLeastOneMatch) { + $(this).addClass("d-none"); + } + }); +}); diff --git a/src/Modules/GrapesJS/resources/assets/js/ckeditor-hyperlinks.js b/src/Modules/GrapesJS/resources/assets/js/ckeditor-hyperlinks.js new file mode 100644 index 0000000..6b65637 --- /dev/null +++ b/src/Modules/GrapesJS/resources/assets/js/ckeditor-hyperlinks.js @@ -0,0 +1,127 @@ +$(document).ready(function() { + + window.CKEDITOR.on('instanceReady', function (event) { + event.editor.on('paste', function (event) { + let result = event.data.dataValue; + + // remove all not allowed tags + result = result.replace(/<(?!\/?(?:a|table|tr|td|th|thead|tbody|tfoot|caption|col|colgroup|p|ul|ol|li|br|strong|em|b|i|u|strike|sub|sup|h1|h2|h3|h4|h5|h6|blockquote|pre|hr)\b)[^>]+>/gm, ''); + + // remove all attributes of the allowed tags except from anchor + result = result.replace(/<(a|table|tr|td|th|thead|tbody|tfoot|caption|col|colgroup|p|ul|ol|li|br|strong|em|b|i|u|strike|sub|sup|h1|h2|h3|h4|h5|h6|blockquote|pre|hr)\b[^>]*>/gm, function(match, tag) { + // for anchor tags remove all attributes except href + if (tag === 'a') { + let href = match.match(/href="([^"]*)"/); + if (! href) { + return match; + } + return ''; + } + + // allow styling on some tags + if ('|table|tr|td|th|thead|tbody|tfoot|'.includes('|' + tag + '|')) { + let style = match.match(/style="([^"]*)"/); + if (! style) { + return match; + } + return '<' + tag + ' style="' + style[1] + '">'; + } + + return '<' + tag + '>'; + }); + + event.data.dataValue = result; + }); + }); + + window.CKEDITOR.on('dialogDefinition', function(event) { + let dialogName = event.data.name; + let dialogDefinition = event.data.definition; + if (dialogName === 'link') { + let infoTab = dialogDefinition.getContents('info'); + + dialogDefinition.onLoad = function() { + let dialog = CKEDITOR.dialog.getCurrent(); + dialog.getContentElement('info', 'linkType').getElement().hide(); + dialog.getContentElement('info', 'protocol').getElement().hide(); + dialog.getContentElement('info', 'url').getElement().hide(); + }; + + infoTab.add({ + type: 'select', + id: 'linktype-selector', + label: 'Linktype', + 'default': '', + items: [ + [window.translations['page'], "page"], + ["URL", "url"] + ], + onChange: function(obj) { + let dialog = CKEDITOR.dialog.getCurrent(); + if (obj.data.value === 'page') { + dialog.getContentElement('info', 'page-selector').getElement().show(); + dialog.getContentElement('info', 'url-field').getElement().hide(); + } else { + dialog.getContentElement('info', 'page-selector').getElement().hide(); + dialog.getContentElement('info', 'url-field').getElement().show(); + dialog.getContentElement('info', 'url-field').setValue(''); + } + }, + setup: function(data) { + if (data.type === undefined) { + this.setValue('page'); + } else if (data.type === 'url' && data.url.url.startsWith('[page id=')) { + this.setValue('page'); + } else { + this.setValue(data.type); + } + } + }); + + infoTab.add({ + type: 'select', + id: 'page-selector', + label: window.translations['page'], + 'default': '', + items: window.pages, + onChange: function() { + let dialog = CKEDITOR.dialog.getCurrent(); + let page = '[page id=' + this.getValue() + ']'; + dialog.setValueOf('info', 'url', page); + dialog.setValueOf('info', 'protocol', ''); + }, + setup: function(dialog) { + this.allowOnChange = false; + let pageId = ''; + if (dialog.url) { + pageId = dialog.url.url.substr(9, dialog.url.url.length - 10); + } + this.setValue(pageId); + this.allowOnChange = true; + } + }); + + infoTab.add({ + type: 'text', + id: 'url-field', + label: 'URL', + 'default': '', + onChange: function() { + let dialog = CKEDITOR.dialog.getCurrent(); + let url = this.getValue(); + dialog.setValueOf('info', 'url', url); + }, + setup: function(dialog) { + this.allowOnChange = false; + let url = ''; + if (dialog.url) { + url = dialog.url.url; + } + this.setValue(url); + this.allowOnChange = true; + } + }); + } + }); + +}); diff --git a/src/Modules/GrapesJS/resources/assets/js/manage-editable-components.js b/src/Modules/GrapesJS/resources/assets/js/manage-editable-components.js new file mode 100644 index 0000000..e05f8bb --- /dev/null +++ b/src/Modules/GrapesJS/resources/assets/js/manage-editable-components.js @@ -0,0 +1,833 @@ +(function() { + + /** + * After loading GrapesJS, add all theme blocks and activate the editable blocks in the main language. + */ + function afterGrapesJSLoaded() { + addThemeBlocks(); + + // add page injection script with page-loaded event to the end of the body tag of initialComponents, + // which contains the html structure of the used layout file. And add script that starts all external scripts + let scriptTag = document.createElement("script"); + scriptTag.type = "text/javascript"; + scriptTag.src = window.injectionScriptUrl; + let fullScript = scriptTag.outerHTML + ''; + window.initialComponents = window.initialComponents.replace('', fullScript + ''); + + $.each(window.languages, (languageCode, languageTranslation) => { + if (window.pageBlocks[languageCode] === null) { + window.pageBlocks[languageCode] = {}; + } + }); + + activateLanguage(window.currentLanguage); + } + + /** + * GrapesJS wraps each external script with a start[number]Start() method, + * which needs to be called on switching language. + */ + function startFirstScript() { + let scriptTags = document.querySelectorAll("script"); + for (let i = 0; i < scriptTags.length; i++) { + let node = scriptTags[i]; + if (node.innerHTML.startsWith('var script')) { + let beforeEquals = node.innerHTML.split('=')[0]; + let scriptNumber = parseInt(beforeEquals.replace('var script', '')); + if (Number.isInteger(scriptNumber)) { + let startScriptMethodName = 'script' + scriptNumber + 'Start'; + if (typeof window[startScriptMethodName] === 'function') { + if (scriptNumber !== 0) { + window[startScriptMethodName](); + } + return false; + } + } + } + } + } + + /** + * Add all theme blocks to GrapesJS blocks manager. + */ + function addThemeBlocks() { + for (let blockSlug in window.themeBlocks) { + let block = window.themeBlocks[blockSlug]; + + // remove whitespace from phpb-block-container elements, otherwise these components will become type=text, + // resulting in components dropped inside the container jumping to the dropped position - 1 + let $blockHtml = $("").append(block.content); + $blockHtml.find("[phpb-blocks-container]").each(function() { + if ($(this).html() !== '' && $(this).html().trim() === '') { + $(this).html(''); + } + }); + window.themeBlocks[blockSlug].content = $blockHtml.html(); + block.content = $blockHtml.html(); + + editor.BlockManager.add(blockSlug, block); + } + } + + /** + * Switch pagebuilder to another language variant on changing the language selector. + */ + $("#language-selector select").on("change", function() { + let selectedLanguage = $(this).find("option:selected").val(); + + window.switchLanguage(selectedLanguage, function() { + activateLanguage(selectedLanguage); + }); + }); + + /** + * Activate the given language variant in the pagebuilder. + * + * @param newLanguage + */ + window.activateLanguage = function(newLanguage) { + window.currentLanguage = newLanguage; + + // reset GrapesJS editor before loading the new language variant + window.editor.select(); + window.editor.DomComponents.clear(); + window.editor.DomComponents.componentsById = []; + window.editor.UndoManager.clear(); + + // remove any script tags from previous languages + window.editor.Canvas.getDocument().querySelectorAll("script").forEach(function(node) { + node.remove(); + }); + + // load initial non-editable layout components + window.editor.setComponents(window.initialComponents); + denyAccessToLayoutElements(editor.getWrapper()); + window.editor.getWrapper().find("[phpb-content-container]").forEach((container, index) => { + container.set('custom-name', window.translations['page-content']); + + // reload components of this content container (adding all root phpb-block elements) + container.components(window.contentContainerComponents[index]); + + // replace phpb-block elements with the server-side rendered version of each block + replacePlaceholdersForRenderedBlocks(container); + + // apply the stored block settings to the server-side rendered html + applyBlockAttributesToComponents(container); + }); + }; + + $(window).on('pagebuilder-page-loaded', function(event) { + window.editor.getWrapper().find("[phpb-content-container]").forEach(container => { + restrictEditAccess(container); + window.runScriptsOfComponentAndChildren(container); + }); + window.setWaiting(false); + + setTimeout(function() { + window.changesOffset = window.editor.getModel().get('changesCount'); + window.afterInitialRendering = true; + }, 250); + }); + + /** + * Replace phpb-block elements with the server-side rendered version of each block. + * + * @param component + */ + function replacePlaceholdersForRenderedBlocks(component) { + let newComponent = component; + + // if we encounter a pagebuilder block, replace it with the server-side rendered html + if (component.get('tagName') === 'phpb-block') { + let id = component.attributes.attributes.id; + if (window.pageBlocks[window.currentLanguage][id] !== undefined && window.pageBlocks[window.currentLanguage][id]['html'] !== undefined) { + newComponent = component.replaceWith(window.pageBlocks[window.currentLanguage][id]['html']); + window.pageBlocks[window.currentLanguage][id]['html'] = ''; + } + } + + // replace placeholders inside child components + newComponent.get('components').each(childComponent => replacePlaceholdersForRenderedBlocks(childComponent)); + } + + /** + * Function for denying edit access to this component and all children that belong to the layout. + * + * @param component + */ + function denyAccessToLayoutElements(component) { + if ('phpb-content-container' in component.attributes.attributes) return; + + disableAllEditFunctionality(component); + + // apply restrictions to child components + component.get('components').each(component => denyAccessToLayoutElements(component)); + } + + + /** + * Component select handler. + */ + window.editor.on('component:selected', function(component) { + // if the component has settings, activate settings panel in pagebuilder sidebar + if (componentHasBlockSettings(component)) { + $(".gjs-pn-buttons .gjs-pn-btn:nth-of-type(2)").click(); + } + else if (component.get('type') === '' && componentHasBackground(component)) { + // on selecting a default component without settings, with editable background, show background styling + $(".gjs-pn-buttons .gjs-pn-btn:nth-of-type(3)").click(); + if ($("#gjs-sm-position").hasClass("gjs-sm-open")) { + $("#gjs-sm-position").find(".gjs-sm-title").click(); + } + if (! $("#gjs-sm-background").hasClass("gjs-sm-open")) { + $("#gjs-sm-background").find(".gjs-sm-title").click(); + } + } + + // if component has no settings, add no settings text to settings panel in sidebar + if (! componentHasBlockSettings(component)) { + setTimeout(function() { + $(".gjs-trt-traits").html('

' + window.translations['trait-manager']['no-settings'] + '

'); + }, 0); + } + + // only show the toolbar buttons that are applicable + setTimeout(function() { + if (! component.attributes.removable) { + $(".gjs-toolbar .fa-trash-o.gjs-toolbar-item").hide(); + } + if (! component.attributes.copyable) { + $(".gjs-toolbar .fa-clone.gjs-toolbar-item").hide(); + } + if (! component.attributes.draggable) { + $(".gjs-toolbar .fa-arrows.gjs-toolbar-item").hide(); + } + if (! component.attributes.removable && ! component.attributes.copyable && ! component.attributes.draggable) { + window.editor.select(component.parent()); + } + + let blockSlug = component.attributes['block-slug']; + if (blockSlug) { + let labelHtml = window.themeBlocks[blockSlug]['label']; + let labelTextParts = labelHtml.split(""); + if (labelTextParts.length > 1) { + $(".gjs-toolbar").attr('title', "Bloknaam: " + labelTextParts[1]); + } + } + }, 0); + }); + + + /** + * Component clone handler. + */ + window.editor.on('component:clone', function(component) { + // if the clone is performed by the user, do not copy the block id and style identifier + if (! isCloningFromScript) { + let originalComponent = window.editor.getWrapper().find('.' + component.attributes['style-identifier'])[0]; + + if (component.attributes['style-identifier'] !== undefined && component.attributes['style-identifier'] !== '') { + component.removeClass(component.attributes['style-identifier']); + delete component.attributes['style-identifier']; + addUniqueClass(component); + } + component.attributes['block-id'] = component.attributes['block-slug']; + + // pass a reference of the scripts of the original component to run on the cloned component + if (originalComponent && window.customBuilderScripts[originalComponent.attributes['block-id']] !== undefined) { + component.attributes['run-builder-script'] = originalComponent.attributes['block-id']; + } + } + }); + + + /** + * Return whether the given component contains a CSS background, that should be editable. + * + * @param component + * @returns {boolean} + */ + function componentHasBackground(component) { + let hasBackground = false; + + let componentElement = component.getEl(); + if (componentElement && componentElement.style) { + let componentStyle = window.getComputedStyle(componentElement); + + ['background', 'background-image', 'background-color'].forEach(property => { + let value = componentStyle.getPropertyValue(property); + if (value !== undefined && value !== '' && ! value.includes('none') && ! value.includes('rgba(0, 0, 0, 0)')) { + hasBackground = true; + } + }); + } + + return hasBackground; + } + + /** + * Return whether the given component has settings defined in its block config file. + * + * @param component + * @returns {boolean} + */ + function componentHasBlockSettings(component) { + return component.attributes.traits.length > 0; + } + + /** + * On dropping a component on the canvas, apply attributes of the container phpb-block element with configuration passed + * from the server and restrict edit access to editable components. + */ + window.editor.on('block:drag:stop', function(droppedComponent) { + // ensure component drop was successful + if (! droppedComponent || ! droppedComponent.attributes || ! droppedComponent.attributes.attributes) return; + + let draggedBlockId = generateId(); + droppedComponent.attributes.attributes['dropped-component-id'] = draggedBlockId; + + let parent = droppedComponent.parent(); + applyBlockAttributesToComponents(droppedComponent); + + // at this point droppedComponent is replaced in the DOM by the actual component (without the phpb-block element), + // so we need to find the dropped component again in the context of its parent + parent.components().each(function(child) { + if (child.attributes['dropped-component-id'] === draggedBlockId) { + delete child.attributes['dropped-component-id']; + droppedComponent = child; + } + }); + restrictEditAccess(droppedComponent); + + window.runScriptsOfComponentAndChildren(droppedComponent); + }); + + /** + * Apply the block attributes which are stored in elements to the top-level html element inside the block. + * If the block starts with multiple top-level html elements, add a div element wrapping the block's top-level elements. + * + * @param component + */ + function applyBlockAttributesToComponents(component) { + if (component.attributes.tagName === 'phpb-block') { + let container = component.parent(); + let clone = cloneComponent(component); + + // since component is a that should be removed and replaced by its children, + // the component's parent's child that has the id of the component needs to be replaced + let blockRootComponent; + if (component.attributes.attributes['is-html'] === 'false') { + container.components().each(function(componentSibling) { + if (componentSibling.cid === component.cid) { + // replace the by the actual component + // the component is wrapped with a wrapper element to allow block styling (via a unique .style-identifier selector) + let wrapperElement = ('wrapper' in component.attributes.attributes) ? component.attributes.attributes['wrapper'] : 'div'; + blockRootComponent = component.replaceWith({tagName: wrapperElement}); + blockRootComponent.attributes['is-style-wrapper'] = true; + clone.components().each(function(componentChild) { + blockRootComponent.append(cloneComponent(componentChild)); + }); + } + }); + } else { + container.components().each(function(componentSibling) { + if (componentSibling.cid === component.cid) { + // if the has one direct child, replace it by its only child + // else, replace it by a wrapper div to allow block styling (via a unique .style-identifier selector) + if (clone.components().length === 1) { + let firstChild = cloneComponent(clone.components().models[0]); + blockRootComponent = component.replaceWith(firstChild); + } else { + blockRootComponent = component.replaceWith({tagName: 'div'}); + blockRootComponent.attributes['is-style-wrapper'] = true; + clone.components().each(function(componentChild) { + blockRootComponent.append(cloneComponent(componentChild)); + }); + } + } + }); + } + component.remove(); + + copyAttributes(clone, blockRootComponent, true, false); + // add all settings of this component to the settings panel in the sidebar + addSettingsToSidebar(blockRootComponent); + // recursive call to find and replace elements of nested blocks (loaded via shortcodes) + applyBlockAttributesToComponents(blockRootComponent); + } else { + component.components().each(function(childComponent) { + // recursive call to find and replace elements of nested blocks (loaded via shortcodes) + applyBlockAttributesToComponents(childComponent); + }); + } + } + + /** + * Get the current setting values for the given component. + * + * @param component + */ + function getCurrentSettingValues(component) { + // Block settings are stored in window.pageBlocks in a structure starting with each root block (the first ancestor that does not have a dynamic parent itself). + // So, we need to find the root of the given component and store all block ids along the way, in order to traverse the pageBlocks structure to the settings of the given component. + // These block ids are only unique in the context of their parent (we can have multiple instances of the same nested block structure), so we call them relative IDs. + let relativeIds = []; + + // get the root component of the given component (its first ancestor that does not have a dynamic parent itself or the block that is inside a blocks container) + let rootComponent = component; + let hasDynamicAncestor = false; + while (rootComponent.parent() && + rootComponent.parent().attributes.attributes['phpb-blocks-container'] === undefined && + rootComponent.parent().attributes['is-html'] !== 'true' && + rootComponent.parent().attributes.attributes['phpb-content-container'] === undefined + ) { + if (rootComponent.parent().attributes['is-html'] === 'false') { + hasDynamicAncestor = true; + } + if (rootComponent.attributes['block-id'] !== undefined) { + relativeIds.push(rootComponent.attributes['block-id']); + } + rootComponent = rootComponent.parent(); + } + + let rootId = component.attributes['block-id']; + if (hasDynamicAncestor) { + rootId = rootComponent.attributes['block-id']; + } else { + relativeIds = []; + } + + // get the component settings by traversing the pageBlocks structure + let settings = window.pageBlocks[window.currentLanguage][rootId]; + relativeIds.reverse().forEach(function(relativeId) { + if (settings === undefined || settings.blocks === undefined || settings.blocks[relativeId] === undefined) { + settings = {}; + } else { + settings = settings.blocks[relativeId]; + } + }); + + // return the values stored in the current component's settings structure + let settingsValues = {}; + if (settings !== undefined && settings.settings !== undefined && settings.settings.attributes !== undefined) { + settingsValues = settings.settings.attributes; + } + return settingsValues; + } + + /** + * Add all settings from the block's config file to the given component, + * to allow them to be changed in the settings side panel. + * + * @param component + */ + function addSettingsToSidebar(component) { + if (window.blockSettings[component.attributes['block-slug']] === undefined) { + return; + } + component.attributes.settings = {}; + + let settingValues = getCurrentSettingValues(component); + + // set style identifier class to the block wrapper, if an identifier has been stored during earlier getDataInStorageFormat calls + if (settingValues['style-identifier'] !== undefined) { + component.addClass(settingValues['style-identifier']); + } + + // for each setting add a trait to the settings sidebar panel with the earlier stored or default value + component.attributes['is-updating'] = true; + let settings = window.blockSettings[component.attributes['block-slug']]; + settings.forEach(function(setting) { + let trait = component.addTrait(setting); + if (settingValues[setting['name']] !== undefined) { + trait.setTargetValue(settingValues[setting['name']]); + } else if (setting['default-value'] !== undefined) { + trait.setTargetValue(setting['default-value']); + } + }); + component.attributes['is-updating'] = false; + } + + /** + * On updating an attribute (block setting from the settings side panel), refresh dynamic block via Ajax. + */ + window.editor.on('component:update', function(component) { + if (window.isLoaded !== true || + component.attributes['block-slug'] === undefined || + component.attributes['is-updating'] || + component.changed['attributes'] === undefined || + $(".gjs-frame").contents().find("#" + component.ccid).length === 0 + ) { + return; + } + + // dynamic pagebuilder blocks can depend on data passed by dynamic parent blocks, + // so we need to update the closest parent which does not have a dynamic parent itself or the block that is inside a blocks container. + // also keep track of all intermediate block ids, for re-selecting the currently selected component. + let relativeIds = []; + let ancestorToUpdate = component; + let hasDynamicAncestor = false; + while (ancestorToUpdate.parent() && + ancestorToUpdate.parent().attributes.attributes['phpb-blocks-container'] === undefined && + ancestorToUpdate.parent().attributes['is-html'] !== 'true' && + ancestorToUpdate.parent().attributes.attributes['phpb-content-container'] === undefined + ) { + if (ancestorToUpdate.parent().attributes['is-html'] === 'false') { + hasDynamicAncestor = true; + } + if (ancestorToUpdate.attributes['block-id'] !== undefined) { + relativeIds.push(ancestorToUpdate.attributes['block-id']); + } + ancestorToUpdate = ancestorToUpdate.parent(); + } + + if (hasDynamicAncestor) { + component = ancestorToUpdate; + } else { + relativeIds = []; + } + + component.attributes['is-updating'] = true; + $(".gjs-frame").contents().find("#" + component.ccid).addClass('gjs-freezed'); + + let container = window.editor.getWrapper().find("#" + component.ccid)[0].parent(); + let data = window.getComponentDataInStorageFormat(component); + + // refresh component contents with updated version requested via ajax call + $.ajax({ + type: "POST", + url: window.renderBlockUrl, + data: { + data: JSON.stringify(data), + language: window.currentLanguage + }, + success: function(blockHtml) { + let blockId = $(blockHtml).attr('block-id'); + + // set the block settings for the updated component to the new values + window.pageBlocks[window.currentLanguage][blockId] = (data.blocks[blockId] === undefined) ? {} : data.blocks[blockId]; + + // replace old component for the rendered html returned by the server + component.replaceWith(blockHtml); + replacePlaceholdersForRenderedBlocks(container); + applyBlockAttributesToComponents(container); + restrictEditAccess(container, false, false); + + // run builder scripts of the replaced component and all its children + let replacedComponent = findChildViaBlockIdsPath(container, [blockId]); + runScriptsOfComponentAndChildren(replacedComponent); + + // select the component that was selected before the ajax call + relativeIds.push(blockId); + let componentToSelect = findChildViaBlockIdsPath(container, relativeIds.reverse()); + window.editor.select(componentToSelect); + }, + error: function() { + $(".gjs-frame").contents().find("#" + component.ccid).removeClass('gjs-freezed'); + component.attributes['is-updating'] = false; + window.toastr.error(window.translations['toastr-component-update-failed']); + } + }); + }); + + /** + * Traverse the children of the given component via the given path of block IDs + * and return the component with the last ID from the list. + * + * @param component + * @param blockIds + * @returns {null|*} + */ + function findChildViaBlockIdsPath(component, blockIds) { + if (blockIds.length === 0) { + return component; + } + + let result = null; + + component.components().each(function(child) { + if (child.attributes['block-id'] === blockIds[0]) { + result = findChildViaBlockIdsPath(child, blockIds.slice(1)); + return false; + } + }); + + component.components().each(function(child) { + let childResult = findChildViaBlockIdsPath(child, blockIds); + if (childResult !== null) { + result = childResult; + return false; + } + }); + + return result; + } + + /** + * Clone the given component (while preserving all attributes, like IDs). + * + * @param component + */ + let isCloningFromScript = false; + window.cloneComponent = function(component) { + isCloningFromScript = true; + + let clone = component.clone(); + deepCopyAttributes(component, clone); + + isCloningFromScript = false; + return clone; + }; + + /** + * Apply the attributes of the given component and its children to each corresponding component of the given clone. + * + * @param component + * @param clone + */ + function deepCopyAttributes(component, clone) { + // apply all attributes from component to clone + copyAttributes(component, clone, false, true); + // apply attributes from component's children to clone's children + for (let index = 0; index < component.components().length; index++) { + let componentChild = component.components().models[index]; + let cloneChild = clone.components().models[index]; + deepCopyAttributes(componentChild, cloneChild); + } + } + + /** + * Apply the attributes of the given component to the given target component. + * + * @param component + * @param targetComponent + * @param copyGrapesAttributes whether all GrapesJS component attributes (like permissions) should be copied + * @param copyHtmlElementAttributes whether the html element attributes should be copied + */ + function copyAttributes(component, targetComponent, copyGrapesAttributes, copyHtmlElementAttributes) { + let componentAttributes = component.attributes.attributes; + for (let attribute in componentAttributes) { + if (copyHtmlElementAttributes) { + targetComponent.attributes.attributes[attribute] = componentAttributes[attribute]; + } + if (copyGrapesAttributes) { + targetComponent.attributes[attribute] = componentAttributes[attribute]; + } + } + } + + /** + * Function for only allowing edit access on whitelisted components. + * + * @param component + * @param directlyInsideDynamicBlock + * @param allowEditableComponents + */ + function restrictEditAccess(component, directlyInsideDynamicBlock = false, allowEditableComponents = true) { + disableAllEditFunctionality(component); + + if (component.attributes.attributes['phpb-content-container'] !== undefined) { + // the content container of the current page can receive other components + component.set({ + droppable: true, + hoverable: true, + }); + } else if (component.attributes['block-slug'] !== undefined) { + // change visibility of child elements that depend on whether this block is editable + component.find('[phpb-hide-if-not-editable]').forEach((element) => { + if (allowEditableComponents || window.afterInitialRendering) { + element.addClass('editable'); + } else { + element.removeClass('editable'); + } + }); + + // we just entered a new block, set default permissions + let permissions = { + selectable: true, + hoverable: true, + }; + if (! directlyInsideDynamicBlock) { + // the block we entered is not located directly inside a dynamic block, hence this block can be removed, dragged, configured and styled + permissions = { + removable: true, + draggable: true, + copyable: true, + selectable: true, + hoverable: true, + stylable: true, + }; + // for styling this particular block, the block needs to have a unique class + addUniqueClass(component); + } + if (component.attributes['is-html'] === 'true') { + // the block we just entered is an html block, + // the next layer of child blocks are not directly inside a dynamic block + directlyInsideDynamicBlock = false; + // in an html block, editing elements (based on their html tag) is allowed + allowEditableComponents = true; + } else { + // the block we just entered is dynamic, + // the next layer of child blocks are directly inside a dynamic block + directlyInsideDynamicBlock = true; + // in a dynamic block, editing elements (based on their html tag) is not allowed + allowEditableComponents = false; + // dynamic blocks do not have text-editable components, so remove text cursors + component.getEl().setAttribute('data-cursor', 'default'); + } + component.set(permissions); + } + + // for raw content components, set editable to true and ignore processing editability for any child component + if (component.attributes.attributes['data-raw-content'] !== undefined) { + component.set({editable: true}); + return; + } + + // set editable access based on tags, styling or html class attribute + if (allowEditableComponents) { + allowEditBasedOnComponentAttributes(component); + + // if the component is made text-editable, re-add the raw html contents + // to ensure the text editor does not deal with elements with attributes added by GrapesJS + if (component.attributes['made-text-editable'] === 'true') { + component.attributes.attributes['data-raw-content'] = 'true'; + + // refresh the current component in order to switch its component type to raw-content. + // this disables GrapesJS parsing of any child elements, avoiding that any GrapesJS specific html attributes are added + let newComponent = component.replaceWith(component.toHTML()); + // copy important attributes from the original component to the refreshed component + ['block-id', 'block-slug', 'is-html', 'style-identifier'].forEach(attribute => { + newComponent.attributes[attribute] = component.attributes[attribute]; + }); + // apply block/component edit restrictions to the new raw-content type version of the component + restrictEditAccess(newComponent); + return; + } + } + + // apply edit restrictions to child components + component.get('components').each(component => restrictEditAccess(component, directlyInsideDynamicBlock, allowEditableComponents)); + } + + /** + * Set the given component's editability based on which tag the component represents, + * which attributes are set or which styling is applied. + * + * @param component + * @returns {boolean} + */ + function allowEditBasedOnComponentAttributes(component) { + let htmlTag = component.get('tagName'); + + let textEditableTags = [ + //'div','span', // needed for editable bootstrap alert, but cannot be used since divs (block containers) then cannot be removed + 'h1','h2','h3','h4','h5','h6','h7', + 'p','small','b','strong','i','em','label','button', + 'ol', 'ul','li','table' + ]; + let otherEditableTags = [ + 'img' + ]; + + let settings = {}; + if ('phpb-blocks-container' in component.attributes.attributes) { + settings.hoverable = true; + settings.selectable = true; + settings.droppable = true; + } + + if (textEditableTags.includes(htmlTag) || 'phpb-editable' in component.attributes.attributes) { + settings.editable = true; + component.attributes['made-text-editable'] = 'true'; + } else if (otherEditableTags.includes(htmlTag)) { + settings.editable = true; + } + + if (componentHasBackground(component)) { + settings.hoverable = true; + settings.selectable = true; + settings.stylable = true; + } + + if (htmlTag === 'a') { + settings.hoverable = true; + settings.selectable = true; + settings.stylable = true; + settings.removable = true; + } + + if (! $.isEmptyObject(settings)) { + component.set(settings); + if (settings.stylable !== undefined && settings.stylable) { + addUniqueClass(component); + } + } + } + + /** + * Add a unique class to this component to ensure style only applies to this component instance. + * + * @param component + */ + function addUniqueClass(component) { + // get component identifier class if one is already added to the component's html when saving the pagebuilder previously + let componentIdentifier = false; + component.getClasses().forEach(componentClass => { + if (componentClass.startsWith('ID') && componentClass.length === 16) { + componentIdentifier = componentClass; + } + }); + + if (component.attributes['style-identifier'] === undefined) { + component.attributes['style-identifier'] = componentIdentifier ? componentIdentifier : generateId(); + } + component.addClass(component.attributes['style-identifier']); + } + + /** + * Disable all edit functionality on the given component. + * + * @param component + */ + function disableAllEditFunctionality(component) { + component.set({ + removable: false, + draggable: false, + droppable: false, + badgable: false, + stylable: false, + highlightable: false, + copyable: false, + resizable: false, + editable: false, + layerable: false, + selectable: false, + hoverable: false + }); + } + + /** + * Generate a unique id string. + * + * Based on: https://gist.github.com/gordonbrander/2230317 + */ + let counter = 0; + function generateId() { + return 'ID' + (Date.now().toString(36) + + Math.random().toString(36).substr(2, 5) + counter++).toUpperCase(); + } + + /** + * Wait for GrapesJS to be fully loaded before trying to load the components in the page builder. + */ + function waitForGrapesToLoad() { + if (window.grapesJSLoaded) { + afterGrapesJSLoaded(); + } else { + setTimeout(waitForGrapesToLoad, 100); + } + } + waitForGrapesToLoad(); + +})(); diff --git a/src/Modules/GrapesJS/resources/assets/js/page-injection.js b/src/Modules/GrapesJS/resources/assets/js/page-injection.js new file mode 100644 index 0000000..ba8f345 --- /dev/null +++ b/src/Modules/GrapesJS/resources/assets/js/page-injection.js @@ -0,0 +1,14 @@ +/* disable ctrl + s, since this is handled in iframe parent */ +window.addEventListener('keydown', function(e) { + if (e.ctrlKey && e.key === 's') { + e.preventDefault(); + return false; + } +}); + +/* post message to iframe parent that page has been loaded */ +window.parent.postMessage("page-loaded", '*'); + +document.addEventListener('touchstart', e => { + window.parent.postMessage("touch-start", '*'); +}); diff --git a/src/Modules/GrapesJS/resources/assets/js/pagebuilder.js b/src/Modules/GrapesJS/resources/assets/js/pagebuilder.js new file mode 100644 index 0000000..ef5e799 --- /dev/null +++ b/src/Modules/GrapesJS/resources/assets/js/pagebuilder.js @@ -0,0 +1,87 @@ +$(document).ready(function() { + + $(".gjs-editor").append($("#toggle-sidebar")); + $(".gjs-pn-panels").prepend($("#sidebar-header")); + $(".gjs-pn-panels").append($("#sidebar-bottom-buttons")); + + $("#toggle-sidebar").click(function() { + $("#gjs").toggleClass('sidebar-collapsed'); + triggerEditorResize(); + }); + autoCollapseSidebar(); + + window.editor.on('run:open-sm', function(editor) { + $(".gjs-trt-traits").parent().parent().css('display', 'none'); + $(".gjs-sm-sectors").parent().parent().css('display', 'block'); + // move element classes editor to advanced section + $("#gjs-sm-advanced .gjs-sm-properties").append($(".gjs-clm-tags")); + }); + window.editor.on('run:open-tm', function(editor) { + $(".gjs-sm-sectors").parent().parent().css('display', 'none'); + $(".gjs-trt-traits").parent().parent().css('display', 'block'); + }); + + window.editor.on('block:drag:start', function(block) { + autoCollapseSidebar(); + }); + + window.editor.on('rteToolbarPosUpdate', function(toolbarPosition) { + if (! window.editor || ! window.editor.getSelected()) return; + let selectedDomComponent = window.editor.getSelected().getEl(); + if (! selectedDomComponent) return; + + setTimeout(function() { + let $toolbar = $(".gjs-rte-toolbar").first(); + let toolbarInUpperHalf = $toolbar.offset().top < (toolbarPosition.elementTop + (0.5 * toolbarPosition.elementHeight)); + if (toolbarInUpperHalf) { + let newTop = toolbarPosition.elementTop - $toolbar.height(); + if (newTop > 0) { + $toolbar.css('top', newTop + 'px'); + } else { + //$toolbar.css('top', (toolbarPosition.elementTop + toolbarPosition.elementHeight) + 'px'); + } + } + }, 0); + }); + + function autoCollapseSidebar() { + if ($(window).width() < 1000) { + $("#gjs").addClass('sidebar-collapsed'); + triggerEditorResize(); + } + } + + function triggerEditorResize() { + window.editor.trigger('change:canvasOffset canvasScroll'); + } + + // prevent exiting page builder with backspace button + let backspaceIsPressed = false; + $(document).keydown(function(event) { + if (event.which === 8) backspaceIsPressed = true; + }).keyup(function(event) { + if (event.which === 8) backspaceIsPressed = false; + }); + $(window).on('beforeunload', function(event) { + if (backspaceIsPressed) event.preventDefault(); + }); +}); + +function addBlockSearch() { + $(".gjs-blocks-cs").prepend($("#block-search")); +} + +// listen to messages from iframe +window.addEventListener("message", onMessage, false); + +function onMessage(event) { + // if the page is loaded, remove loading element + if (event.data === 'page-loaded') { + $("#phpb-loading").addClass('loaded'); + addBlockSearch(); + window.isLoaded = true; + $(window).trigger('pagebuilder-page-loaded'); + } else if(event.data === 'touch-start') { + window.touchStart(); + } +} diff --git a/src/Modules/GrapesJS/resources/assets/js/responsive.js b/src/Modules/GrapesJS/resources/assets/js/responsive.js new file mode 100644 index 0000000..249cb0e --- /dev/null +++ b/src/Modules/GrapesJS/resources/assets/js/responsive.js @@ -0,0 +1,7 @@ +$(document).ready(function() { + + window.touchStart = function() { + $("#gjs").addClass('sidebar-collapsed'); + } + +}); \ No newline at end of file diff --git a/src/Modules/GrapesJS/resources/assets/js/run-builder-scripts.js b/src/Modules/GrapesJS/resources/assets/js/run-builder-scripts.js new file mode 100644 index 0000000..d1ebb1d --- /dev/null +++ b/src/Modules/GrapesJS/resources/assets/js/run-builder-scripts.js @@ -0,0 +1,107 @@ +(function() { + + window.customBuilderScripts = {}; + + /** + * On instantiating the component model, before it is mounted in the canvas. + */ + window.editor.on('component:create', component => { + // extract the script tag of the given component (if it has one) + if (component.components().length) { + let lastChild = component.components().models[component.components().length - 1]; + if (lastChild.attributes.type === 'script') { + let blockId = component.attributes.attributes['block-id']; + if (blockId === undefined) { + blockId = component.attributes.attributes['id']; + } + + let rootComponent = lastChild; + let insideEditablePartOfPage = false; + while (rootComponent.parent()) { + rootComponent = rootComponent.parent(); + if (rootComponent.attributes.attributes['phpb-content-container']) { + insideEditablePartOfPage = true; + break; + } + } + + if (insideEditablePartOfPage) { + window.customBuilderScripts[blockId] = lastChild.toHTML(); + lastChild.remove(); + } + } + } + }); + + /** + * After mounting the component in the canvas. + */ + window.editor.on('component:add', function (component) { + // run the script that was set when creating this component + if (component.attributes['run-builder-script'] !== undefined) { + let originalCustomBuilderScripts = customBuilderScripts; + + window.customBuilderScripts[component.attributes['block-id']] = customBuilderScripts[component.attributes['run-builder-script']]; + runScriptsOfComponentAndChildren(component); + + window.customBuilderScripts = originalCustomBuilderScripts; + delete component.attributes['run-builder-script']; + } + }); + + /** + * On ending a component order drag, re-run builder scripts on newly added HTMl. + */ + window.editor.on('sorter:drag:end', function(event) { + let component = event.modelToDrop; + if (component && component.attributes && (component.attributes['block-id'] || component.attributes['id'])) { + window.runScriptsOfComponentAndChildren(component); + } + // remove all existing CKEditors after dragging a block with active editor + for (let instanceName in CKEDITOR.instances) { + CKEDITOR.instances[instanceName].destroy(true); + } + }); + + /** + * Run the custom builder scripts of the given component and of all child components. + * + * @param component + */ + window.runScriptsOfComponentAndChildren = function(component) { + runComponentScript(component); + component.components().each(function(child) { + runScriptsOfComponentAndChildren(child); + }); + } + + /** + * Run the custom builder scripts of the given component. + * + * @param component + */ + function runComponentScript(component) { + let blockId = component.attributes['block-id']; + if (blockId === undefined) { + blockId = component.attributes.attributes['id']; + } + if (blockId && window.customBuilderScripts[blockId] !== undefined) { + let styleIdentifier = component.attributes["style-identifier"]; + let $scriptTag = $("").append(window.customBuilderScripts[blockId]); + // prepend block and blockSelector variables allowing the script to refer to this exact block instance + $scriptTag.find('script').prepend('let inPageBuilder = true;'); + $scriptTag.find('script').prepend('let blockSelector = ".' + styleIdentifier + '";'); + $scriptTag.find('script').prepend('let block = document.getElementsByClassName("' + styleIdentifier + '")[0];'); + // wrap the script contents in a self-invoking function (to add a scope avoiding variable name collisions) + $scriptTag.find('script').prepend('(function(){'); + $scriptTag.find('script').append('})();'); + + // execute the script in the page that is being edited + let scriptTag = document.createElement("script"); + scriptTag.type = "text/javascript"; + scriptTag.innerHTML = $scriptTag.find('script').html(); + window.editor.Canvas.getDocument().body.appendChild(scriptTag); + } + } + +})(); diff --git a/src/Modules/GrapesJS/resources/assets/js/save-page.js b/src/Modules/GrapesJS/resources/assets/js/save-page.js new file mode 100644 index 0000000..97d3dfd --- /dev/null +++ b/src/Modules/GrapesJS/resources/assets/js/save-page.js @@ -0,0 +1,484 @@ +$(document).ready(function() { + + window.pageData = {}; + + window.changesOffset = 0; + window.onbeforeunload = confirmExit; + function confirmExit() { + let changesCount = window.editor.getModel().get('changesCount') - window.changesOffset; + if (changesCount > 0) { + return "Are you sure? There are unsaved changes."; + } + } + + /** + * Save page on clicking save button. + */ + $("#save-page").click(function() { + saveAllTranslationsToServer(); + }); + + /** + * Save page on Ctrl + S. + */ + $(document).bind("keydown", function(e){ + if(e.ctrlKey && e.which === 83) { + // text-editor updates are not applied until focus is lost, so force GrapesJS update + window.editor.store(); + + saveAllTranslationsToServer(); + e.preventDefault(); + return false; + } + }); + + /** + * Switch the pagebuilder to the given language. + * This stores the all data of the current language locally for later use and renders the given language variant on the server. + * + * @param newLanguage + * @param callback + */ + window.switchLanguage = function(newLanguage, callback) { + window.setWaiting(true); + + saveCurrentTranslationLocally(function() { + applyChangesFromCurrentLanguageToNewLanguage(newLanguage); + + let data = window.pageData; + data.blocks = {[newLanguage]: window.pageBlocks[newLanguage]}; + + // render the language variant server-side + $.ajax({ + type: "POST", + url: window.renderLanguageVariantUrl, + data: { + data: JSON.stringify(data), + language: newLanguage + }, + success: function(response) { + response = JSON.parse(response); + window.pageBlocks[newLanguage] = response.dynamicBlocks ? response.dynamicBlocks : {}; + callback(); + }, + error: function(error) { + callback(); + console.log(error); + let errorMessage = error.statusText + ' ' + error.status; + errorMessage = error.responseJSON.message ? (errorMessage + ': "' + error.responseJSON.message + '"') : errorMessage; + window.toastr.error(errorMessage); + window.toastr.error(window.translations['toastr-switching-language-failed']); + } + }); + }); + }; + + /** + * Copy new blocks of the current language to the new language or remove old blocks from the new language. + * + * @param newLanguage + */ + function applyChangesFromCurrentLanguageToNewLanguage(newLanguage) { + let newLanguageBlocks = window.pageBlocks[newLanguage]; + let currentLanguageBlocks = window.pageBlocks[window.currentLanguage]; + + if (newLanguageBlocks === undefined) { + newLanguageBlocks = currentLanguageBlocks; + } else { + updateNestedBlocks(currentLanguageBlocks, newLanguageBlocks); + + // copy missing blocks from the current language to the target language + for (let blockId in currentLanguageBlocks) { + if (newLanguageBlocks[blockId] === undefined) { + newLanguageBlocks[blockId] = currentLanguageBlocks[blockId]; + } + } + } + + // copy the content of blocks containers of the current language to the blocks containers of the new language + for (let blockId in currentLanguageBlocks) { + let $currentLanguageBlockHtmlDom = $("" + currentLanguageBlocks[blockId]['html'] + ""); + let $newLanguageBlockHtmlDom = $("" + newLanguageBlocks[blockId]['html'] + ""); + $currentLanguageBlockHtmlDom.find("[phpb-blocks-container]").each(function(index) { + let currentLanguageBlockContainerHtml = $(this).html(); + $newLanguageBlockHtmlDom.find("[phpb-blocks-container]").eq(index).html(currentLanguageBlockContainerHtml); + }); + newLanguageBlocks[blockId]['html'] = $newLanguageBlockHtmlDom.html(); + } + + window.pageBlocks[newLanguage] = newLanguageBlocks; + } + + /** + * Replace phpb-blocks-container html snippets if a block of the current language already exists in the target language. + * This ensures all child blocks are present for all languages and they remain in the same order + */ + function updateNestedBlocks(currentLanguageBlocks, newLanguageBlocks) { + for (let blockId in currentLanguageBlocks) { + // skip if the parent block does not yet exist in the target language + if (newLanguageBlocks[blockId] === undefined) { + continue; + } + + for (let subBlockId in currentLanguageBlocks[blockId].blocks) { + let updatedSubBlock = currentLanguageBlocks[blockId].blocks[subBlockId]; + let oldSubBlock = newLanguageBlocks[blockId].blocks[subBlockId]; + if (! updatedSubBlock || ! oldSubBlock) { + continue; + } + + let updatedSubBlockMatches = updatedSubBlock.html.match(/phpb-blocks-container(.*)>(.*)(.*) { + let data = getContainerContentInStorageFormat(container); + + window.pageData['css'] = data.css; + window.pageData['style'] = data.style; + window.pageData['html'][index] = data.html; + window.pageData['components'][index] = data.components; + + window.pageBlocks[window.currentLanguage] = {...window.pageBlocks[window.currentLanguage], ...data.blocks}; + window.contentContainerComponents[index] = data.components; + }); + + if (callback) { + callback(); + } + }, 200); + } + + /** + * Save the data of all translation variants on the server. + */ + function saveAllTranslationsToServer() { + toggleSaving(); + + saveCurrentTranslationLocally(function() { + + // update all language variants with the latest data of the current language we just saved locally + $.each(window.languages, (languageCode, languageTranslation) => { + if (languageCode !== window.currentLanguage) { + applyChangesFromCurrentLanguageToNewLanguage(languageCode); + } + }); + + let data = window.pageData; + data.style = removeOldStyleSelectors(data.css, data.style); + data.blocks = window.pageBlocks; + + $.ajax({ + type: "POST", + url: $("#save-page").data('url'), + data: { + data: JSON.stringify(data) + }, + success: function() { + toggleSaving(); + window.toastr.success(window.translations['toastr-changes-saved']); + + setTimeout(function() { + window.changesOffset = window.editor.getModel().get('changesCount'); + }, 250); + }, + error: function(error) { + toggleSaving(); + console.log(error); + let errorMessage = error.statusText + ' ' + error.status; + errorMessage = error.responseJSON.message ? (errorMessage + ': "' + error.responseJSON.message + '"') : errorMessage; + window.toastr.error(errorMessage); + window.toastr.error(window.translations['toastr-saving-failed']); + } + }); + }); + } + + /** + * Remove the style selectors that are not present in the given CSS string. + */ + function removeOldStyleSelectors(css, styleComponents) { + let updatedStyleComponents = []; + + styleComponents.forEach(styleComponent => { + if (styleComponent.attributes.selectors.models.length) { + let selector = styleComponent.attributes.selectors.models[0].id; + if (css.includes(selector)) { + updatedStyleComponents.push(styleComponent); + } + } + }); + + return updatedStyleComponents; + } + + /** + * Get the given component in storage format (in context of its container with all siblings removed). + * + * @param component + */ + window.getComponentDataInStorageFormat = function(component) { + // clone component's parent, enabling us to temporarily remove all component's siblings without updating the pagebuilder + let container = window.cloneComponent(component.parent()); + + // remove all component's siblings since we only want to return the given component in storage format + container.get('components').reset(); + container.append(component); + + return getContainerContentInStorageFormat(container); + }; + + /** + * Get the given container in storage format. + * + * @param container + */ + function getContainerContentInStorageFormat(container) { + // remove all existing references while cloning GrapesJS components, + // this prevents GrapesJS from changing our IDs due to ID collisions + let componentReferences = window.editor.DomComponents.componentsById; + window.editor.DomComponents.componentsById = []; + + // we need to clone the container, since we will be replacing components with placeholders and we don't want to update the page builder + container = window.cloneComponent(container); + // replace each pagebuilder block for a shortcode and phpb-block element and return an array of all page blocks data + let blocksData = replaceDynamicBlocksWithPlaceholders(container).blocks; + + let html = window.html_beautify(getContainerHtml(container)); + let css = window.editor.getCss(); + let style = window.editor.getStyle(); + let components = JSON.parse(JSON.stringify(container.get('components'))); + + // switch back to original GrapesJS component references + window.editor.DomComponents.componentsById = componentReferences; + + return { + html: html, + css: css, + components: components, + blocks: blocksData, + style: style, + } + } + + /** + * Return the html representation of the contents of the given container. + * + * @param container + */ + function getContainerHtml(container) { + let html = ''; + container.get('components').forEach(component => html += component.toHTML()); + let htmlDom = $("" + html + ""); + // replace phpb-block elements with shortcode + htmlDom.find('phpb-block').each(function() { + $(this).replaceWith('[block slug="' + $(this).attr('slug') + '" id="' + $(this).attr('id') + '"]'); + }); + return htmlDom.html(); + } + + /** + * Return the html representation of the given component. + * + * @param component + */ + function getComponentHtml(component) { + let htmlDom = $("" + component.toHTML() + ""); + // replace phpb-block elements with shortcode + htmlDom.find('phpb-block').each(function() { + $(this).replaceWith('[block slug="' + $(this).attr('slug') + '" id="' + $(this).attr('id') + '"]'); + }); + return htmlDom.html(); + } + + /** + * Replace all blocks with is-html === false with a component that contains all block attributes. + * + * @param component + * @param parentIsDynamic + * @param parentIsHtmlInsideDynamic + */ + function replaceDynamicBlocksWithPlaceholders(component, parentIsDynamic = false, parentIsHtmlInsideDynamic = false) { + // data structure to be filled with the data of nested blocks via recursive calls + let data = { + current_block: {settings: {}, blocks: {}, html: "", is_html: false}, + blocks: {} + }; + + // update variables for passing context to the recursive calls on child components + let newParentIsDynamic = parentIsDynamic; + let newParentIsHtmlInsideDynamic = parentIsHtmlInsideDynamic; + if (component.attributes['block-id'] !== undefined) { + if (component.attributes['is-html'] === 'false') { + newParentIsDynamic = true; + newParentIsHtmlInsideDynamic = false; + } else if (parentIsDynamic) { + newParentIsDynamic = false; + newParentIsHtmlInsideDynamic = true; + } + } + + // depth-first recursive call for replacing nested blocks (the deepest blocks are handled first) + component.get('components').forEach(function(childComponent) { + let childData = replaceDynamicBlocksWithPlaceholders(childComponent, newParentIsDynamic, newParentIsHtmlInsideDynamic); + + // update data object with child data + for (let key in childData.current_block.blocks) { data.current_block.blocks[key] = childData.current_block.blocks[key]; } + for (let key in childData.blocks) { data.blocks[key] = childData.blocks[key]; } + }); + + // if the method is called with a cloned container (which does not have a parent), this top-level component does not need any changes + if (! component.parent()) { + return data; + } + + // if the component is not a block, no replacements need to be done + if (component.attributes['block-id'] === undefined) { + return data; + } + + // do the actual replacement of this component with a placeholder component + if (component.attributes['is-html'] === 'true') { + if (parentIsDynamic) { + // the full html content of html blocks directly inside a dynamic block should be stored in parent context using its block-id, + // this is important because a dynamic block defines block ids and this can collide with block ids hardcoded in other dynamic blocks + data.current_block['blocks'][component.attributes['block-id']] = {settings: {}, blocks: {}, html: window.html_beautify(getComponentHtml(component)), is_html: true}; + } else { + // html blocks outside direct context of dynamic blocks should be stored as a block itself + + // store the block's style-identifier + // this will be used as class in a wrapper around the dynamic block to give the block its styling + if (component.attributes['style-identifier'] !== undefined) { + data.current_block['settings']['attributes'] = {'style-identifier': component.attributes['style-identifier']}; + } + + // replace this html component by a shortcode with a unique id + let instanceId = component.attributes['block-id']; + if (! component.attributes['block-id'].startsWith('ID')) { + instanceId = generateId(); + } + + component.replaceWith({ + tagName: 'phpb-block', + attributes: { + slug: component.attributes['block-slug'], + id: instanceId + } + }); + + // store the block data globally in the blocks array + data.blocks[instanceId] = {settings: data.current_block['settings'], blocks: {}, html: window.html_beautify(getComponentHtml(component)), is_html: true}; + data.current_block = {settings: {}, blocks: {}, html: "", is_html: false}; + } + } else { + // store the attributes set to this block using traits in the settings side panel + let attributes = {}; + component.get('traits').each(function(trait) { + attributes[trait.get('name')] = trait.getTargetValue(); + }); + data.current_block['settings']['attributes'] = attributes; + + // store the block's style-identifier + // this will be used as class in a wrapper around the dynamic block to give the block its styling + if (component.attributes['style-identifier'] !== undefined) { + data.current_block['settings']['attributes']['style-identifier'] = component.attributes['style-identifier']; + } + + // replace this dynamic component by a shortcode with a unique id + let instanceId = component.attributes['block-id']; + if (! component.attributes['block-id'].startsWith('ID')) { + instanceId = generateId(); + } + component.replaceWith({ + tagName: 'phpb-block', + attributes: { + slug: component.attributes['block-slug'], + id: instanceId + } + }); + + // store data.current_block data inside data.blocks with the unique id we just generated + if (parentIsDynamic) { + // inside a dynamic block, the block data is passed to the context of its parent block (so current_block is used) + let currentBlockForParent = {settings: {}, blocks: {}, html: "", is_html: false}; + currentBlockForParent['blocks'][component.attributes['block-id']] = data.current_block; + data.current_block = currentBlockForParent; + } else { + // outside dynamic blocks, the block data is globally stored in the blocks array + data.blocks[instanceId] = data.current_block; + data.current_block = {settings: {}, blocks: {}, html: "", is_html: false}; + } + } + + return data; + } + + /** + * Generate a unique id string. + * + * Based on: https://gist.github.com/gordonbrander/2230317 + */ + let counter = 0; + function generateId() { + return 'ID' + (Date.now().toString(36) + + Math.random().toString(36).substr(2, 5) + counter++).toUpperCase(); + } + + /** + * Set the page builder waiting status. + */ + window.setWaiting = function(value) { + let wrapper = window.editor.DomComponents.getWrapper(); + if (value) { + wrapper.addClass("gjs-waiting"); + } else { + wrapper.removeClass("gjs-waiting"); + } + }; + + /** + * Toggle the save button waiting status. + */ + function toggleSaving() { + let button = $("#save-page"); + button.blur(); + + if (button.hasClass('waiting')) { + button.attr("disabled", false); + button.removeClass('waiting'); + button.find('.spinner-border').addClass('d-none'); + } else { + button.attr("disabled", true); + button.addClass('waiting'); + button.find('.spinner-border').removeClass('d-none'); + } + } + +}); diff --git a/src/Modules/GrapesJS/resources/assets/sass/app.scss b/src/Modules/GrapesJS/resources/assets/sass/app.scss new file mode 100644 index 0000000..4e41150 --- /dev/null +++ b/src/Modules/GrapesJS/resources/assets/sass/app.scss @@ -0,0 +1,2 @@ +@import 'pagebuilder'; +@import 'mobile-mode'; diff --git a/src/Modules/GrapesJS/resources/assets/sass/asset-manager.scss b/src/Modules/GrapesJS/resources/assets/sass/asset-manager.scss new file mode 100644 index 0000000..62d4eca --- /dev/null +++ b/src/Modules/GrapesJS/resources/assets/sass/asset-manager.scss @@ -0,0 +1,58 @@ +.gjs-am-assets-header { + display: none; +} +.gjs-am-assets-cont { + background: none; + padding-top: 0; +} +.gjs-am-assets { + height: 325px; +} +.gjs-am-asset { + -webkit-touch-callout: none; + -webkit-user-select: none; + -moz-user-select: none; + -ms-user-select: none; + user-select: none; +} + +.gjs-btn-prim { + display: inline-block; + margin-top: 10px; + padding: .375rem .75rem; + font-weight: 400; + text-align: center; + vertical-align: middle; + -webkit-user-select: none; + -moz-user-select: none; + -ms-user-select: none; + user-select: none; + font-size: 1rem; + line-height: 1.5; + border-radius: .25rem; + transition: color .15s ease-in-out,background-color .15s ease-in-out,border-color .15s ease-in-out,box-shadow .15s ease-in-out; + color: #fff; + border: 1px solid #0091d1; + background-color: #0091d1; +} + +.gjs-am-add-asset { + button { + float: left; + width: auto; + } + .gjs-am-add-field { + width: 100%; + } +} + +.gjs-am-file-uploader { + & > form { + background-color: rgba(195, 226, 236, 0.14); + border: 2px dashed rgb(189, 194, 200); + } + #gjs-am-title { + color: #7e8793; + text-shadow: none; + } +} diff --git a/src/Modules/GrapesJS/resources/assets/sass/ckeditor.scss b/src/Modules/GrapesJS/resources/assets/sass/ckeditor.scss new file mode 100644 index 0000000..1ba0f89 --- /dev/null +++ b/src/Modules/GrapesJS/resources/assets/sass/ckeditor.scss @@ -0,0 +1,16 @@ +.cke_dialog_body { + .cke_dialog_ui_vbox_child { + padding: 0; + } + input.cke_dialog_ui_input_text, + input.cke_dialog_ui_input_password, + input.cke_dialog_ui_input_tel, + textarea.cke_dialog_ui_input_textarea, + div.cke_dialog_ui_input_select { + margin-bottom: 10px; + } + + .cke_dialog_ui_input_select { + width: 100% !important; + } +} diff --git a/src/Modules/GrapesJS/resources/assets/sass/fields.scss b/src/Modules/GrapesJS/resources/assets/sass/fields.scss new file mode 100644 index 0000000..c71746d --- /dev/null +++ b/src/Modules/GrapesJS/resources/assets/sass/fields.scss @@ -0,0 +1,42 @@ +.gjs-field { + background-color: #22272e; +} +.gjs-field select { + option { + background-color: #fff; + color: #000; + } +} +.gjs-input-unit { + color: #e1e1e1; +} +.gjs-field-arrows { + color: #e1e1e1; +} +.gjs-sm-field select.gjs-input-unit { + color: #e1e1e1; + + option { + background-color: #22272e; + color: #fff; + } +} +.gjs-field-arrow-d { + border-top: 4px solid #e1e1e1; +} +.gjs-field-arrow-u { + border-bottom: 4px solid #e1e1e1; +} + +.gjs-field-radio { + padding: 0 !important; +} +.gjs-radio-item .gjs-radio-item-label { + padding-top: 10px; + margin-bottom: 0; + padding-bottom: 10px; + width: 100%; +} +.gjs-radio-item input:checked + .gjs-radio-item-label { + background-color: #545d6c; +} \ No newline at end of file diff --git a/src/Modules/GrapesJS/resources/assets/sass/mobile-mode.scss b/src/Modules/GrapesJS/resources/assets/sass/mobile-mode.scss new file mode 100644 index 0000000..db5870a --- /dev/null +++ b/src/Modules/GrapesJS/resources/assets/sass/mobile-mode.scss @@ -0,0 +1,21 @@ +.sidebar-collapsed { + .gjs-cv-canvas { + width: calc(100% - 0px); + } + + .gjs-pn-panels { + display: none; + } + .gjs-cv-canvas, .gjs-pn-devices-c { + left: 0; + } + + #toggle-sidebar { + padding: 14px 18px; + font-size: 18px; + -webkit-box-shadow: 3px 7px 11px -4px rgba(0,0,0,0.03); + -moz-box-shadow: 3px 7px 11px -4px rgba(0,0,0,0.03); + box-shadow: 2px 3px 10px 2px rgba(0,0,0,0.3); + border-bottom-right-radius: 4px; + } +} diff --git a/src/Modules/GrapesJS/resources/assets/sass/page-injection.scss b/src/Modules/GrapesJS/resources/assets/sass/page-injection.scss new file mode 100644 index 0000000..3e1b1d1 --- /dev/null +++ b/src/Modules/GrapesJS/resources/assets/sass/page-injection.scss @@ -0,0 +1,70 @@ +html, body { + overflow-x: initial !important; +} +form { + margin-block-end: 0; +} + +[data-cursor="default"] { + cursor: default; +} +[data-cursor="text"] { + cursor: text; +} +span[draggable="true"] { + display: inline-flex; +} +[phpb-hide-if-not-editable] { + background: #fde3c17d; + border: 1px dashed #b98e577d; + padding: 7px; + font-size: 1.1rem; + font-style: italic; + font-weight: normal; + text-align: center; + color: #5e5e5e; + + &:not(.editable) { + display: none; + } +} + +[data-gjs-type].gjs-comp-selected { + outline: 1px solid #0091d1 !important; + outline-offset: 0 !important; +} +div[data-gjs-type].gjs-comp-selected { + outline: 1px solid #0091d1 !important; + outline-offset: -1px !important; +} +[phpb-content-container], +[phpb-blocks-container] { + min-height: 50px; + width: 100%; +} +[phpb-blocks-container] { + border: 1px dashed #0091d1; +} + +html, +body { + ::-webkit-scrollbar { + width: 11px; + height: 11px; + } + ::-webkit-scrollbar-track { + background: #f5f5f5; + } + ::-webkit-scrollbar-thumb { + background-color: #ccc; + + &:hover { + background-color: #bbb; + } + } +} + +.gjs-waiting { + opacity: 0.5; + pointer-events: none; +} diff --git a/src/Modules/GrapesJS/resources/assets/sass/pagebuilder.scss b/src/Modules/GrapesJS/resources/assets/sass/pagebuilder.scss new file mode 100644 index 0000000..c114ada --- /dev/null +++ b/src/Modules/GrapesJS/resources/assets/sass/pagebuilder.scss @@ -0,0 +1,573 @@ +$sidebar-width: 325px; +$sidebar-bottom-buttons-height: 40px; + + +/* GENERAL */ + +html, body, #gjs { + height: 100% !important; + margin: 0; + overflow: hidden; +} + +* { + -webkit-box-shadow: none !important; + -moz-box-shadow: none !important; + box-shadow: none !important; +} + +.form-control, .form-control:focus { + color: #e1e1e1; +} + +.cursor-pointer { + cursor: pointer; +} + +.gjs-editor { + font-size: 0.9rem; +} + +.toast { + opacity: 1 !important; + border: none; + right: 15px; + box-shadow: none; + + &.toast-success { + background: #2dc837; + } +} + +#phpb-loading { + position: absolute; + height: 100%; + width: 100%; + background-color: #fff; + z-index: 10000; + transition: opacity 0.3s, visibility 0.3s; + + &.loaded { + visibility: hidden; + opacity: 0; + } + + .circle { + position: absolute; + top: 50%; + left: 50%; + transform: translate(-50%,-50%); + width: 150px; + height: 150px; + + .text { + font-size: 20px; + margin: 0 -30px; + margin-top: 20px; + text-align: center; + color: #0091d1; + } + } + .loader { + width: calc(100% - 0px); + height: calc(100% - 0px); + border: 8px solid #0091d1; + border-top: 8px solid #004a6c; + border-radius: 50%; + animation: rotate 5s linear infinite; + } + @keyframes rotate { + 100% {transform: rotate(360deg);} + } +} + +.btn.focus, .btn:focus { + box-shadow: none; +} + +.gjs-cv-canvas { + height: 100%; + top: 0; + width: calc(100% - #{$sidebar-width}); +} +.gjs-toolbar { + z-index: 100 !important; +} + +.gjs-pn-panel { + padding: 0; + + .gjs-pn-buttons { + justify-content: center; + } +} +.gjs-pn-commands, +.gjs-pn-options, +.gjs-pn-devices-c { + display: none; +} +.gjs-devices-c { + padding: 0; +} +.gjs-one-bg { + background-color: #313844; + border-bottom: none; + color: #c4c7ce; +} +.gjs-two-color { + color: #e1e1e1; +} +.gjs-four-color { + color: #e1e1e1; +} +.gjs-four-color-h:hover { + color: #e1e1e1; +} +.gjs-pn-commands { + width: 100%; + -webkit-box-shadow: none; + -moz-box-shadow: none; + box-shadow: none; +} +::-webkit-scrollbar { + width: 7px; + height: 7px; +} +::-webkit-scrollbar-track { + background: #313844 !important; +} +::-webkit-scrollbar-thumb { + background-color: #a5acb9 !important; + border-radius: 3px; + + &:hover { + background-color: #0091d1 !important; + } +} + +/* SIDEBAR */ + +.gjs-pn-views { + top: 40px; + + .gjs-pn-btn { + width: 33.33%; + margin-right: 0; + padding: 16px 15px 16px 15px; + -webkit-border-radius: 0; + -moz-border-radius: 0; + border-radius: 0; + background: #3a3f4a; + color: #e3e3e3; + border-bottom: 1px solid #3a3f4a; + font-size: 16px; + + &.gjs-pn-active { + padding: 15px; + background-color: #515664; + border-bottom-left-radius: unset; + border-bottom-right-radius: unset; + -webkit-box-shadow: none; + -moz-box-shadow: none; + box-shadow: none; + color: #fff; + border-bottom: 3px solid #0091d1; + } + } +} +.gjs-pn-options { + right: 0; +} +.gjs-pn-views, +.gjs-pn-views-container { + left: 0; + -webkit-box-shadow: none; + -moz-box-shadow: none; + box-shadow: none; + width: $sidebar-width; + padding-bottom: 0; + margin-bottom: 0; + margin-left: 0; + margin-right: 0; + padding-left: 0; + padding-right: 0; +} +.gjs-pn-views-container { + padding-top: 89px; + background: #22272e; + height: calc(100% - #{$sidebar-bottom-buttons-height}); + overflow: hidden; + + > div:first-of-type { + margin-top: 44px; + } + + > div { + height: 100%; + overflow-y: auto; + } + + > div > div { + background: #22272e; + border: none; + } +} +.gjs-cv-canvas, +.gjs-pn-devices-c { + left: $sidebar-width; +} +.gjs-pn-panel { + #gjs-sm-caret { + padding-right: 0 !important; + } + .fa-caret-down { + margin-right: 5px !important; + } + .fa-caret-right { + margin-right: 8px !important; + } +} + + +/* SIDEBAR FIELDS */ + +.gjs-three-bg { + background-color: #0091d1; +} +.gjs-clm-tags { + #gjs-clm-close, + #gjs-clm-checkbox { + color: #fff; + } +} +.gjs-field { + background-color: #22272e; + border-radius: 0; + padding: 2px; + + input, + select, + textarea { + padding: 5px; + } + + .gjs-d-s-arrow { + border-top: 4px solid rgb(100, 100, 100); + } +} + + +/* SIDEBAR HEADER */ + +#sidebar-header { + position: absolute; + box-shadow: none; + width: $sidebar-width; + padding-bottom: 0; + margin-bottom: 0; + margin-left: 0; + margin-right: 0; + padding-left: 0; + padding-right: 0; + background: #22272e; + height: 40px; + z-index: 100; + + #language-selector { + float: right; + + .dropdown-item.active, + .dropdown-item:active { + background: #22272e !important; + } + .dropdown-menu.show { + padding: 0; + } + .dropdown-toggle { + margin-top: 2px; + color: #fff !important; + background: none !important; + border: none; + box-shadow: none; + outline: none !important; + } + .flag-icon { + background-size: contain; + background-position: 50%; + background-repeat: no-repeat; + position: relative; + display: inline-block; + width: 1.33333333em; + height: 12px; + line-height: 1em; + } + } +} +#toggle-sidebar { + position: absolute; + left: 0; + top: 0; + z-index: 100; + color: #c4c7ce; + background: #22272e; + border-radius: 0; + transition-duration: unset; +} + + +/* BLOCKS PANEL VIEW */ + +#block-search { + position: fixed; + background: #22272e; + border-color: #3a3f4a; + border-radius: 0; + width: 325px; + margin-top: -44px; + + i.fa-search { + position: absolute; + top: 14px; + left: 9px; + font-size: 15px; + color: #515664; + } + + input { + background: #181b1e; + padding: 22px 20px 22px 30px; + border-radius: 0; + border: none; + + &::placeholder { + color: #515664; + } + } +} + +.gjs-block { + border: none; + box-shadow: none; + padding-bottom: 8px; + margin: 5px; + width: calc(50% - 10px); + + &.fa { + padding: 8px; + } + + &:hover { + color: #0091d1 !important; + } + + .block-thumb { + height: 70px; + overflow: hidden; + margin-bottom: 5px; + opacity: 0.8; + + img { + width: 100%; + } + } +} +.gjs-blocks-c { + background: #22272e; + padding: 4px; +} +.gjs-block-categories { + background: #22272e; + padding-bottom: 45px; +} +.gjs-block-label { + font-size: 0.8rem; + height: 100%; + display: grid; + + b { + display: contents; + font-weight: 800; + } +} +.gjs-block-category { + background: #5a6371; +} +.gjs-block-category.gjs-open { + border-bottom: none !important; + margin-bottom: 10px; +} +.gjs-blocks-cs { + border-bottom: none !important; +} + + +/* LAYERS PANEL VIEW */ + +.gjs-layer .gjs-layer-title { + background: #5a6371 !important; +} +.gjs-layer.gjs-selected .gjs-layer-title { + background-color: #0091d1 !important; +} +.gjs-layer.gjs-hovered .gjs-layer-title { + background-color: #0091d170 !important +} +.gjs-category-title, +.gjs-sm-sector .gjs-sm-title, +.gjs-clm-tags .gjs-sm-title, +.gjs-block-category .gjs-title, +.gjs-layer-title { + background: #424853 !important; + border-bottom: 2px solid #363d48 !important; + letter-spacing: 0; + font-size: 16px; + font-weight: normal; +} +.gjs-sm-sector.gjs-sm-open .gjs-sm-title, +.gjs-clm-tags.gjs-open .gjs-sm-title, +.gjs-block-category.gjs-open .gjs-title { + background: #545d6c !important; +} +.gjs-layer-name { + padding-top: 2px; + padding-bottom: 13px; +} +.gjs-layer-count { + display: none; +} +.gjs-layer-vis { + padding-top: 11px +} + + +/* LAYERS PANEL VIEW */ + +.gjs-sm-sector.gjs-sm-open { + border-bottom: 1px solid rgba(0, 0, 0, 0.1); +} + + +/* TRAITS PANEL VIEW */ + +.gjs-trt-trait { + display: block; +} +.gjs-trt-header { + font-weight: normal; +} +.gjs-trt-trait .gjs-label, +.gjs-trt-trait .gjs-field { + width: 100%; +} +.gjs-field-checkbox { + height: 17px !important; + width: 17px !important; +} +.gjs-traits-label { + font-weight: normal; + font-size: 16px; + border-bottom: none; +} +.gjs-sm-sector #gjs-sm-caret, +.gjs-clm-tags #gjs-sm-caret { + font-size: initial; +} +.gjs-trt-traits .gjs-label-wrp { + width: 100%; +} +.gjs-trt-traits p.no-settings { + padding-top: 10px; + padding-bottom: 10px; +} +.gjs-trt-trait__wrp:first-of-type { + padding-top: 8px; +} +.gjs-trt-trait__wrp:last-of-type { + padding-bottom: 8px; +} +.gjs-trt-trait { + padding-bottom: 10px; +} +.gjs-trt-trait .gjs-field-image { + background: none; + padding: 0; + + .image__preview-container { + text-align: center; + + .image__remove-button { + position: absolute; + right: 0; + top: 0; + border-radius: 0; + background-color: #e9eef2; + border-color: #e9eef2; + color: #515664; + padding: 2px 6px; + } + + img { + max-width: 100%; + max-height: 150px; + } + } +} + + +/* SIDEBAR BOTTOM BUTTONS */ + +#sidebar-bottom-buttons { + position: absolute; + left: 0; + bottom: 0; + height: $sidebar-bottom-buttons-height; + width: $sidebar-width; + margin: 0; + padding: 0; + -webkit-box-shadow: none; + -moz-box-shadow: none; + box-shadow: none; + background: #474c57; + border-top: none; + + button, + a { + float: right; + height: 100%; + width: 33.33%; + border-left: 1px solid #343944; + border-radius: 0; + color: #e3e3e3; + font-size: 15px; + padding: 8px 0; + + &:hover { + background: #017eb5; + color: #fff; + } + &:last-child { + border-left: none; + } + } + + button.waiting { + background: #0091d1; + color: #fff !important; + + i.fa { + display: none; + } + } + + #go-back:hover { + background: #b03541; + } + #save-page:hover { + background: #419147; + } +} + +@import 'fields'; +@import 'style-manager'; +@import 'asset-manager'; +@import 'ckeditor'; \ No newline at end of file diff --git a/src/Modules/GrapesJS/resources/assets/sass/style-manager.scss b/src/Modules/GrapesJS/resources/assets/sass/style-manager.scss new file mode 100644 index 0000000..1e53887 --- /dev/null +++ b/src/Modules/GrapesJS/resources/assets/sass/style-manager.scss @@ -0,0 +1,68 @@ +.gjs-sm-header, .gjs-trt-header { + font-weight: normal; + color: #8c909d; +} + +.gjs-clm-tags { + width: 100%; + padding-top: 0; + padding-bottom: 0; + + #gjs-clm-status-c, + #gjs-clm-sel-help { + display: none; + } + #gjs-clm-new { + color: #e1e1e1; + } + #gjs-clm-add-tag { + background-color: #0091d1; + border: none; + box-shadow: 1px 1px 0 rgba(255, 255, 255, 0.2) inset; + color: #fff; + + &:hover { + background-color: #004a6c; + } + } +} + +.gjs-sm-sectors { + .gjs-four-color, + .gjs-color-warn { + color: #e1e1e1; + } + + .gjs-sm-field.gjs-sm-composite { + background-color: rgba(195, 226, 236, 0.14); + border: 1px solid rgba(121, 147, 155, 0.14); + } + + .gjs-sm-layers { + background-color: #3a3f4a; + + .gjs-sm-btn { + background: #fff; + color: #000; + text-shadow: none; + } + + .gjs-field { + padding: 0; + background-color: #3a3f4a; + + select { + color: #fff; + background: #424853; + } + } + } + + .gjs-sm-stack #gjs-sm-add { + color: #fff; + + &:hover { + color: #aaa; + } + } +} \ No newline at end of file diff --git a/src/Modules/GrapesJS/resources/views/grapesjs/asset-manager.php b/src/Modules/GrapesJS/resources/views/grapesjs/asset-manager.php new file mode 100644 index 0000000..8a6941d --- /dev/null +++ b/src/Modules/GrapesJS/resources/views/grapesjs/asset-manager.php @@ -0,0 +1,18 @@ + diff --git a/src/Modules/GrapesJS/resources/views/grapesjs/component-type-manager.php b/src/Modules/GrapesJS/resources/views/grapesjs/component-type-manager.php new file mode 100644 index 0000000..930a598 --- /dev/null +++ b/src/Modules/GrapesJS/resources/views/grapesjs/component-type-manager.php @@ -0,0 +1,110 @@ + diff --git a/src/Modules/GrapesJS/resources/views/grapesjs/config.php b/src/Modules/GrapesJS/resources/views/grapesjs/config.php new file mode 100644 index 0000000..b64cd3d --- /dev/null +++ b/src/Modules/GrapesJS/resources/views/grapesjs/config.php @@ -0,0 +1,114 @@ + '#gjs', + 'noticeOnUnload' => false, + 'avoidInlineStyle' => true, + 'allowScripts' => true, + 'storageManager' => [ + 'type' => 'local', + 'autoload' => false, + 'autosave' => false + ], + 'canvasCss' => 'body {height: auto;}', // prevent scrollbar jump on pasting in CKEditor + 'assetManager' => [ + 'upload' => phpb_url('pagebuilder', ['action' => 'upload', 'page' => $page->getId()]), + 'uploadName' => 'files', + 'multiUpload' => false, + 'assets' => $assets + ], + 'styleManager' => [ + 'sectors' => [[ + 'id' => 'position', + 'name' => phpb_trans('pagebuilder.style-manager.sectors.position'), + 'open' => true, + 'buildProps' => ['width', 'height', 'min-width', 'min-height', 'max-width', 'max-height', 'padding', 'margin', 'text-align'], + 'properties' => [[ + 'property' => 'text-align', + 'list' => [ + ['value' => 'left', 'className' => 'fa fa-align-left'], + ['value' => 'center', 'className' => 'fa fa-align-center'], + ['value' => 'right', 'className' => 'fa fa-align-right'], + ['value' => 'justify', 'className' => 'fa fa-align-justify'], + ], + ]] + ], [ + 'id' => 'background', + 'name' => phpb_trans('pagebuilder.style-manager.sectors.background'), + 'open' => false, + 'buildProps' => ['background-color', 'background'] + ]] + ], + 'selectorManager' => [ + 'label' => phpb_trans('pagebuilder.selector-manager.label'), + 'statesLabel' => phpb_trans('pagebuilder.selector-manager.states-label'), + 'selectedLabel' => phpb_trans('pagebuilder.selector-manager.selected-label'), + 'states' => [ + ['name' => 'hover', 'label' => phpb_trans('pagebuilder.selector-manager.state-hover')], + ['name' => 'active', 'label' => phpb_trans('pagebuilder.selector-manager.state-active')], + ['name' => 'nth-of-type(2n)', 'label' => phpb_trans('pagebuilder.selector-manager.state-nth')] + ], + ], + 'traitManager' => [ + 'labelPlhText' => '', + 'labelPlhHref' => 'https://website.com' + ], + 'panels' => [ + 'defaults' => [ + [ + 'id' => 'views', + 'buttons' => [ + [ + 'id' => 'open-blocks-button', + 'className' => 'fa fa-th-large', + 'command' => 'open-blocks', + 'togglable' => 0, + 'attributes' => ['title' => phpb_trans('pagebuilder.view-blocks')], + 'active' => true, + ], + [ + 'id' => 'open-settings-button', + 'className' => 'fa fa-cog', + 'command' => 'open-tm', + 'togglable' => 0, + 'attributes' => ['title' => phpb_trans('pagebuilder.view-settings')], + ], + [ + 'id' => 'open-style-button', + 'className' => 'fa fa-paint-brush', + 'command' => 'open-sm', + 'togglable' => 0, + 'attributes' => ['title' => phpb_trans('pagebuilder.view-style-manager')], + ] + ] + ], + ] + ], + 'canvas' => [ + 'styles' => [ + phpb_asset('pagebuilder/page-injection.css'), + ], + ], + 'plugins' => ['grapesjs-touch', 'gjs-plugin-ckeditor'], + 'pluginsOpts' => [ + 'gjs-plugin-ckeditor' => [ + 'position' => 'left', + 'options' => [ + 'startupFocus' => true, + 'allowedContent' => true, + //'forcePasteAsPlainText' => false, // when true does not copy UL, random JS errors while pasting + //'extraAllowedContent' => '*(*);*[*];ul ol li span', // allows classes, inline styles and certain elements + //'enterMode' => 'CKEDITOR.ENTER_BR', // issues on pasting in Chromes + 'extraPlugins' => 'sourcedialog', + 'toolbar' => [ + ['Bold', 'Italic', 'Underline', 'Strike', 'Undo', 'Redo'], + ['Link', 'Unlink'], + ['NumberedList', 'BulletedList'], + ['JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock'], + ['FontSize', 'TextColor'], + ['Sourcedialog'] + ], + ] + ] + ] +]; diff --git a/src/Modules/GrapesJS/resources/views/grapesjs/style-manager.php b/src/Modules/GrapesJS/resources/views/grapesjs/style-manager.php new file mode 100644 index 0000000..0f7b8e6 --- /dev/null +++ b/src/Modules/GrapesJS/resources/views/grapesjs/style-manager.php @@ -0,0 +1,32 @@ + diff --git a/src/Modules/GrapesJS/resources/views/grapesjs/trait-manager.php b/src/Modules/GrapesJS/resources/views/grapesjs/trait-manager.php new file mode 100644 index 0000000..aef08db --- /dev/null +++ b/src/Modules/GrapesJS/resources/views/grapesjs/trait-manager.php @@ -0,0 +1,46 @@ + diff --git a/src/Modules/GrapesJS/resources/views/layout.php b/src/Modules/GrapesJS/resources/views/layout.php new file mode 100644 index 0000000..45f284e --- /dev/null +++ b/src/Modules/GrapesJS/resources/views/layout.php @@ -0,0 +1,36 @@ + + + + + PageBuilder + + + + + + + + + customStyle(); ?> + + + + + + + + + + customScripts('head'); ?> + + + + + + + +customScripts('body'); ?> + + diff --git a/src/Modules/GrapesJS/resources/views/pagebuilder.php b/src/Modules/GrapesJS/resources/views/pagebuilder.php new file mode 100644 index 0000000..078b2c7 --- /dev/null +++ b/src/Modules/GrapesJS/resources/views/pagebuilder.php @@ -0,0 +1,165 @@ +
+
+
+
+
+
+
+
+
+
+ +
+
+
+ +
+ + + + + + + + + + + +
+ + diff --git a/src/Modules/Router/DatabasePageRouter.php b/src/Modules/Router/DatabasePageRouter.php new file mode 100644 index 0000000..a1befe6 --- /dev/null +++ b/src/Modules/Router/DatabasePageRouter.php @@ -0,0 +1,200 @@ +pageRepository = new PageRepository; + $this->pageTranslationRepository = new PageTranslationRepository; + $this->routeParameters = []; + $this->routeToPageTranslationIdMapping = []; + } + + /** + * Return the page from database corresponding to the given URL. + * + * @param $url + * @return PageTranslationContract|null + */ + public function resolve($url) + { + // strip URL query parameters + $url = explode('?', $url, 2)[0]; + // split URL into segments using / as separator + $urlSegments = explode('/', $url); + + // request all routes and convert each to its segments using / as separator + $pageTranslations = $this->pageTranslationRepository->getAll(['id', 'route']); + $routes = []; + foreach ($pageTranslations as $pageTranslation) { + $route = $pageTranslation->route; + $this->routeToPageTranslationIdMapping[$route] = $pageTranslation->id; + $routeSegments = explode('/', $route); + $routes[] = $routeSegments; + } + + // sort routes into the order for evaluation + $orderedRoutes = $this->getRoutesInOrder($routes); + + // match each route with current URL segments and return the corresponding page once we find a match + foreach ($orderedRoutes as $routeSegments) { + if ($this->onRoute($urlSegments, $routeSegments)) { + $fullRoute = implode('/', $routeSegments); + $matchedPage = $this->getMatchedPage($fullRoute, $this->routeToPageTranslationIdMapping[$fullRoute]); + + if ($matchedPage) { + global $phpb_route_parameters; + $phpb_route_parameters = $this->routeParameters; + + return $matchedPage; + } + } + } + + return null; + } + + /** + * Sort the given routes into the order in which they need to be evaluated. + * + * @param $allRoutes + * @return array + */ + public function getRoutesInOrder($allRoutes) + { + usort($allRoutes, [$this, "routeOrderComparison"]); + return $allRoutes; + } + + /** + * Compare two given routes and return -1,0,1 indicating which route should be evaluated first. + * + * @param $route1 + * @param $route2 + * @return int + */ + public function routeOrderComparison($route1, $route2) + { + // routes with more segments should be evaluated first + if (sizeof($route1) > sizeof($route2)) { + return -1; + } + if (sizeof($route1) < sizeof($route2)) { + return 1; + } + + // routes ending with (more) named parameters should be evaluated after exact matches, but before catch all + $namedParameterCountRoute1 = substr_count(implode('/', $route1), '{'); + $namedParameterCountRoute2 = substr_count(implode('/', $route2), '{'); + if ($namedParameterCountRoute1 < $namedParameterCountRoute2) { + return -1; + } + if ($namedParameterCountRoute1 > $namedParameterCountRoute2) { + return 1; + } + + // routes ending with a wildcard should be evaluated last (after exact matches or named parameters) + if (array_slice($route1, -1)[0] === '*') { + return 1; + } + if (array_slice($route2, -1)[0] === '*') { + return -1; + } + + // otherwise, the order is undetermined + return 0; + } + + /** + * Return the full page translation instance based on the given matched route or page translation id. + * (this method is helpful when extending a router to perform additional checks after a route has been matched) + * + * @param string $matchedRoute the matched route + * @param string $matchedPageTranslationId the page translation id corresponding to the matched route + * @return PageTranslationContract|null + */ + public function getMatchedPage(string $matchedRoute, string $matchedPageTranslationId) + { + $pageTranslation = $this->pageTranslationRepository->findWithId($matchedPageTranslationId); + if ($pageTranslation instanceof PageTranslationContract) { + return $pageTranslation; + } + return null; + } + + /** + * Return whether the given URL segments match with the given route segments. + * + * @param $urlSegments + * @param $routeSegments + * @return bool + */ + protected function onRoute($urlSegments, $routeSegments) + { + // URL does not match if segment counts don't match, except if the route ends with a * + if (sizeof($urlSegments) !== sizeof($routeSegments) && end($routeSegments) !== '*') { + return false; + } + + // try matching each route segment with the same level URL segment + $routeParameters = []; + foreach ($routeSegments as $i => $routeSegment) { + if (! isset($urlSegments[$i])) { + return false; + } + $urlSegment = $urlSegments[$i]; + + // the URL segment matches if the route segment is a {parameter} + if (substr($routeSegment,0, 1) === '{' && substr($routeSegment, -1) === '}') { + $parameter = trim($routeSegment, '{}'); + $routeParameters[$parameter] = $urlSegment; + continue; + } + // the URL fully matches if the route segment is a wildcard + if ($routeSegment === '*') { + break; + } + // the URL segment matches if equal to the route segment + if ($urlSegment === $routeSegment) { + continue; + } + + // the URL segment and route segment did not match + return false; + } + + $this->routeParameters = $routeParameters; + return true; + } +} diff --git a/src/Modules/WebsiteManager/WebsiteManager.php b/src/Modules/WebsiteManager/WebsiteManager.php new file mode 100644 index 0000000..580e0a6 --- /dev/null +++ b/src/Modules/WebsiteManager/WebsiteManager.php @@ -0,0 +1,236 @@ +renderOverview(); + exit(); + } + + if ($route === 'settings') { + if ($action === 'renderBlockThumbs') { + $this->renderBlockThumbs(); + exit(); + } + if ($action === 'update') { + $this->handleUpdateSettings(); + exit(); + } + } + + if ($route === 'menus') { + if ($action === 'update') { + $this->handleUpdateMenus(); + exit(); + } + } + + if ($route === 'page_settings') { + if ($action === 'create') { + $this->handleCreate(); + exit(); + } + + $pageId = $_GET['page'] ?? null; + $pageRepository = new PageRepository; + $page = $pageRepository->findWithId($pageId); + if (! ($page instanceof PageContract)) { + phpb_redirect(phpb_url('website_manager')); + } + + if ($action === 'edit') { + $this->handleEdit($page); + exit(); + } else if ($action === 'destroy') { + $this->handleDestroy($page); + } + } + } + + /** + * Handle requests for creating a new page. + */ + public function handleCreate() + { + if ($_SERVER['REQUEST_METHOD'] === 'POST') { + $pageRepository = new PageRepository; + $page = $pageRepository->create($_POST); + if ($page) { + phpb_redirect(phpb_url('website_manager'), [ + 'message-type' => 'success', + 'message' => phpb_trans('website-manager.page-created') + ]); + } + } + + $this->renderPageSettings(); + } + + /** + * Handle requests for editing the given page. + * + * @param PageContract $page + */ + public function handleEdit(PageContract $page) + { + if ($_SERVER['REQUEST_METHOD'] === 'POST') { + $pageRepository = new PageRepository; + $success = $pageRepository->update($page, $_POST); + if ($success) { + phpb_redirect(phpb_url('website_manager'), [ + 'message-type' => 'success', + 'message' => phpb_trans('website-manager.page-updated') + ]); + } + } + + $this->renderPageSettings($page); + } + + /** + * Handle requests to destroy the given page. + * + * @param PageContract $page + */ + public function handleDestroy(PageContract $page) + { + $pageRepository = new PageRepository; + $pageRepository->destroy($page->getId()); + phpb_redirect(phpb_url('website_manager'), [ + 'message-type' => 'success', + 'message' => phpb_trans('website-manager.page-deleted') + ]); + } + + /** + * Handle requests for updating the website settings. + */ + public function handleUpdateSettings() + { + if ($_SERVER['REQUEST_METHOD'] === 'POST') { + $settingRepository = new SettingRepository; + $success = $settingRepository->updateSettings($_POST); + if ($success) { + phpb_redirect(phpb_url('website_manager', ['tab' => 'settings']), [ + 'message-type' => 'success', + 'message' => phpb_trans('website-manager.settings-updated') + ]); + } + } + } + + /** + * Handle requests for updating the website menuss. + */ + public function handleUpdateMenus() + { + if ($_SERVER['REQUEST_METHOD'] === 'POST') { + $settingRepository = new MenuRepository; + $success = $settingRepository->updateMenus($_POST); + if ($success) { + phpb_redirect(phpb_url('website_manager', ['tab' => 'menus']), [ + 'message-type' => 'success', + 'message' => phpb_trans('website-manager.menus-updated') + ]); + } + } + } + + /** + * Render the website manager overview page. + */ + public function renderOverview() + { + $pageRepository = new PageRepository; + $pages = $pageRepository->getAll(); + uasort($pages, function ($a, $b){ + return ($a->getRoute() < $b->getRoute()) ? -1 : 1; + }); + + $pageTranslationRepository = new PageTranslationRepository; + $pageTranslations = $pageTranslationRepository->getAll(); + + $filesRepository = new UploadRepository; + $files = $filesRepository->getAll(); + + $menuRepository = new MenuRepository; + $menus = $menuRepository->getHydratedMenus(); + $menusJson = json_encode($menus); + + $menuPages = []; + foreach ($pages as $page) { + $menuPages[] = [ + 'id' => $page->getId(), + 'title' => $page->getName(), + 'route' => $page->getRoute() + ]; + } + $menuPagesJson = json_encode($menuPages); + + $viewFile = 'overview'; + require __DIR__ . '/resources/layouts/master.php'; + } + + /** + * Render the website manager page settings (add/edit page form). + * + * @param PageContract $page + */ + public function renderPageSettings(PageContract $page = null) + { + $action = isset($page) ? 'edit' : 'create'; + $theme = phpb_instance('theme', [ + phpb_config('theme'), + phpb_config('theme.active_theme') + ]); + + $viewFile = 'page-settings'; + require __DIR__ . '/resources/layouts/master.php'; + } + + /** + * Render the website manager menu settings (add/edit menu form). + */ + public function renderMenuSettings() + { + $viewFile = 'menu-settings'; + require __DIR__ . '/resources/layouts/master.php'; + } + + /** + * Render a thumbnail for each theme block. + */ + public function renderBlockThumbs() + { + $viewFile = 'block-thumbs'; + require __DIR__ . '/resources/layouts/master.php'; + } + + /** + * Render the website manager welcome page for installations without a homepage. + */ + public function renderWelcomePage() + { + $viewFile = 'welcome'; + require __DIR__ . '/resources/layouts/empty.php'; + } +} diff --git a/src/Modules/WebsiteManager/resources/assets/entry.js b/src/Modules/WebsiteManager/resources/assets/entry.js new file mode 100644 index 0000000..4a37d61 --- /dev/null +++ b/src/Modules/WebsiteManager/resources/assets/entry.js @@ -0,0 +1,10 @@ +import Alpine from "alpinejs" +import './sass/app.scss' +import './js/app.js' + +import "@phosphor-icons/web/light"; +import "@phosphor-icons/web/bold"; +import "@phosphor-icons/web/fill"; +import "@phosphor-icons/web/duotone"; + +Alpine.start() diff --git a/src/Modules/WebsiteManager/resources/assets/js/app.js b/src/Modules/WebsiteManager/resources/assets/js/app.js new file mode 100644 index 0000000..b585bff --- /dev/null +++ b/src/Modules/WebsiteManager/resources/assets/js/app.js @@ -0,0 +1,8 @@ +window.addEventListener("message", onMessage, false); + +function onMessage(event) { + if (event.data === 'thumb-saved') { + const itr = document.querySelector("iframe.thumb-renderer") + itr.attributes.src = `${itr.attributes.src}` + } +} diff --git a/src/Modules/WebsiteManager/resources/assets/sass/app.scss b/src/Modules/WebsiteManager/resources/assets/sass/app.scss new file mode 100644 index 0000000..b5c61c9 --- /dev/null +++ b/src/Modules/WebsiteManager/resources/assets/sass/app.scss @@ -0,0 +1,3 @@ +@tailwind base; +@tailwind components; +@tailwind utilities; diff --git a/src/Modules/WebsiteManager/resources/layouts/empty.php b/src/Modules/WebsiteManager/resources/layouts/empty.php new file mode 100644 index 0000000..fc48211 --- /dev/null +++ b/src/Modules/WebsiteManager/resources/layouts/empty.php @@ -0,0 +1,28 @@ + + + + + + PHPageBuilder + + + + + + + + + +
+ +
+ + + + + + + + diff --git a/src/Modules/WebsiteManager/resources/layouts/master.php b/src/Modules/WebsiteManager/resources/layouts/master.php new file mode 100644 index 0000000..b701c09 --- /dev/null +++ b/src/Modules/WebsiteManager/resources/layouts/master.php @@ -0,0 +1,35 @@ + + + + + + <?= phpb_trans('website-manager.title') ?> + + + + + + +
+ + + + + + + + + +
+ + + + diff --git a/src/Modules/WebsiteManager/resources/views/block-thumbs.php b/src/Modules/WebsiteManager/resources/views/block-thumbs.php new file mode 100644 index 0000000..dc72cb4 --- /dev/null +++ b/src/Modules/WebsiteManager/resources/views/block-thumbs.php @@ -0,0 +1,30 @@ +getId()); +} +?> + +
+

+
+ +
+
+ +
+

+ +
+ +
+ +
+ + + + +
+
+ +
diff --git a/src/Modules/WebsiteManager/resources/views/overview.php b/src/Modules/WebsiteManager/resources/views/overview.php new file mode 100644 index 0000000..046b2b6 --- /dev/null +++ b/src/Modules/WebsiteManager/resources/views/overview.php @@ -0,0 +1,34 @@ + +
+

+
+ +
+
+
+
+ $tab) : + ?> + + +
+
+ +
+
+ +
+
+
+
diff --git a/src/Modules/WebsiteManager/resources/views/page-settings.php b/src/Modules/WebsiteManager/resources/views/page-settings.php new file mode 100644 index 0000000..8911758 --- /dev/null +++ b/src/Modules/WebsiteManager/resources/views/page-settings.php @@ -0,0 +1,128 @@ +getId()); +} + +$pageTranslations = $page ? $page->getTranslations() : []; +?> + +
+

+
+ +
+
+ +
+
+

+ +

+ +
+
+ + + +
+ +
+ + +
+ + $languageTranslation): + ?> +
> + +
+
+
+ + +
+ +
+ + +
+ +
+ + +
+ +
+ + +
+ +
+
+
+ + +
+ + + + +
+ +
+ +
+ +
+
+ +
diff --git a/src/Modules/WebsiteManager/resources/views/tabs/config.php b/src/Modules/WebsiteManager/resources/views/tabs/config.php new file mode 100644 index 0000000..f9c3c98 --- /dev/null +++ b/src/Modules/WebsiteManager/resources/views/tabs/config.php @@ -0,0 +1,20 @@ + [ + 'title' => phpb_trans('website-manager.pages'), + 'include' => __DIR__ . '/pages.php', + ], + 'menus' => [ + 'title' => phpb_trans('website-manager.menus'), + 'include' => __DIR__ . '/menus.php', + ], + 'files' => [ + 'title' => phpb_trans('website-manager.files'), + 'include' => __DIR__ . '/files.php', + ], + 'settings' => [ + 'title' => phpb_trans('website-manager.settings'), + 'include' => __DIR__ . '/settings.php', + ], +]; diff --git a/src/Modules/WebsiteManager/resources/views/tabs/files.php b/src/Modules/WebsiteManager/resources/views/tabs/files.php new file mode 100644 index 0000000..80999aa --- /dev/null +++ b/src/Modules/WebsiteManager/resources/views/tabs/files.php @@ -0,0 +1,44 @@ +
+ +
+ +
+ +
+ <?= phpb_e($file->public_id) ?> +
+ +
+
+ +
+ + diff --git a/src/Modules/WebsiteManager/resources/views/tabs/menus.php b/src/Modules/WebsiteManager/resources/views/tabs/menus.php new file mode 100644 index 0000000..cb8f86c --- /dev/null +++ b/src/Modules/WebsiteManager/resources/views/tabs/menus.php @@ -0,0 +1,91 @@ +getAll(); +?> + +
+ +
+ + + +
+ + +
+ + +
+ +
+ +
+ +
+ +
+ +
+ + diff --git a/src/Modules/WebsiteManager/resources/views/tabs/pages.php b/src/Modules/WebsiteManager/resources/views/tabs/pages.php new file mode 100644 index 0000000..d0896aa --- /dev/null +++ b/src/Modules/WebsiteManager/resources/views/tabs/pages.php @@ -0,0 +1,67 @@ +
+ +
+ +
+ + +
+ + + + + + + + + + + + + + + + + + + +
ID
+ getId()) ?> + + getName()) ?> + + +
+ getRoute()) ?> +
+ +
+ + + + + + + + + + + + +
+
+
+ +
+ + + +
diff --git a/src/Modules/WebsiteManager/resources/views/tabs/settings.php b/src/Modules/WebsiteManager/resources/views/tabs/settings.php new file mode 100644 index 0000000..68ec5e1 --- /dev/null +++ b/src/Modules/WebsiteManager/resources/views/tabs/settings.php @@ -0,0 +1,99 @@ + + +
+ +
+ +
+ + +
+ + +
+ + +
+ +
+ $config): + if(count(Extensions::getSettings($extKey)) === 0){ + continue; + } + ?> +
+ +
+
+ + +
+ + +
+ + +
+ +
+ + +
+
+
+ +
+ + + + + + + 'settings', 'action' => 'renderBlockThumbs']) ?> + + +
+ +
diff --git a/src/Modules/WebsiteManager/resources/views/welcome.php b/src/Modules/WebsiteManager/resources/views/welcome.php new file mode 100644 index 0000000..db0767e --- /dev/null +++ b/src/Modules/WebsiteManager/resources/views/welcome.php @@ -0,0 +1,10 @@ +
+ +

Welcome to PHPageBuilder

+ + + +
diff --git a/src/PHPageBuilder.php b/src/PHPageBuilder.php new file mode 100644 index 0000000..99cc8bb --- /dev/null +++ b/src/PHPageBuilder.php @@ -0,0 +1,567 @@ +setConfig($config); + + // create database connection, if enabled + if (phpb_config('storage.use_database')) { + $this->setDatabaseConnection(phpb_config('storage.database')); + } + + // init the default authentication, if enabled + if (phpb_config('auth.use_login')) { + $this->auth = phpb_instance('auth'); + } + + // init the default website manager, if enabled + if (phpb_config('website_manager.use_website_manager')) { + $this->websiteManager = phpb_instance('website_manager'); + } + + // init the default page builder, active theme and page router + $this->pageBuilder = phpb_instance('pagebuilder'); + + $this->theme = phpb_instance('theme', [ + phpb_config('theme'), + phpb_config('theme.active_theme') + ]); + + $this->router = phpb_instance('router'); + + // load translations in the language that is currently active + $this->loadTranslations(phpb_current_language()); + + // load extensions + $this->loadExtensions(); + } + + /** + * Load translations of the given language into a global variable. + * + * @param $language + * @return array + */ + public function loadTranslations($language) + { + global $phpb_translations; + + $phpbLanguageFile = __DIR__ . '/../lang/' . $language . '.php'; + if (! file_exists($phpbLanguageFile)) { + $phpbLanguageFile = __DIR__ . '/../lang/en.php'; + } + $phpb_translations = require $phpbLanguageFile; + + // load default and current language translations of the current theme + $themeTranslationsFolder = phpb_config('theme.folder') . '/' . phpb_config('theme.active_theme') . '/translations'; + if (file_exists($themeTranslationsFolder . '/en.php')) { + $phpb_translations = array_merge($phpb_translations, require $themeTranslationsFolder . '/en.php'); + } + if (file_exists($themeTranslationsFolder . '/' . $language . '.php')) { + $phpb_translations = array_merge($phpb_translations, require $themeTranslationsFolder . '/' . $language . '.php'); + } + return $phpb_translations; + } + + /** + * Load extensions into a global variable. + * + * @return void + */ + public function loadExtensions() + { + if (file_exists('extensions') && is_dir('extensions')) { + $extensionsDirectory = new DirectoryIterator('extensions'); + foreach ($extensionsDirectory as $entry) { + $extKey = $entry->getFilename(); + $extensionFile = 'extensions/' . $extKey . '/extension.php'; + $configFile = 'extensions/' . $extKey . '/config.php'; + if ($entry->isDir() && ! $entry->isDot() && file_exists($extensionFile) && file_exists($configFile)) { + require $extensionFile; + $extConfig = include($configFile); + Extensions::registerConfig($extKey, $extConfig); + if(array_key_exists('settings', $extConfig) && is_array($extConfig['settings'])){ + Extensions::addSettings(array_map(function ($setting) use($extKey){ + $setting['key'] = 'ext--' . $extKey . '--' . $setting['name']; + return $setting; + }, $extConfig['settings'])); + } + } + + } + } + } + + /** + * Set the PHPageBuilder configuration to the given array. + * + * @param array $config + */ + public function setConfig(array $config) + { + global $phpb_config; + $phpb_config = $config; + } + + /** + * Set the PHPageBuilder database connection using the given array. + * + * @param array $config + */ + public function setDatabaseConnection(array $config) + { + global $phpb_db; + $phpb_db = new DB($config); + } + + /** + * Set a custom auth. + * + * @param AuthContract $auth + */ + public function setAuth(AuthContract $auth) + { + $this->auth = $auth; + } + + /** + * Set a custom website manager. + * + * @param WebsiteManagerContract $websiteManager + */ + public function setWebsiteManager(WebsiteManagerContract $websiteManager) + { + $this->websiteManager = $websiteManager; + } + + /** + * Set a custom PageBuilder. + * + * @param PageBuilderContract $pageBuilder + */ + public function setPageBuilder(PageBuilderContract $pageBuilder) + { + $this->pageBuilder = $pageBuilder; + } + + /** + * Set a custom router. + * + * @param RouterContract $router + */ + public function setRouter(RouterContract $router) + { + $this->router = $router; + } + + /** + * Set a custom theme. + * + * @param ThemeContract $theme + */ + public function setTheme(ThemeContract $theme) + { + $this->theme = $theme; + if (isset($this->pageBuilder)) { + $this->pageBuilder->setTheme($theme); + } + } + + + /** + * Return the Auth instance of this PHPageBuilder. + * + * @return AuthContract + */ + public function getAuth() + { + return $this->auth; + } + + /** + * Return the WebsiteManager instance of this PHPageBuilder. + * + * @return WebsiteManagerContract + */ + public function getWebsiteManager() + { + return $this->websiteManager; + } + + /** + * Return the PageBuilder instance of this PHPageBuilder. + * + * @return PageBuilderContract + */ + public function getPageBuilder() + { + return $this->pageBuilder; + } + + /** + * Return the Router instance of this PHPageBuilder. + * + * @return RouterContract + */ + public function getRouter() + { + return $this->router; + } + + /** + * Return the Theme instance of this PHPageBuilder. + * + * @return ThemeContract + */ + public function getTheme() + { + return $this->theme; + } + + + /** + * Process the current GET or POST request and redirect or render the requested page. + * + * @param string|null $action + * @return bool + */ + public function handleRequest($action = null) + { + $route = $route ?? $_GET['route'] ?? null; + $action = $action ?? $_GET['action'] ?? null; + if (! phpb_config('auth.use_login') || ! phpb_config('website_manager.use_website_manager')) { + die('The PHPageBuilder Authentication module is disabled, but no alternative has been implemented (you are still calling the standard handleRequest() method).
' + . 'Implement a piece of code that checks whether the user is logged in. If logged in, call handleAuthenticatedRequest() or else call handlePublicRequest().'); + } + + // handle login and logout requests + $this->auth->handleRequest($action); + + // handle website manager requests + if (phpb_in_module('website_manager')) { + $this->auth->requireAuth(); + $this->websiteManager->handleRequest($route, $action); + header("HTTP/1.1 404 Not Found"); + die('PHPageBuilder WebsiteManager page not found'); + } + + // handle page builder requests + if (phpb_in_module('pagebuilder')) { + $this->auth->requireAuth(); + phpb_set_in_editmode(); + $this->pageBuilder->handleRequest($route, $action); + header("HTTP/1.1 404 Not Found"); + die('PHPageBuilder PageBuilder page not found'); + } + + // handle all requests that do not need authentication + if ($this->handlePublicRequest()) { + return true; + } + + if (phpb_current_relative_url() === '/') { + $this->websiteManager->renderWelcomePage(); + return true; + } + header("HTTP/1.1 404 Not Found"); + die('PHPageBuilder page not found. Check your URL: ' . phpb_e(phpb_full_url(phpb_current_relative_url())) . ''); + } + + /** + * Handle public requests, allowed without any authentication. + * + * @return bool + */ + public function handlePublicRequest() + { + // if we are on the URL of an upload, return uploaded file + // (note: this is a fallback option used if .htaccess does not whitelist direct access to the /uploads folder. + // allowing direct /uploads access via .htaccess is preferred since it gives faster loading time) + if (strpos(phpb_current_relative_url(), phpb_config('general.uploads_url') . '/') === 0) { + $this->handleUploadedFileRequest(); + header("HTTP/1.1 404 Not Found"); + exit(); + } + // if we are on the URL of a PHPageBuilder asset, return the asset + if (strpos(phpb_current_relative_url(), phpb_config('general.assets_url') . '/') === 0) { + $this->handlePageBuilderAssetRequest(); + header("HTTP/1.1 404 Not Found"); + exit(); + } + + // try to find page in cache + $cache = phpb_instance('cache'); + if (phpb_config('cache.enabled') && + ! isset($_GET['ignore_cache']) && + ! isset($_GET['refresh_cache']) && + ! isset($_COOKIE['ignore_cache']) && + PageRenderer::canBeCached() + ) { + $cachedContent = $cache->getForUrl(phpb_current_relative_url()); + if ($cachedContent) { + echo $cachedContent; + return true; + } + } + + if(Extensions::getRoute(phpb_current_relative_url())){ + $ext = include Extensions::getRoutes()[phpb_current_relative_url()]; + if($ext !== 'continue'){ + return true; + } + } + + // let the page router resolve the current URL + $page = null; + $pageTranslation = $this->resolvePageLanguageVariantFromUrl(phpb_current_relative_url()); + if ($pageTranslation) { + $page = $pageTranslation->getPage(); + } + // if the URL cannot be resolved, but the lowercase version of the URL can be resolved, redirect to the lowercase URL + if (($page->logic ?? '') === 'page-not-found' && phpb_current_relative_url() !== strtolower(phpb_current_relative_url())) { + $pageLowerCaseUrlTranslation = $this->resolvePageLanguageVariantFromUrl(strtolower(phpb_current_relative_url())); + if ($pageLowerCaseUrlTranslation) { + $pageLowerCaseUrl = $pageLowerCaseUrlTranslation->getPage(); + if (($pageLowerCaseUrl->logic ?? '') !== 'page-not-found') { + header("HTTP/1.1 301 Moved Permanently"); + header("Location: " . strtolower(phpb_current_relative_url())); + exit(); + } + } + } + // render page if resolved + if ($page) { + $renderedContent = $this->pageBuilder->renderPage($page, $pageTranslation->locale); + if (strpos($pageTranslation->route, '/*') === false) { + $this->cacheRenderedPage($renderedContent); + } + echo $renderedContent; + return true; + } + return false; + } + + /** + * Resolve a PageTranslation from the given URL. + * + * @param $url + * @return PageTranslationContract|null + */ + protected function resolvePageLanguageVariantFromUrl($url) + { + $pageTranslation = $this->router->resolve($url); + if ($pageTranslation instanceof PageTranslationContract) { + return $pageTranslation; + } + return null; + } + + /** + * Cache the rendered page contents, if caching is enabled and the current page does not contain non-cacheable blocks. + * + * @param string $renderedContent + */ + protected function cacheRenderedPage(string $renderedContent) + { + if (! phpb_config('cache.enabled') || ! PageRenderer::canBeCached() || isset($_GET['ignore_cache'])) { + return; + } + + // allow a forced cached page refresh, stored for the current URL but without the refresh parameter + $url = phpb_current_relative_url(); + $url = str_replace('?refresh_cache&', '?', $url); + $url = str_replace('?refresh_cache', '', $url); + $url = str_replace('&refresh_cache', '', $url); + + $cache = phpb_instance('cache'); + $cache->storeForUrl($url, $renderedContent, phpb_static(PageRenderer::class)::getCacheLifetime()); + } + + /** + * Handle authenticated requests, this method assumes you have checked that the user is currently logged in. + * + * @param string|null $route + * @param string|null $action + */ + public function handleAuthenticatedRequest($route = null, $action = null) + { + $route = $route ?? $_GET['route'] ?? null; + $action = $action ?? $_GET['action'] ?? null; + + // handle website manager requests + if (phpb_config('website_manager.use_website_manager') && phpb_in_module('website_manager')) { + $this->websiteManager->handleRequest($route, $action); + header("HTTP/1.1 404 Not Found"); + exit(); + } + + // handle page builder requests + if (phpb_in_module('pagebuilder')) { + phpb_set_in_editmode(); + $this->pageBuilder->handleRequest($route, $action); + header("HTTP/1.1 404 Not Found"); + exit(); + } + } + + /** + * Handle uploaded file requests. + */ + public function handleUploadedFileRequest() + { + // get the requested file by stripping the configured uploads_url prefix from the current request URI + $file = substr(phpb_current_relative_url(), strlen(phpb_config('general.uploads_url')) + 1); + // $file is in the format {file id}/{file name}.{file extension}, so get file id as the part before / + $fileId = explode('/', $file)[0]; + if (empty($fileId)) { + header("HTTP/1.1 404 Not Found"); + exit(); + } + + $uploadRepository = new UploadRepository; + $uploadedFile = $uploadRepository->findWhere('public_id', $fileId); + if (! $uploadedFile) { + header("HTTP/1.1 404 Not Found"); + exit(); + } + + $uploadedFile = $uploadedFile[0]; + $serverFile = realpath(phpb_config('storage.uploads_folder') . '/' . $uploadedFile->server_file); + // add backwards compatibility for files uploaded with PHPageBuilder <= v0.12.0, stored as /uploads/{id}.{extension} + if (! $serverFile) $serverFile = realpath(phpb_config('storage.uploads_folder') . '/' . basename($uploadedFile->server_file)); + if (! $serverFile) { + header("HTTP/1.1 404 Not Found"); + exit(); + } + + header('Content-Type: ' . $uploadedFile->mime_type); + header('Content-Disposition: inline; filename="' . basename($uploadedFile->original_file) . '"'); + header('Expires: 0'); + header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); + header('Content-Length: ' . filesize($serverFile)); + + readfile($serverFile); + exit(); + } + + /** + * Handle page builder asset requests. + */ + public function handlePageBuilderAssetRequest() + { + // get asset file path by stripping the configured assets_url prefix from the current request URI + $asset = substr(phpb_current_relative_url(), strlen(phpb_config('general.assets_url')) + 1); + $asset = explode('?', $asset)[0]; + + $distPath = realpath(__DIR__ . '/../dist/'); + $requestedFile = realpath($distPath . '/' . $asset); + if (! $requestedFile) { + header("HTTP/1.1 404 Not Found"); + exit(); + } + + // prevent path traversal by ensuring the requested file is inside the dist folder + if (strpos($requestedFile, $distPath) !== 0) { + header("HTTP/1.1 404 Not Found"); + exit(); + } + + // only allow specific extensions + $ext = pathinfo($requestedFile, PATHINFO_EXTENSION); + if (! in_array($ext, ['js', 'css', 'jpg', 'png', 'svg'])) { + header("HTTP/1.1 404 Not Found"); + exit(); + } + + $contentTypes = [ + 'js' => 'application/javascript; charset=utf-8', + 'css' => 'text/css; charset=utf-8', + 'png' => 'image/png', + 'jpg' => 'image/jpeg', + 'svg' => 'image/svg+xml' + ]; + header('Content-Type: ' . $contentTypes[$ext]); + header('Content-Disposition: inline; filename="' . basename($requestedFile) . '"'); + header('Expires: 0'); + header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); + header('Content-Length: ' . filesize($requestedFile)); + + readfile($requestedFile); + exit(); + } + + + /** + * Render the PageBuilder. + * + * @param PageContract $page + */ + public function renderPageBuilder(PageContract $page) + { + phpb_set_in_editmode(); + $this->pageBuilder->renderPageBuilder($page); + } +} diff --git a/src/Page.php b/src/Page.php new file mode 100644 index 0000000..d4cffe3 --- /dev/null +++ b/src/Page.php @@ -0,0 +1,188 @@ +attributes = $data; + } elseif (is_array($data)) { + $this->attributes = is_null($this->attributes) ? [] : $this->attributes; + foreach ($data as $key => $value) { + $this->attributes[$key] = $value; + } + } + } + + /** + * Set the translation data of this page. + * + * @param $translationData + */ + public function setTranslations($translationData) + { + $this->translations = $translationData; + } + + /** + * Return all data stored for this page (page builder data and other data set via setData). + * + * @return array|null + */ + public function getData() + { + return $this->attributes; + } + + /** + * Return the page builder data stored for this page. + * + * @return array|null + */ + public function getBuilderData() + { + return $this->attributes['data'] ?? []; + } + + /** + * Return the id of this page. + * + * @return string + */ + public function getId() + { + return $this->get('id'); + } + + /** + * Return the name of this page. + * + * @return string + */ + public function getName() + { + return $this->get('name'); + } + + /** + * Return the layout (file name) of this page. + * + * @return string + */ + public function getLayout() + { + return $this->get('layout'); + } + + /** + * Return the translated settings of this page. + * + * @return array + */ + public function getTranslations() + { + if (is_null($this->translations)) { + $records = (new PageTranslationRepository)->findWhere(phpb_config('page.translation.foreign_key'), $this->getId()); + $translations = []; + foreach ($records as $record) { + if (in_array($record->locale, array_keys(phpb_active_languages()))) { + $translations[$record->locale] = (array) $record; + } + } + $this->translations = $translations; + } + return $this->translations; + } + + /** + * Return the given language dependant setting for this page, in the current or in the given language. + * + * @param string $setting + * @param string|null $locale + * @return mixed|string|null + */ + public function getTranslation(string $setting, $locale = null) + { + $translations = $this->getTranslations(); + if (empty($translations)) { + return null; + } + $locale = $locale ?? phpb_config('general.language'); + return $translations[$locale][$setting] ?? + $translations['en'][$setting] ?? + $translations[array_keys($translations)[0]][$setting] ?? + null; + } + + /** + * Return the route of this page. + * + * @param string|null $locale + * @return mixed|string|null + */ + public function getRoute($locale = null) + { + $routeTranslation = $this->getTranslation('route', $locale); + foreach (phpb_route_parameters() as $routeParameter => $value) { + $routeTranslation = str_replace('{' . $routeParameter . '}', $value, $routeTranslation); + } + return $routeTranslation; + } + + /** + * Get the value of the given property of this Page. + * + * @param $property + * @return mixed|null + */ + public function get($property) + { + if (property_exists($this, $property)) { + return $this->$property; + } + + if ($this->attributes && is_array($this->attributes)) { + return $this->attributes[$property] ?? null; + } + + return null; + } + + /** + * Invalidate all cached variants of this page. + */ + public function invalidateCache() + { + $cache = phpb_instance('cache'); + + foreach ($this->getTranslations() as $locale => $translationData) { + $languageRoute = $this->getRoute($locale); + $cache->invalidate($languageRoute); + } + } +} diff --git a/src/PageTranslation.php b/src/PageTranslation.php new file mode 100644 index 0000000..9bbcd8f --- /dev/null +++ b/src/PageTranslation.php @@ -0,0 +1,21 @@ +findWithId($this->{$foreignKey}); + } +} diff --git a/src/Repositories/BaseRepository.php b/src/Repositories/BaseRepository.php new file mode 100644 index 0000000..d7636a9 --- /dev/null +++ b/src/Repositories/BaseRepository.php @@ -0,0 +1,244 @@ +db = $phpb_db; + + // apply the configured prefix to the table set in the superclass and remove non-alphanumeric characters + $this->table = phpb_config('storage.database.prefix') . $this->removeNonAlphaNumeric($this->table); + } + + /** + * Create a new instance using the given data. + * + * @param array $data + * @return object|null + */ + protected function create(array $data) + { + $columns = array_keys($data); + foreach ($columns as &$column) { + $column = $this->removeNonAlphaNumeric($column); + } + $columns = implode(', ', $columns); + $questionMarks = implode(', ', array_fill(0, sizeof($data), '?')); + + $this->db->query( + "INSERT INTO {$this->table} ({$columns}) VALUES ({$questionMarks})", + array_values($data) + ); + + $id = $this->db->lastInsertId(); + if ($id) { + return $this->findWithId($id); + } + return null; + } + + /** + * Update the record with the given id with the given updated data. + * + * @param $instance + * @param array $data + * @return bool + */ + protected function update($instance, array $data) + { + $set = ''; + foreach ($data as $column => $value) { + if ($set !== '') { + $set .= ', '; + } + $set .= $this->removeNonAlphaNumeric($column) . '=?'; + } + + $values = array_values($data); + $values[] = $instance->id ?? $instance->getId(); + + return $this->db->query( + "UPDATE {$this->table} SET {$set} WHERE id=?", + $values + ); + } + + /** + * Remove the given instance from the database. + * + * @param $id + * @return bool + */ + public function destroy($id) + { + return $this->db->query( + "DELETE FROM {$this->table} WHERE id=?", + [$id] + ); + } + + /** + * Remove all instances from the database that satisfy the given condition. + * + * @param string $column + * @param $value + * @return bool + */ + public function destroyWhere(string $column, $value) + { + $column = $this->removeNonAlphaNumeric($column); + return $this->db->query( + "DELETE FROM {$this->table} WHERE {$column}=?", + [$value] + ); + } + + /** + * Remove all instances from the database. + * + * @return bool + */ + public function destroyAll() + { + return $this->db->query( + "DELETE FROM {$this->table}" + ); + } + + /** + * Return an array of all pages. + * + * @param array|string $columns + * @return array + */ + public function getAll($columns = '*') + { + if (is_array($columns)) { + foreach ($columns as &$column) { + $column = $this->removeNonAlphaNumeric($column); + } + } + return $this->createInstances($this->db->all($this->table, $columns)); + } + + /** + * Return the instance with the given id, or null. + * + * @param string $id + * @return object|null + */ + public function findWithId($id) + { + return $this->createInstance($this->db->findWithId($this->table, $id)); + } + + /** + * Return the instances for which the given condition holds. + * + * @param string $column do NOT pass user input here + * @param string $value + * @return array + */ + public function findWhere($column, $value) + { + $column = $this->removeNonAlphaNumeric($column); + return $this->createInstances($this->db->select( + "SELECT * FROM {$this->table} WHERE {$column} = ?", + [$value] + )); + } + + /** + * Remove any non-alphanumeric characters. + * + * @param string $string + * @return string|null + */ + protected function removeNonAlphaNumeric(string $string) + { + return preg_replace('/\W*/', '', $string); + } + + /** + * Create an instance using the first record. + * + * @param array $records + * @return object|null + */ + protected function createInstance(array $records) + { + $instances = $this->createInstances($records); + if (empty($instances)) { + return null; + } + return $instances[0]; + } + + /** + * For each record create an instance. + * + * @param array $records + * @return array + */ + protected function createInstances(array $records) + { + $result = []; + + if (empty($this->class)) { + return $records; + } + + foreach ($records as $record) { + $instance = new $this->class; + if (method_exists($instance, 'setData')) { + $data = []; + foreach($record as $k => $v) { + $data[$k] = $v; + } + $instance->setData($data); + } else { + foreach($record as $k => $v) { + $instance->$k = $v; + } + } + $result[] = $instance; + } + + return $result; + } +} diff --git a/src/Repositories/MenuRepository.php b/src/Repositories/MenuRepository.php new file mode 100644 index 0000000..e943c30 --- /dev/null +++ b/src/Repositories/MenuRepository.php @@ -0,0 +1,83 @@ +destroyAll(); + + foreach ($data as $key => $value) { + $this->create([ + 'name' => $key, + 'pages' => $value, + ]); + } + + return true; + } + + /** + * Get one hydrated menu with the given name. + * + * @param string $name + * @return array|null + */ + public function getHydratedMenu(string $name) + { + $pageRepository = new PageRepository; + $pages = $pageRepository->getAll(); + $menu = $this->findWhere('name', $name)[0]; + $menuPages = explode(',',$menu['pages']); + $hyMenuPages = []; + foreach ($pages as $page) { + $key = array_search($page->getId(), $menuPages); + if($key === false) continue; + $hyMenuPages[$key] = [ + 'id' => $page->getId(), + 'title' => $page->getName(), + 'route' => $page->getRoute() + ]; + } + ksort($hyMenuPages); + + $hyMenu = [ + 'name' => $menu['name'], + 'pageIds' => $menu['pages'], + 'pages' => $hyMenuPages, + ]; + return $hyMenu; + } + + /** + * Get all hydrated menus with the given name. + * + * @return array + */ + public function getHydratedMenus() + { + $menus = []; + + foreach ($this->getAll() as $entry){ + $menus[] = $this->getHydratedMenu($entry['name']); + } + + return $menus; + } +} diff --git a/src/Repositories/PageRepository.php b/src/Repositories/PageRepository.php new file mode 100644 index 0000000..6071969 --- /dev/null +++ b/src/Repositories/PageRepository.php @@ -0,0 +1,147 @@ +table = empty(phpb_config('page.table')) ? 'pages' : phpb_config('page.table'); + parent::__construct(); + $this->class = phpb_instance('page'); + } + + /** + * Create a new page. + * + * @param array $data + * @return bool|object|null + * @throws Exception + */ + public function create(array $data) + { + foreach (['name', 'layout'] as $field) { + if (! isset($data[$field]) || ! is_string($data[$field])) { + return false; + } + } + + $page = parent::create([ + 'name' => $data['name'], + 'layout' => $data['layout'], + ]); + if (! ($page instanceof PageContract)) { + throw new Exception("Page not of type PageContract"); + } + return $this->replaceTranslations($page, $data); + } + + /** + * Update the given page with the given updated data. + * + * @param $page + * @param array $data + * @return bool|object|null + */ + public function update($page, array $data) + { + foreach (['name', 'layout'] as $field) { + if (! isset($data[$field]) || ! is_string($data[$field])) { + return false; + } + } + + $this->replaceTranslations($page, $data); + + $updateResult = parent::update($page, [ + 'name' => $data['name'], + 'layout' => $data['layout'], + ]); + $page->invalidateCache(); + return $updateResult; + } + + /** + * Replace the translations of the given page by the given data. + * + * @param PageContract $page + * @param array $data + * @return bool + */ + protected function replaceTranslations(PageContract $page, array $data) + { + $activeLanguages = phpb_active_languages(); + foreach (['title', 'meta_title', 'meta_description', 'route'] as $field) { + foreach ($activeLanguages as $languageCode => $languageTranslation) { + if (! isset($data[$field][$languageCode])) { + return false; + } + } + } + + $pageTranslationRepository = new PageTranslationRepository; + $pageTranslationRepository->destroyWhere(phpb_config('page.translation.foreign_key'), $page->getId()); + foreach ($activeLanguages as $languageCode => $languageTranslation) { + $pageTranslationRepository->create([ + phpb_config('page.translation.foreign_key') => $page->getId(), + 'locale' => $languageCode, + 'title' => $data['title'][$languageCode], + 'meta_title' => $data['meta_title'][$languageCode], + 'meta_description' => $data['meta_description'][$languageCode], + 'route' => $data['route'][$languageCode], + ]); + } + + return true; + } + + /** + * Update the given page with the given updated page data. + * + * @param $page + * @param array $data + * @return bool|object|null + */ + public function updatePageData($page, array $data) + { + $updateResult = parent::update($page, [ + 'data' => json_encode($data), + ]); + $page->invalidateCache(); + return $updateResult; + } + + /** + * Remove the given page from the database. + * + * @param $id + * @return bool + */ + public function destroy($id) + { + $this->findWithId($id)->invalidateCache(); + + return parent::destroy($id); + } +} diff --git a/src/Repositories/PageTranslationRepository.php b/src/Repositories/PageTranslationRepository.php new file mode 100644 index 0000000..62310cf --- /dev/null +++ b/src/Repositories/PageTranslationRepository.php @@ -0,0 +1,32 @@ +table = empty(phpb_config('page.translation.table')) ? 'page_translations' : phpb_config('page.translation.table'); + parent::__construct(); + $this->class = phpb_instance('page.translation'); + } +} diff --git a/src/Repositories/SettingRepository.php b/src/Repositories/SettingRepository.php new file mode 100644 index 0000000..ed79da8 --- /dev/null +++ b/src/Repositories/SettingRepository.php @@ -0,0 +1,41 @@ +destroyAll(); + + + foreach ($data as $key => $value) { + $isArray = is_array($value) ? 1 : 0; + if ($isArray) { + $value = implode(',', $value); + } + $this->create([ + 'setting' => $key, + 'value' => $value, + 'is_array' => $isArray, + ]); + } + + return true; + } +} diff --git a/src/Repositories/UploadRepository.php b/src/Repositories/UploadRepository.php new file mode 100644 index 0000000..5eecf6d --- /dev/null +++ b/src/Repositories/UploadRepository.php @@ -0,0 +1,45 @@ + $data['public_id'], + 'original_file' => $data['original_file'], + 'mime_type' => $data['mime_type'], + 'server_file' => $data['server_file'], + ]); + } +} diff --git a/src/Setting.php b/src/Setting.php new file mode 100644 index 0000000..646bc94 --- /dev/null +++ b/src/Setting.php @@ -0,0 +1,64 @@ +getAll() as $setting) { + if ($setting['is_array'] === 1) { + self::$settings[$setting['setting']] = explode(',', $setting['value']); + } else { + self::$settings[$setting['setting']] = $setting['value']; + } + } + } + + /** + * Return the value(s) of the given setting. + * + * @param string $key + * @return mixed|array|null + */ + public static function get(string $key) + { + if (is_null(self::$settings)) { + self::loadSettings(); + } + + if (isset(self::$settings[$key])) { + return self::$settings[$key]; + } + return null; + } + + /** + * Return whether the given setting exists and has the given value. + * + * @param string $key + * @param string $value + * @return bool + */ + public static function has(string $key, string $value) + { + if (is_null(self::$settings)) { + self::loadSettings(); + } + + return isset(self::$settings[$key]) && ( + (is_array(self::$settings[$key]) && in_array($value, self::$settings[$key])) || + (! is_array(self::$settings[$key]) && self::$settings[$key] === $value) + ); + } +} diff --git a/src/Theme.php b/src/Theme.php new file mode 100644 index 0000000..4e2cea7 --- /dev/null +++ b/src/Theme.php @@ -0,0 +1,192 @@ +config = $config; + $this->themeSlug = $themeSlug; + } + + /** + * Load a single block entry + */ + + protected function attemptBlockRegistration($entry) { + if ($entry->isDir() && ! $entry->isDot()) { + $blockSlug = $entry->getFilename(); + $block = new ThemeBlock($this, $blockSlug); + + $isActive = true; + foreach (($block->get('whitelist') ?? []) as $whitelistDomain) { + $isActive = false; + if (strpos(phpb_current_full_url(), $whitelistDomain) !== false) { + $isActive = true; + break; + } + } + + if ($isActive) { + $this->blocks[$blockSlug] = $block; + } + } + } + + /** + * Load a single extension block entry + */ + + protected function attemptExtensionBlockRegistration($slug, $path) { + if ($slug && $path) { + $block = new ThemeBlock($this, $path, true, $slug); + + $isActive = true; + foreach (($block->get('whitelist') ?? []) as $whitelistDomain) { + $isActive = false; + if (strpos(phpb_current_full_url(), $whitelistDomain) !== false) { + $isActive = true; + break; + } + } + + if ($isActive) { + $this->blocks[$slug] = $block; + } + } + } + + /** + * Load a single layout entry + */ + + protected function attemptLayoutRegistration($entry) { + if ($entry->isDir() && ! $entry->isDot()) { + $layoutSlug = $entry->getFilename(); + $layout = new ThemeLayout($this, $layoutSlug); + $this->layouts[$layoutSlug] = $layout; + } + } + + /** + * Load a single layout entry + */ + + protected function attemptExtensionLayoutRegistration($slug, $path) { + $layout = new ThemeLayout($this, $path, true, $slug); + $this->layouts[$slug] = $layout; + } + + /** + * Load all blocks of the current theme. + */ + protected function loadThemeBlocks() + { + $this->blocks = []; + + $folders = [ + '', + '/archived', + '/elements', + '/php', + ]; + foreach ($folders as $folder) { + if (file_exists($this->getFolder() . '/blocks' . $folder)) { + $blocksDirectory = new DirectoryIterator($this->getFolder() . '/blocks' . $folder); + foreach ($blocksDirectory as $entry) { + // skip special subfolders containing blocks + if (in_array('/' . $entry, $folders)) { + continue; + } + $this->attemptBlockRegistration($entry); + } + } + } + + foreach (Extensions::getBlocks() as $slug => $path) { + $this->attemptExtensionBlockRegistration($slug, $path); + } + } + + /** + * Load all layouts of the current theme. + */ + protected function loadThemeLayouts() + { + $this->layouts = []; + + if (file_exists($this->getFolder() . '/layouts')) { + $layoutsDirectory = new DirectoryIterator($this->getFolder() . '/layouts'); + foreach ($layoutsDirectory as $entry) { + $this->attemptLayoutRegistration($entry); + } + } + + foreach (Extensions::getLayouts() as $slug => $path) { + $this->attemptExtensionLayoutRegistration($slug, $path); + } + } + + /** + * Return all blocks of this theme. + * + * @return array array of ThemeBlock instances + */ + public function getThemeBlocks() + { + $this->loadThemeBlocks(); + return $this->blocks; + } + + /** + * Return all layouts of this theme. + * + * @return array array of ThemeLayout instances + */ + public function getThemeLayouts() + { + $this->loadThemeLayouts(); + return $this->layouts; + } + + /** + * Return the absolute folder path of the theme passed to this Theme instance. + * + * @return string + */ + public function getFolder() + { + return $this->config['folder'] . '/' . basename($this->themeSlug); + } +} diff --git a/src/ThemeBlock.php b/src/ThemeBlock.php new file mode 100644 index 0000000..a8ea951 --- /dev/null +++ b/src/ThemeBlock.php @@ -0,0 +1,365 @@ +theme = $theme; + $this->blockSlug = $blockSlug; + $this->isExtension = $isExtension; + $this->extensionSlug = $extensionSlug; + + $this->config = []; + if (file_exists($this->getFolder() . '/config.php')) { + $this->config = require $this->getFolder() . '/config.php'; + } + + PageRenderer::setCanBeCached( + boolval($this->config['cache'] ?? true), + $this->config['cache_lifetime'] ?? null + ); + } + + /** + * Return the absolute folder path of this theme block. + * + * @return string + */ + public function getFolder() + { + if ($this->isExtension) { + return $this->blockSlug; + } + $folder = $this->theme->getFolder() . '/blocks/archived/' . basename($this->blockSlug); + if (file_exists($folder)) { + return $folder; + } + $folder = $this->theme->getFolder() . '/blocks/elements/' . basename($this->blockSlug); + if (file_exists($folder)) { + return $folder; + } + $folder = $this->theme->getFolder() . '/blocks/php/' . basename($this->blockSlug); + if (file_exists($folder)) { + return $folder; + } + return $this->theme->getFolder() . '/blocks/' . basename($this->blockSlug); + } + + /** + * Return the namespace to the folder of this theme block. + * + * @return string + */ + protected function getNamespace() + { + // return Namespace from the Config file of the Block if it is an extension. Used for Extensions. + if (isset( $this->config['namespace'])) { + return $this->config['namespace']; + } + + // return Namespace from Config file if exists; + if (phpb_config('theme.namespace')) { + return phpb_config('theme.namespace'); + } + + // get namespace from directory structure if not provided: + $themesPath = phpb_config('theme.folder'); + $themesFolderName = basename($themesPath); + $blockFolder = $this->getFolder(); + $namespacePath = $themesFolderName . str_replace($themesPath, '', $blockFolder); + + // convert each character after a - to uppercase + $namespace = implode('-', array_map('ucfirst', explode('-', $namespacePath))); + // convert each character after a _ to uppercase + $namespace = implode('_', array_map('ucfirst', explode('-', $namespace))); + // convert each character after a / to uppercase + $namespace = implode('/', array_map('ucfirst', explode('/', $namespace))); + // remove all dashes + $namespace = str_replace('-', '', $namespace); + // remove all underscores + $namespace = str_replace('_', '', $namespace); + // replace / by \ + $namespace = str_replace('/', '\\', $namespace); + + return $namespace; + } + + /** + * Return the controller class of this theme block. + * + * @return string + */ + public function getControllerClass() + { + if (file_exists($this->getFolder() . '/controller.php')) { + return $this->getNamespace() . '\\Controller'; + } + return BaseController::class; + } + + /** + * Return the controller file of this theme block. + * + * @return string|null + */ + public function getControllerFile() + { + if (file_exists($this->getFolder() . '/controller.php')) { + return $this->getFolder() . '/controller.php'; + } + return null; + } + + /** + * Return the model class of this theme block. + * + * @return string + */ + public function getModelClass() + { + if (file_exists($this->getFolder() . '/model.php')) { + return $this->getNamespace() . '\\Model'; + } + return BaseModel::class; + } + + /** + * Return the model file of this theme block. + * + * @return string|null + */ + public function getModelFile() + { + if (file_exists($this->getFolder() . '/model.php')) { + return $this->getFolder() . '/model.php'; + } + return null; + } + + /** + * Return the view file of this theme block. + * + * @return string + */ + public function getViewFile() + { + if ($this->isPhpBlock()) { + return $this->getFolder() . '/view.php'; + } + return $this->getFolder() . '/view.html'; + } + + /** + * Return the pagebuilder script file of this theme block. + * This script can be used to assist correct rendering of the block in the pagebuilder. + * + * @return string|null + */ + public function getBuilderScriptFile() + { + if (file_exists($this->getFolder() . '/builder-script.php')) { + return $this->getFolder() . '/builder-script.php'; + } elseif (file_exists($this->getFolder() . '/builder-script.html')) { + return $this->getFolder() . '/builder-script.html'; + } elseif (file_exists($this->getFolder() . '/builder-script.js')) { + return $this->getFolder() . '/builder-script.js'; + } + return $this->getScriptFile(); + } + + /** + * Return the script file of this theme block. + * This script can be used to assist correct rendering of the block when used on a publicly accessed web page. + * + * @return string|null + */ + public function getScriptFile() + { + if (file_exists($this->getFolder() . '/script.php')) { + return $this->getFolder() . '/script.php'; + } elseif (file_exists($this->getFolder() . '/script.html')) { + return $this->getFolder() . '/script.html'; + } elseif (file_exists($this->getFolder() . '/script.js')) { + return $this->getFolder() . '/script.js'; + } + return null; + } + + /** + * Return the file path of the thumbnail of this block. + * + * @return string + */ + public function getThumbPath() + { + $blockThumbsFolder = $this->theme->getFolder() . '/public/block-thumbs/'; + return $blockThumbsFolder . md5($this->blockSlug) . '/' . md5(file_get_contents($this->getViewFile())) . '.jpg'; + } + + public function getThumbUrl() + { + return phpb_theme_asset('block-thumbs/' . md5($this->blockSlug) . '/' . md5(file_get_contents($this->getViewFile())) . '.jpg'); + } + + /** + * Return the slug identifying this type of block. + * + * @return string + */ + public function getSlug() + { + return (! $this->isExtension) ? $this->blockSlug : $this->extensionSlug; + } + + /** + * Return whether this block is a block containing/allowing PHP code. + * + * @return bool + */ + public function isPhpBlock() + { + return file_exists($this->getFolder() . '/view.php'); + } + + /** + * Return whether this block is a plain html block that does not contain/allow PHP code. + * + * @return bool + */ + public function isHtmlBlock() + { + return (! $this->isPhpBlock()); + } + + /** + * The wrapper element to be used in the pagebuilder and for carrying style in case this block is a PHP block. + */ + public function getWrapperElement() + { + return $this->config['wrapper'] ?? 'div'; + } + + /** + * Return configuration with the given key (as dot-separated multidimensional array selector). + * + * @param $key + * @return mixed + */ + public function get($key = null) + { + if (empty($key)) { + return $this->config; + } + // if no dot notation is used, return first dimension value or empty string + if (strpos($key, '.') === false) { + return $this->config[$key] ?? null; + } + + // if dot notation is used, traverse config string + $segments = explode('.', $key); + $subArray = $this->config; + foreach ($segments as $segment) { + if (isset($subArray[$segment])) { + $subArray = &$subArray[$segment]; + } else { + return null; + } + } + + return $subArray; + } + + /** + * Replace configuration at the given key (as dot-separated multidimensional array selector) by the given value. + * + * @param $slug + * @param $key + * @param $value + * @return void + */ + public static function set($slug, $key, $value) + { + if (empty($key)) { + self::$dynamicConfig[$slug] = $value; + return; + } + // if no dot notation is used, replace first dimension value or empty string + if (strpos($key, '.') === false) { + self::$dynamicConfig[$slug][$key] = $value; + return; + } + + // if dot notation is used, traverse config and replace at the right depth + $segments = explode('.', $key); + $subArray = &self::$dynamicConfig[$slug]; + foreach ($segments as $i => $segment) { + if (isset($subArray[$segment])) { + if ($i === count($segments) - 1) { + $subArray[$segment] = $value; + } else { + $subArray = &$subArray[$segment]; + } + } else { + return; + } + } + } + + /** + * Get all dynamic configuration of the block with the given slug. + * + * @param $slug + * @return mixed + */ + public static function getDynamicConfig($slug) + { + return self::$dynamicConfig[$slug] ?? null; + } +} diff --git a/src/ThemeLayout.php b/src/ThemeLayout.php new file mode 100644 index 0000000..01c85ac --- /dev/null +++ b/src/ThemeLayout.php @@ -0,0 +1,121 @@ +theme = $theme; + $this->layoutSlug = $layoutSlug; + $this->isExtension = $isExtension; + $this->extensionSlug = $extensionSlug; + + $this->config = []; + if (file_exists($this->getFolder() . '/config.php')) { + $this->config = include $this->getFolder() . '/config.php'; + } + } + + /** + * Return the absolute folder path of this theme layout. + * + * @return string + */ + public function getFolder() + { + return (! $this->isExtension) ? ($this->theme->getFolder() . '/layouts/' . $this->layoutSlug) : $this->layoutSlug; + } + + /** + * Return the view file of this theme layout. + * + * @return string + */ + public function getViewFile() + { + return $this->getFolder() . '/view.php'; + } + + /** + * Return the slug identifying this type of layout. + * + * @return string + */ + public function getSlug() + { + return !$this->isExtension ? $this->layoutSlug : $this->extensionSlug; + } + + /** + * Return the title of this theme layout. + * + * @return string + */ + public function getTitle() + { + return $this->get('title') ?? ucfirst($this->getSlug()); + } + + /** + * Return configuration with the given key (as dot-separated multidimensional array selector). + * + * @param $key + * @return mixed|string + */ + public function get($key) + { + // if no dot notation is used, return first dimension value or empty string + if (strpos($key, '.') === false) { + return $this->config[$key] ?? null; + } + + // if dot notation is used, traverse config string + $segments = explode('.', $key); + $subArray = $this->config; + foreach ($segments as $segment) { + if (isset($subArray[$segment])) { + $subArray = &$subArray[$segment]; + } else { + return null; + } + } + + return $subArray; + } +} diff --git a/src/UploadedFile.php b/src/UploadedFile.php new file mode 100644 index 0000000..27cab6f --- /dev/null +++ b/src/UploadedFile.php @@ -0,0 +1,14 @@ +public_id . '/' . $this->original_file); + } +} diff --git a/tailwind.config.js b/tailwind.config.js new file mode 100644 index 0000000..a1492fa --- /dev/null +++ b/tailwind.config.js @@ -0,0 +1,18 @@ +/** @type {import('tailwindcss').Config} */ +module.exports = { + content: [ + "./src/Modules/Auth/**/*.{html,js,php}", + "./src/Modules/WebsiteManager/**/*.{html,js,php}", + ], + theme: { + extend: {}, + }, + plugins: [ + require("daisyui") + ], + daisyui: { + themes: ["lemonade","forest","cupcake"], + darkTheme: "lemonade", + } +} +