Pete

Module
Module: XML Sitemap

123 posts in this topic

I missed the XML sitemap generator that I used in a previous CMS so I built my own module to achieve the same functionality.

This module outputs an XML sitemap of your site that is readable by Google Webmaster Tools etc. I've generally found that it reduces the time it takes for new sites and pages to be listed in search engines using one in combination with Webmaster Tools etc (since you're specifically telling the service that a new site/new pages exist) so thought I may as well create a module for it.

The module ignores any hidden pages and their children, assuming that since you don't want these to be visible on the site then you don't want them to be found via search engines either.

It also adds a field called sitemap_ignore that you can add to your templates and exclude specific pages on a per-page basis. Again, this assumes that you wish to ignore that page's children as well.

The sitemap is accessible at yoursite.com/sitemap.xml - the module checks to see whether this URL has been called and outputs the sitemap, then does a hard exit before PW gets a chance to output a 404 page. If there's a more elegant way of doing this I'll happily change the code to suit.

Feedback and suggestions welcome :)

On a slightly different note, I wanted to call the file XMLSitemap originally so as to be clearer about what it does in the filename, but if you have a module that begins with more than one uppercase letter then a warning containing only the module name is displayed on the Modules page, so I changed it to Sitemap instead which is fine as the description still says what it does.

File can be downloaded via GitHub here: https://github.com/N.../zipball/master

7 people like this

Share this post


Link to post
Share on other sites

Here's a list of services you can submit your sitemap to:

Google Webmaster Tools

Bing Webmaster Tools

There used to be a service for Yahoo called Site Explorer that was similar in functionality to the above two services, but it appears that this has now been replaced with Bing's offering. On the bright side it's one less service to sign up to :)

You can also submit to Ask using the following URL (replacing the relevant part with the full URL to your sitemap):

http://submissions.ask.com/ping?sitemap=http://www.the URL of your sitemap here.xml

Generally I find Google and Bing to be sufficient though, as the other search services seem to trawl their content reasonably quickly and find out about new sites that way sometimes I think.

1 person likes this

Share this post


Link to post
Share on other sites

It is also recommended to add the following to your robots.txt file (create one if you don't have one):

Sitemap: http://www.your-domain.com/sitemap.xml

This allows search engines to find your sitemap.xml, even if you didn't submit it to that specific search engine.

Regarding this module, until now I've always used a sitemap.xml template. When I created that one I used the regular sitemap page as an example.

But I will certainly try this module sooner or later.  :)

/Jasper

Share this post


Link to post
Share on other sites

That's actually how I began this module - as a separate template - but then I thought it would be quicker as a module and then there's no need for an actual page or any templates and it's all in one file.

Plus I really wanted to have that optional sitemap_ignore field that I'd used in the previous CMS I worked with.

I'm glad I did start creating it as a template and page though, else I'd have had more hassle working out why it wasn't outputting XML (I needed to specify that XML was being outputted by using a PHP header).

Share this post


Link to post
Share on other sites

Pete, nice job with this module, it looks very well put together and provides a helpful function. I like the simplicity of it being a module and how easy that makes installation. But there are a couple potential issues with this approach I wanted to mention.

First is that it's taking the place of the 404 page and a 404 header is getting sent before the sitemap.xml output is displayed. This will probably be an issue for any search engines that hit it. You can avoid this by moving everything from your generateSitemap() function into your init() function. You don't need to use any hooks. Of course, you won't have a $page to check at the init() stage, but I don't think you need it–just get rid of the $page->template != 'admin' check... your strpos() below it is likely just as fast.

Next concern is scalability. Generating this sitemap could be a slow thing on a large site. Anything that's slow to generate can be a DDOS hole. Because it's in a module, you can't as easily cache the output with a template setting. However, you could use the MarkupCache module to perform your own caching, and that's something I'd probably recommend here.

Last thing is that I'd suggest renaming the module since it falls in the Markup group of modules. Perhaps the name MarkupSitemapXML?

Other than that, I think it looks great.

Share this post


Link to post
Share on other sites

Thanks ryan - I was a bit worried about the 404 so this is a good solution and something I'll definitely bear in mind for future modules. I enjoy writing these modules as every one teaches me something new about how PW works behind the scenes.

