MarkupSitemap.module.php 11.2 KB
Newer Older
Mike Rockétt's avatar
init  
Mike Rockétt committed
1 2
<?php

3 4 5 6 7 8 9 10 11 12
/**
 * Sitemap for ProcessWire
 *
 * Module class
 *
 * @author Mike Rockett
 * @copyright 2017
 * @license MIT
 */

Mike Rockétt's avatar
init  
Mike Rockétt committed
13 14 15 16
require_once __DIR__ . '/vendor/autoload.php';

use Thepixeldeveloper\Sitemap\Output;
use Thepixeldeveloper\Sitemap\Subelements\Link;
17
use Thepixeldeveloper\Sitemap\Subelements\Image;
Mike Rockétt's avatar
init  
Mike Rockétt committed
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
use Thepixeldeveloper\Sitemap\Url;
use Thepixeldeveloper\Sitemap\Urlset;

class MarkupSitemap extends WireData implements Module
{
    /**
     * LanguageSupport module name
     */
    const LANGUAGE_SUPPORT_PAGE_NAMES_MODULE = 'LanguageSupportPageNames';

    /**
     * MarkupCache module name
     */
    const MARKUP_CACHE_MODULE = 'MarkupCache';

    /**
     * MultiSite module name
     */
    const MULTI_SITE_MODULE = 'MultiSite';

    /**
     * Sitemap URI
     */
    const SITEMAP_URI = '/sitemap.xml';

    /**
     * Language
     * @var string
     */
    protected $lang = '';

    /**
     * Current request URI
     * @var string
     */
    protected $requestUri = '';

    /**
     * Page selector
     * @var string
     */
    protected $selector = '';

    /**
     * Subdomain (multi-site support)
     * @var string
     */
    protected $subdomain = '';

    /**
     * This UrlSet
     * @var Urlset
     */
    protected $urlSet;

    /**
     * Install module
75 76
     * 1) Install MarkupCache
     * 2) Install new system fields
Mike Rockétt's avatar
init  
Mike Rockétt committed
77 78 79 80
     * @return void
     */
    public function ___install()
    {
81 82 83 84
        // Install MarkupCache
        $this->modules->{self::MARKUP_CACHE_MODULE};

        // Create Fieldset (open)
Mike Rockétt's avatar
init  
Mike Rockétt committed
85
        $this->createField('FieldsetOpen', 'sitemap_fieldset', [
86
            'label' => $this->_('Sitemap'),
87
            'description' => $this->_('These options are specific to Sitemap, and allow you to select whether or not this Page (and, optionally, its children) should be rendered in the sitemap.'),
Mike Rockétt's avatar
init  
Mike Rockétt committed
88 89 90 91
            'icon' => 'sitemap',
            'collapsed' => Inputfield::collapsedBlank,
        ], true);

92
        // Create ignore-page field
Mike Rockétt's avatar
init  
Mike Rockétt committed
93 94
        $this->createField('Checkbox', 'sitemap_ignore_page', [
            'label' => $this->_('Exclude Page'),
95
            'label2' => $this->_('Do not render include this Page in sitemap.xml'),
Mike Rockétt's avatar
init  
Mike Rockétt committed
96 97
        ], true);

98
        // Create ignore-children field
Mike Rockétt's avatar
init  
Mike Rockétt committed
99 100
        $this->createField('Checkbox', 'sitemap_ignore_children', [
            'label' => $this->_('Exclude Children'),
101
            'label2' => $this->_('Do not include this Page’s children (if any) in sitemap.xml'),
Mike Rockétt's avatar
init  
Mike Rockétt committed
102 103
            'notes' => $this->_('This option is independent of the option above which, if not checked, means that only this page’s children will be excluded when this option is checked.'),
        ], true);
104

105
        // Create Fieldset (close)
106 107 108
        $this->createField('FieldsetClose', 'sitemap_fieldset_END', [
            'label' => $this->_('Close Sitemap'),
        ], true);
Mike Rockétt's avatar
init  
Mike Rockétt committed
109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160
    }

    /**
     * Uninstall module
     * @return void
     */
    public function ___uninstall()
    {
        $fields = $this->fields;
        foreach (MarkupSitemapConfig::getDefaultFields() as $fieldName) {
            foreach ($this->templates as $template) {
                if (!$template->hasField($fieldName)) {
                    continue;
                }
                $templateFields = $template->fields;
                $templateFields->remove($fieldName);
                $templateFields->save();
            }
            $field = $fields->get($fieldName);
            $field->flags = Field::flagSystemOverride;
            $field->flags = 0;
            $fields->delete($field);
        }
    }

    /**
     * Class constructor
     */
    public function __construct()
    {
        $this->requestUri = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : null;
    }

    /**
     * Initiate the module
     * @return void
     */
    public function init()
    {
        // If the request is valid (/sitemap.xml)...
        if ($this->isValidRequest()) {
            // Add the relevant page hooks for multi-language support
            // as these are not bootstrapped at the 404 event (for some reason...)
            if ($this->modules->isInstalled(self::LANGUAGE_SUPPORT_PAGE_NAMES_MODULE)) {
                foreach (['localHttpUrl', 'localName'] as $pageHook) {
                    $pageHookFunction = 'hookPage' . ucfirst($pageHook);
                    $this->addHook("Page::{$pageHook}", null, function ($event) use ($pageHookFunction) {
                        $this->modules->{self::LANGUAGE_SUPPORT_PAGE_NAMES_MODULE}->{$pageHookFunction}($event);
                    });
                }
            }
            // Add the hook to process and render the sitemap.
161
            $this->addHookAfter('ProcessPageView::pageNotFound', $this, 'render');
Mike Rockétt's avatar
init  
Mike Rockétt committed
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223
        }

        // Add a hook that moves the XML Sitemap fields to the Settings tab
        $this->addHookAfter('ProcessPageEdit::buildForm', $this, 'moveSitemapFields');
    }

    /**
     * Move sitemap fields
     * @param HookEvent $event
     */
    public function moveSitemapFields(HookEvent $event)
    {
        // Get the form
        $form = $event->return;

        // Loop through the sitemap fields and move them to just before
        // the status field.
        foreach (MarkupSitemapConfig::getDefaultFields() as $fieldName) {
            $field = $form->find("name={$fieldName}")->first();
            if ($field) {
                $settings = $form->find("name=status")->first();
                if ($settings) {
                    $form->remove($field);
                    $form->insertBefore($field, $settings);
                }
            }
        }
    }

    /**
     * Render the sitemap
     * @param HookEvent $event
     */
    public function render(HookEvent $event)
    {
        // Get the initial root URI.
        $rootPage = $this->getRootPageUri();

        // If multi-site is present and active, prepend the subdomain prefix.
        if ($this->modules->isInstalled(self::MULTI_SITE_MODULE)) {
            $multiSite = $this->modules->get(self::MULTI_SITE_MODULE);
            if ($multiSite->subdomain) {
                $rootPage = "/{$multiSite->subdomain}{$rootPage}";
            }
        }

        // Make sure that the root page exists.
        if ($this->pages->get($rootPage) instanceof NullPage) {
            return;
        }

        // Check for cached sitemap or regenerate if it doesn't exist
        $rootPageName = $this->sanitizer->pageName($rootPage);
        $markupCache = $this->modules->{self::MARKUP_CACHE_MODULE};
        if (!$output = $markupCache->get('MarkupSitemap', 3600)) {
            $this->urlSet = new Urlset();
            $this->addUrls($this->pages->get($rootPage));
            $sitemapOutput = new Output();
            $output = $sitemapOutput->setIndented(true)->getOutput($this->urlSet);
            $markupCache->save($output);
        }
        header('Content-Type: text/xml', true, 200);
224
        $event->return = $output;
Mike Rockétt's avatar
init  
Mike Rockétt committed
225 226 227 228 229 230 231
    }