I've implemented your suggestions and replaced the file in the first post with the modified version with the new name (if anyone has this installed already, simply uninstall the old module, delete the module file and install the new one).

I also implemented caching as you suggested and cached it for an hour (for most sites a day or more would probably be fine, but if you're writing articles or running a blog you want search engines to index your content as soon as possible so that seemed like a good period to set it at thoguh I've no idea how often search engines actually check a sitemap).

I agree that there are quite a few potential issues on larger sites and not just because of the sitemap's size. Google doesn't always index everything on larger sites, and I was just reading about how someone tested this by telling Google that things like news posts and forum posts (individual posts, not threads) should on;y be indexed once as they're unlikely to ever change. This apparently frees up the search engine crawlers to check the new content rather than go over the same content each visit.

I can see a few places that this would be useful in PW - for example a news section would only need each article to be indexed once (if you ever went back and edited a page, I believe the last modified date would force a re-index) and various other similar examples.

There's a good list of tags for sitemaps here: http://support.google.com/webmasters/bin/answer.py?hl=en&answer=183668 and the tag to use would be <changefreq> , however that could get a bit tiresome if you had to have it on every page. A potential solution for a future version of this module would be to have such a field and simply have all child pages inherit the parent value if they don't have one set themselves.

Another option as a possible alternative to caching would be to run the module once on the first time the page is called, then only re-generate the sitemap once a page is edited/created/deleted as those are the only three times a change to the sitemap would technically be required.

I'll leave it as it is for now though.

Share this post


Link to post
Share on other sites

I forgot to ask - is there a better way of having a module run when an admin-only page is loaded other than this:

<?php
if ($page->template != 'admin') {
 // Do stuff
}
?>

It's no longer relevant for this module as it now runs before the page data is available, but when I had it in the first version I gave myself a pat on the back for figuring I could check for the admin template like this. I can see how such a check would be good for other modules though so just wondering if there's a better way for checking if we're in the admin.

Share this post


Link to post
Share on other sites

You also could use a Sitemap Index (<sitemapindex>) which allows you to have multiple sitemaps per site.

This allows you to break your sitemap up into several smaller sitemaps. You could even have different cache times per branch, eg. 5 minutes for the news section and 1 day for the other pages.

/Jasper

Share this post


Link to post
Share on other sites

Very good point - I'd completely forgotten about that!

One of the forum applications I use has this though I'm quite far behind on the versions. I believe they had one for forums, one for posts, one for calendars etc. It would have made more sense for them to split up posts by forum though as it gets a bit silly if it tries to put a million posts in one file (I don't have that problem fortunately ;)).

So thinking about this a bit more, it would make sense to have some template settings for this module too in a future version and specify cache times and re-index periods for all pages there. It could then create separate sitemaps on a per-template basis as you say. I think that would cover most eventualities there.

My only gripe would be that caching per-template wouldn't help if you were running a large blog/news site as one main template would apply to most of the content. Perhaps splitting it per year, or simply having it split the sitemap at X thousand pages if you have a huge amount of articles? I think per-year sitemaps for larger article sections would be best thinking about it. Presumably if a page from 2009 is modified and then ends up in the 2012 sitemap it's not a big issue - Google will be told in 2012 sitemap to index it again and it's not like you're going to modify old articles particularly often so I wouldn't see a need in cleaning up the 2009 cached sitemap in this case.

It does look like you can easily have a master sitemap linking to sub-sitemaps though so that part is pretty straightforward at least (and it looks like 50,00 pages per sitemap is the maximum allowed): http://googlewebmastercentral.blogspot.com/2006/10/multiple-sitemaps-in-same-directory.html

Anyway, this is one for when I next get a few free hours ;)

Share this post


Link to post
Share on other sites

Great update, thanks Pete!

What do you think about putting this on GitHub? (whether now or in the future)?

For the cache time, you could always make it configurable with the module if you wanted to. Let me know if I can assist.

I also like your alternative for time based caching, though I'm guessing time based caching is adequate for most. But if you want to pursue that alternative, you'd use the CacheFile class directly and have a Pages::save hook clear the cache file (or maybe just Pages::added and Pages::deleted hooks).

I wasn't aware of the <sitemapindex>, this sounds like a good idea for the large sites. But also sounds like a much more complex module.

Share this post


Link to post
Share on other sites

Cheers ryan

Forgot I had a Github account for a sec there. Added, updated the link in the first thread and added it to the growing modules spreadsheet on Google Docs ;)

Yup - I'll probably make the time configurable at some point in the future as it seems like an easy interim update before doing anything more complicated.

Share this post


Link to post
Share on other sites

Nice job Pete. It's easier to follow on GitHub just because we can pull in updates automatically without downloading, unzipping, etc. So many great new modules lately. I need to make a lot of additions to the modules directory.

Share this post


Link to post
Share on other sites

Mine is throwing an error:

Exception: Unable to create path: /MarkupSitemapXML/ (in /home/theseeke/public_html/wire/core/CacheFile.php line 62)
This error message was shown because you are logged in as a Superuser. Error has been logged.

From a quick read of the relevant modules, it's not apparent to me where it's trying to create that directory.

Share this post


Link to post
Share on other sites

It sounds like your site/assets/cache directory might not be writeable (it needs to be in order to be able to cache the sitemap). Hopefully making that writeable (CHMOD 644 probably) will fix that.

The cache folder itself isn't solely related to this module, so I'm sure you would have come across that message sooner or later.

Hope that fixes it for you :)

Share this post


Link to post
Share on other sites

It sounds like your site/assets/cache directory might not be writeable (it needs to be in order to be able to cache the sitemap). Hopefully making that writeable (CHMOD 644 probably) will fix that.

The cache folder itself isn't solely related to this module, so I'm sure you would have come across that message sooner or later.

Hope that fixes it for you :)

No such luck - still didn't work. Also tried 755 and 777 on the off chance, and recursed it through that whole tree to be sure.

Incidentally, file uploads and caching of size()'d images are working fine.

Share this post


Link to post
Share on other sites

Hmm... that's odd, I'll take a look at the module. Cheers for checking that though.

Share this post


Link to post
Share on other sites

Looks like it tries to create /MarkupSitemapXML/ folder in the root. There should be full path to cache folder visible on error msg.

Share this post


Link to post
Share on other sites

I worked it out - you have to install the Cache module as well, which is present in the default PW installation, just not installed by default (I already ahd it switched on on my test account!).

That will make it work, but I do need to put some sort of check into my module to make it a bit easier (need to read the posts around here on module dependencies).

Share this post


Link to post
Share on other sites

I worked it out - you have to install the Cache module as well, which is present in the default PW installation, just not installed by default (I already ahd it switched on on my test account!).

That will make it work, but I do need to put some sort of check into my module to make it a bit easier (need to read the posts around here on module dependencies).

Still doesn't seem to work, same error msg, damned if I know why?

http://theseekerr.com/sitemap.xml - there it is, if staring at my error provides any sort of motivation.

Share this post


Link to post
Share on other sites

Could you try uninstalling both modules and then reinstalling the cache one first and see if that helps please?

Share this post


Link to post
Share on other sites

Pete, try adding an extra line to your install function:

wire('modules')->get('MarkupCache'); 

That will just ensure that it's installed ahead of time and should resolve the problem in this particular case.

However, I don't think there is a problem with your code, I think it's actually a bug with the MarkupCache module (or maybe Module installer) because the MarkupCache module is responsible for making sure it's files go into the right place, and clearly it's not doing that. I will locate and fix the issue. I was able to reproduce it here by uninstalling the MarkupCache module and then letting it be installed at the time it's used. That seems to be the only time the issue occurs.

Share this post


Link to post
Share on other sites

Found it--it was a bug. Sorry for the inconvenience guys. This is one of those obscure bugs that takes the right set of circumstances to turn up, so these can be difficult to track down. Thanks for finding it. I've just committed the fix to the dev branch, and it should be merged into the stable branch likely tomorrow. Here's the commit message:

[dev c3a8ffe] Dev: fix issue with $modules->get('uninstalled module') where the module's init() wasn't called on an "autoload" module when it was used immediately after it was installed.

Share this post


Link to post
Share on other sites

I've tried uninstalling both the Sitemap module and the Cache module, then reinstalling the Cache module before the Sitemap module. I'm still not winning...

Share this post


Link to post
Share on other sites