    /**
     * @param $page
     */
    protected function addUrls($page)
    {
232

Mike Rockétt's avatar
init  
Mike Rockétt committed
233 234 235 236 237 238 239 240 241 242 243 244 245 246 247
        // Add this page
        if ($page->viewable() && ($page->sitemap_ignore_page == false || $page->path === '/')) {
            $url = new Url($page->httpUrl);
            $url->setLastMod(date('c', $page->modified));
            // Add multi-language alternates (if available)
            if ($this->modules->isInstalled(self::LANGUAGE_SUPPORT_PAGE_NAMES_MODULE)) {
                foreach ($this->languages as $language) {
                    if (!$language->isDefault() && !$page->{"status{$language->id}"}) {
                        continue;
                    }
                    $languageIsoName = $this->pages->get(1)->localName($language);
                    $alternateLink = new Link($languageIsoName, $page->localHttpUrl($language));
                    $url->addSubElement($alternateLink);
                }
            }
248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278

            // Check for images to add to this entry
            foreach ($this->sitemap_image_fields as $imageFieldName) {
                $page->of(false);
                $imageField = $page->$imageFieldName;
                if (!$imageField) continue;
                foreach ($imageField as $image) {
                    $imageLink = new Image($image->httpUrl);
                    foreach ([
                        'Caption' => 'description',
                        'License' => 'license',
                        'Title' => 'title',
                        'GeoLocation' => 'geo|location|geolocation',
                    ] as $imageMetaMethod => $imageMetaValues) {
                        foreach (explode('|', $imageMetaValues) as $imageMetaValue) {
                            if ($imageMetaMethod === 'License') {
                                if (!filter_var($image->$imageMetaValue, FILTER_VALIDATE_URL)) {
                                    continue;
                                }
                            }
                            if ($image->$imageMetaValue) {
                                $setImageLinkMeta = "set{$imageMetaMethod}";
                                $imageLink->{$setImageLinkMeta}($image->$imageMetaValue);
                            }
                        }
                    }
                    $url->addSubElement($imageLink);
                }
            }

            // Finally, add the url to the set
Mike Rockétt's avatar
init  
Mike Rockétt committed
279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357
            $this->urlSet->addUrl($url);
        }

        // Check for children if allowed
        if ($page->sitemap_ignore_children != true) {
            $children = $page->children($this->selector);
            if (count($children)) {
                foreach ($children as $child) {
                    $this->addUrls($child);
                }
            }
        }

        // Always return true
        return true;
    }

    /**
     * Given a fieldtype, name, and attributes, create and save a new Field.
     * @param  string       $fieldType
     * @param  string       $name
     * @param  array        $meta
     * @return Field|bool
     */
    protected function createField($fieldType, $name, $meta, $system = false)
    {
        if ($this->fields->get($name)) {
            return false;
        }

        // Set the initial properties
        $field = new Field();
        $fieldType = "Fieldtype{$fieldType}";
        $field->type = $this->modules->$fieldType;
        $field->name = $name;
        if ($system === true) {
            $field->set('flags', Field::flagSystem);
        }

        // Unset extra meta (already used)
        unset($meta['type']);
        unset($meta['name']);

        // Add meta
        foreach ($meta as $metaNames => $metaInfo) {
            $metaNames = explode('+', $metaNames);
            foreach ($metaNames as $metaName) {
                $field->$metaName = $metaInfo;
            }
        }

        $field->save();

        return $field;
    }

    /**
     * Get the root page URI
     * @return string
     */
    protected function getRootPageUri()
    {
        return (string) str_ireplace(trim($this->config->urls->root, '/'), '', $this->sanitizer->path(dirname($this->requestUri)));
    }

    /**
     * Determine if the request is valud
     * @return boolean
     */
    protected function isValidRequest()
    {
        $valid = (bool) (
            $this->requestUri !== null &&
            strlen($this->requestUri) - strlen(self::SITEMAP_URI) === strrpos($this->requestUri, self::SITEMAP_URI)
        );

        return $valid;
    }
}