Sorry, I think it's Markup Cache module and not Fieldtype - I forgot to specify which one (the Fieldtype cache module is on by default whereas ModuleCache isn't).

Share this post


Link to post
Share on other sites

Sorry, I think it's Markup Cache module and not Fieldtype - I forgot to specify which one (the Fieldtype cache module is on by default whereas ModuleCache isn't).

No dice. The module was already installed, and threw an error about a missing MarkupCache folder when I went to remove it. So I created the folder, and it uninstalled cleanly, deleting that folder. Then I reinstalled the two modules....still no go, and I notice that folder is still missing. I manually created it on the off chance that'd help but that didn't work either.

I'm on the verge of converting your code back to a template, this is getting silly...

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now

  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By Robin S
      I have had this module sitting in a 95% complete state for a while now and have finally made the push to get it out there. Thanks to @teppo for his Hanna Code Helper module which I referred to and borrowed from during development.
      http://modules.processwire.com/modules/hanna-code-dialog/
      https://github.com/Toutouwai/HannaCodeDialog
      HannaCodeDialog
      A module for ProcessWire CMS/CMF. Provides a number of enhancements for working with Hanna Code tags in CKEditor. The main enhancement is that Hanna tags in a CKEditor field may be double-clicked to edit their attributes using core ProcessWire inputfields in a modal dialog.
      Requires the Hanna Code module.
      Installation
      Install the HannaCodeDialog module using any of the normal methods.
      For any CKEditor field where you want the "Insert Hanna tag" dropdown menu to appear in the CKEditor toolbar, visit the field settings and add "HannaDropdown" to the "CKEditor Toolbar" settings field.
      Module configuration
      Visit the module configuration screen to set any of the following:
      Exclude prefix: Hanna tags named with this prefix will not appear in the CKEditor toolbar dropdown menu for Hanna tag insertion. Exclude Hanna tags: Hanna tags selected here will not appear in the CKEditor toolbar dropdown menu for Hanna tag insertion. Background colour of tag widgets: you can customise the background colour used for Hanna tags in CKEditor if you like. Dialog width: in pixels Dialog height: in pixels Features
      Insert tag from toolbar dropdown menu
      Place the cursor in the CKEditor window where you want to insert your Hanna tag, then select the tag from the "Insert Hanna tag" dropdown.

      Advanced: if you want to control which tags appear in the dropdown on particular pages or templates you can hook HannaCodeDialog::getDropdownTags. See the forum support thread for examples .
      Edit tag attributes in modal dialog
      Insert a tag using the dropdown or double-click an existing tag in the CKEditor window to edit the tag attributes in a modal dialog.

      Tags are widgets
      Hanna tags that have been inserted in a CKEditor window are "widgets" - they have a background colour for easy identification, are protected from accidental editing, and can be moved within the text by drag-and-drop.

      Options for tag attributes may be defined
      You can define options for a tag attribute so that editors must choose an option rather than type text. This is useful for when only certain strings are valid for an attribute and also has the benefit of avoiding typos.
      Add a new attribute for the Hanna tag, named the same as the existing attribute you want to add options for, followed by "__options". The options themselves are defined as a string, using a pipe character as a delimiter between options. Example for an existing attribute named "vegetables":
      vegetables__options=Spinach|Pumpkin|Celery|Tomato|Brussels Sprout|Potato You can define a default for an attribute as normal. Use a pipe delimiter if defining multiple options as the default, for example:
      vegetables=Tomato|Potato Dynamic options
      Besides defining static options as above, you can use one Hanna tag to dynamically generate options for another. For instance, you could create a Hanna tag that generates options based on images that have been uploaded to the page, or the titles of children of the page.
      Your Hanna tag that generates the options should echo a string of options delimited by pipe characters (i.e. the same format as a static options string).
      You will probably want to name the Hanna tag that generates the options so that it starts with an underscore (or whatever prefix you have configured as the "exclude" prefix in the module config), to avoid it appearing as an insertable tag in the HannaCodeDialog dropdown menu.
      Example for an existing attribute named "image":
      image__options=[[_images_on_page]] And the code for the _images_on_page tag:
      <?php $image_names = array(); $image_fields = $page->fields->find('type=FieldtypeImage')->explode('name'); foreach($image_fields as $image_field) { $image_names = array_unique( array_merge($image_names, $page->$image_field->explode('name') ) ); } echo implode('|', $image_names); Advanced: define or manipulate options in a hook
      You can hook HannaCodeDialog::prepareOptions to define or manipulate options for a Hanna tag attribute. Your Hanna tag must include a someattribute__options attribute in order for the hook to fire. The prepareOptions method receives the following arguments that can be used in your hook:
      options_string Any existing string of options you have set for the attribute attribute_name The name of the attribute the options are for tag_name The name of the Hanna tag page The page being edited If you hook after HannaCodeDialog::prepareOptions then your hook should set $event->return to an array of option values, or an associative array in the form of $value => $label.
      Choice of inputfield for attribute
      You can choose the inputfield that is used for an attribute in the dialog.
      For text attributes the supported inputfields are text (this is the default inputfield for text attributes so it isn't necessary to specify it if you want it) and textarea. Note: any manual line breaks inside a textarea are removed because these will break the CKEditor tag widget.
      Inputfields that support the selection of a single option are select (this is the default inputfield for attributes with options so it isn't necessary to specify it if you want it) and radios.
      Inputfields that support the selection of multiple options are selectmultiple, asmselect and checkboxes.
      You can also specify a checkbox inputfield - this is not for attributes with defined options but will limit an attribute to an integer value of 1 or 0.
      The names of the inputfield types are case-insensitive.
      Example for an existing attribute named "vegetables":
      vegetables__type=asmselect Descriptions and notes for inputfields
      You can add a description or notes to an attribute and these will be displayed in the dialog.
      Example for an existing attribute named "vegetables":
      vegetables__description=Please select vegetables for your soup. vegetables__notes=Pumpkin and celery is a delicious combination. Notes
      When creating or editing a Hanna tag you can view a basic cheatsheet outlining the HannaCodeDialog features relating to attributes below the "Attributes" config inputfield.
      Troubleshooting
      HannaCodeDialog includes and automatically loads the third-party CKEditor plugins Line Utilities and Widget. If you have added these plugins to your CKEditor field already for some purpose and experience problems with HannaCodeDialog try deactivating those plugins from the CKEditor field settings.
    • By joshuag
      Introducing our newest [commercial] module:
      Recurme
      Processwire Recurring Dates Field & Custom Calendar Module.
      http://www.99lime.com/modules/recurme/
      One Field to Recur them ALL…
      A Recurring Dates InputField for your Processwire templates. The InputField you’ve been waiting for.
      Complex RRule date repeating in a simple and fast user interface.
      Use the super simple, & powerful API to output them into your templates.
      example:
      <? // easy to get recurring events $events = $recurme->find(); // events for this day $events = $recurme->day(); // events for this week $events = $recurme->week(); // events for this month $events = $recurme->month(); ?> <? // Loop through your events foreach($events as $event){ echo $event->title; echo $event->start_date; echo $event->rrule; echo $event->original->url; ... } ?> Unlimited Custom Calendars.
      Imagine you could create any calendar you wanted on your website. Use recurring events with the Recurme field, or use your own Processwire pages and date fields to render calendars… it’s up to you. Fully customizable. Make as many calendars as you like. Get events from anywhere. Recurme does all the hard date work for you.
      Unlimited Custom Admin Calendars too.
      Hope you like it  ,
       Joshua & Eduardo from 99Lime.
       




    • By valan
      At our site we use both email and phone authorizations at frontend. To make life easier, I've developed HelperPhone pack that handles phone numbers. This pack includes following modules for ProcessWire CMS/CMF:
      FieldtypePhoneNumber: module that stores phone numbers InputfieldPhoneNumber: module that renders inputfield for phone numbers HelperPhone: module that loads PhoneNumber and PhoneNumberConst classes, and 'libphonenumber' namespace All these modules require included PW WireData-derived class PhoneNumber and PhoneNumberConst.
      PhoneNumber class is a thin wrapper over giggsey/libphonenumber-for-php, itself is port of Google's libphonenumber. PhoneNumberConst class stores constants, used by PhoneNumber class Usage: PhoneNumber class
      $phone = '8 (916) 318-07-29 ext 1234'; // input string could be in any phone-recognizable format $phoneNumber = new PhoneNumber($phone, 'RU'); // or wire('modules')->get('HelperPhone')->makePhoneNumber($phone, 'RU'); echo ($phoneNumber->isValidNumber() ? 'Yes':'No'); // Yes echo ($phoneNumber->isValidNumberForRegion($regionCode) ? 'Yes':'No'); // Yes echo $phoneNumber->getNumberTypeTitle(); // Mobile echo $phoneNumber->getCountryCode(); // 7 echo $phoneNumber->getRegionCode(); // RU echo $phoneNumber->getNationalNumber(); // 9163180729 echo $phoneNumber->getExtension(); // 1234 echo $phoneNumber->formatForCallingFrom('US') // 011 7 916 318-07-28 echo $phoneNumber->formatForCallingFrom('GE') // 00 7 916 318-07-28
      For more methods and properties please refer to PhoneNumber and PhoneNumberConst source files. Need more? Check giggsey/libphonenumber-for-php and use it by accessing $phoneNumber->phoneNumber property - it is instance of \libphonenumber\PhoneNumber or null (if empty).
      Usage: field
      Note: on field creation, make sure that you've configured field settings
      Default region: assumed region if input phone number string is not in international format (starts with '+', etc)
      Enabled/disabled phone extentions: if disabled, phone extension will be removed on field save.
      Phone field settings in example below: default region code 'RU', phone extensions are enabled
      echo $page->phone; // +79163180729 // Note1: $page->phone stores instance of PhoneNumber and renders to string in E164 format. // Note2: E164 format does not include extension. echo $page->getFormatted('phone'); // +7 916 318-07-29 ext. 1234 echo $page->getUnformatted('phone'); // +79163180729 echo $page->phone->format(PhoneNumberConst::RFC3966); // tel:+7-916-318-07-29;ext=1234 echo $page->phone->getNationalNumber(); // 9163180729 Usage: PW selectors
      FieldtypePhoneNumber is instance of FieldtypeText. It stores phone numbers and extensions as string in E164 format with #extention (if provided by user and enabled in settings) E.g. in db it looks like this: '+79163180729#1234'. This makes it easy to query fields as any text field.
      echo $pages->find([     'template' => 'my_temlate',     'phone^=' => '+79163180729', ]); // will echo page ids where phone starts with '+79163180729' Finally
      I've decided to put it here first and later to Modules directory (based on your feedbacks).
      GitHub: https://github.com/valieand/HelperPhone
      Enjoy
    • By justb3a
      Little admin helper module: Using this module you can view all template cache settings at once. E.g. cache status, cache time (configurable). Furthermore it adds the functionality to clear the entire template cache or just the template cache for a given template. Note that this may cause a temporary delay for one or more requests while pages are re-cached.

       
      GitHub: https://github.com/justb3a/processwire-templatecacheoverview
    • By Steven Veerbeek
      Hi,
      I am trying to create a module for a webshop in which I can predefine a number of thumbnail sizes for my product images. I was thinking of storing each of these image sizes as a child page with 'width' and 'height' fields under the module page , so I can use a PageTable input field in my module to easily manage them.
      I know how to create a Pagetable field and add it to templates so I can use it in regular pages, but because I am planning on implementing some other functionalities that (I think) can't be achieved with a regular page, I need the PageTable field to work within a module.
      So far I have come up with this piece of code by trial and error:
      $page = $this->page; $field_sizes = $this->modules->get("InputfieldPageTable"); $field_sizes->title = "image_sizes"; $field_sizes->label = "Image sizes"; $field_sizes->set('parent_id', $page->id); $template = wire("templates")->get("image_size"); $field_sizes->set('template_id', $template->id); $field_sizes->set('columns', "title\nimage_width\nimage_height"); $wrapper->add($field_sizes); It works in that it does display an empty PageTable in my module. I can also add pages and they will be added as child pages under my module page, but when I do, the way the PageTable is displayed gets all messed up. Instead of showing the newly created page as a row in the PageTable, all the fields on the module page (including the PageTable field itself) are repeated within the PageTable field.
      I hope my explanation makes sense. I am fairly new to Processwire (and module development in particular) so perhaps I am just trying to use PageTable in a way it was not intended to be. Maybe you guys could give me some directions on how to achieve what I am looking for?
      Thanks!