benbyf

3 new beginner modules

Recommended Posts

Hi!

I've been making my first modules and I've created three so far to help me learn. I would love so feedback or pull requests for improvements as I hope to write a tutorial about my work soon. In particular the third modules isn't very finished.

git: https://github.com/benbyford/PW-starter-modules/

  • HelloUserYouSaved - adds message {your user name, page saved} in admin when a page is saved.

    • This module shows how to implement a basic module,
    • get and use variables,
    • create a message in the admin
  • RedirectAdminPages - redirect specific user role to a custom page set in the module config.

    • This module shows how to implement module configuration,
    • using variables saved in the admin,
    • redirecting a user using session->redirect()
  • HotSwapUser - Swap user on the fly in the admin or frontend of your site

    • This module shows how users can be used in a module
    • how to set a user permission
    • how to install / uninstall something within your module
    • how to create a function that can be output in the frontend of your site.
  • Like 10

Share this post


Link to post
Share on other sites

Hi!

Very good initiative! ^-^

I have skimread through the code and my opinion is: The first and second ones looks good. But to be honest, this hotswap user thing is a big security issue. Sorry! :)

Also only for demonstration / tutorial purposes, it is better not to use hot user swapping as a thema. The audience for beginner tutorials often will be, yes, the name says it: beginners. And assumed they simply do not know about such security issues and best practices in regard of how to validate user-inputs, you should not show code like this to them. At least you would need to embedd all security relevant stuff too. But then it fastly will become to complex for a beginner tutorial. A good one would be to only pick up how to validate user inputs and how PW provides good tools for that. (type and format validation, whitelist matching, ...)

With your code, everyone can login with each existing account (also Superuser) just by knowing / trying (multiple til endless!) user name(s). In regard to this, you may have a look into ALIF or TracyDebugger, how the security for this is tackled there.

I hope you do not mind me my frankness.

-------------

Looking to the code of the users redirect module, you can shorten it a bit. When found a matching user / role, you don't need to store true in a temporary var, break the loop and then check the temporary vars value / state, if you should redirect the current user. You simply can redirect the current user if a role matches:

    /*
    * ___renderPageRedirect
    *
    * redirect user to page if current user role found in config
    */
    public function ___renderPageRedirect($event) {

        // check to see if current page = admin template page
        // otherwise: early return!
        if($this->page->template != "admin") {
            return;
        }

        // find roles set in module configuration and create array
        $roles = explode(',', $this->userRoles);

        // for each user in module config check to see if current user
        foreach ($roles as $key => $val) {
            $roles[$key] = trim($roles[$key]);

            // if current user found then redirect = true
            if($this->user->hasRole($roles[$key])) {

                // this will leave the page and code immediately!
                $this->session->redirect($this->redirectPage);

                // stop user search
                break; // this can stay in here, just as fallback, 
                       // if something went wrong with calling the redirect, 
                       // but normally this line will not get executed.
            }
        }
    }

 

  • Like 4

Share this post


Link to post
Share on other sites

Hi Horst! Thanks for you code amends, will alter now.

I totally agree with you, the third module not really beginner level and needs a heck load more work on it before anyone was to actually use it. The security aspect I'm looking at next and thanks for those links.

Bar the first module, I was trying to make modules that didn't already exist that would be useful and interesting for me to make and had aspects I could teach. If you have any more suggestions for a third module whcih doesn't already exist then I'm all ears.

Thanks,

  • Like 2

Share this post


Link to post
Share on other sites
8 minutes ago, benbyf said:

If you have any more suggestions for a third module whcih doesn't already exist then I'm all ears.

You could write a beginner module about Fieldtype/Inputfield which accept a simple text, save it and render its markup :rolleyes:.

As Horst said, nice initiative !

  • Like 5

Share this post


Link to post
Share on other sites

anyone happen to have any ideas for inputfields that we havent already got??

  • Like 1

Share this post


Link to post
Share on other sites

A simple fieldtype might be "Name", where you enter a firstname and a lastname, which is stored separately and maybe a computed property for the fullname. I think it shouldn't hold more values, as it'll probably become complex just for the amount of fields. 

Also interesting might be other often extended core classes/modules like Process or Textformatter, with the latter actually being quite simple with often just a single method.

  • Like 4

Share this post


Link to post
Share on other sites

I've updated the my modules replacing HotUserSwap with simple TextformatterFindReplace instead. I'm going to work on some field types next :)

  • Like 3

Share this post


Link to post
Share on other sites

It would be good to also work on some Modules that do not 'autoload' :) Thanks for your efforts....

  • Like 1

Share this post


Link to post
Share on other sites

Ok been trying to take on everyones comments. In doing so I've split repos into beginner and intermediate.

https://github.com/benbyford/PW-starter-modules/
https://github.com/benbyford/PW-intermediate-modules

In doing so I can add to them with simple and more complex modules as and when I create them (and learn a new skill). The basic ones are currently super basic, so could probably do a couple more and then stop of crucial things to learn in modeul making. Any more suggestions welcome.

  • Like 5

Share this post


Link to post
Share on other sites

I think composer and dependency mamgement in general is a little out of scope for this series of module creation tutorials, looks interesting though, I've never felt the need for this myself mostly working on small projects and happy using profile exporting and wireshell for different installing / exporting tasks.

Share this post


Link to post
Share on other sites

Would love to see a simple tut on using hooks from a front-end form. Like if a form creates or saves a PW page, can I take the value of a user ID in that saved form/page, and then use that ID to update an altogether different page.

Share this post


Link to post
Share on other sites

Added new module PageDeferredPublish to Intermediate modules - Module allows you to publish a page at a time interval in the future e.g. 24hrs.

  • adds Publish Later buttons to edit page and page tree
  • uses LazyCron to count down pages that are both unpublished and have been checked to publish later
  • when page count down reaches 0, page publishes
     

Screenshot 2016-08-12 10.51.38.png

Screenshot 2016-08-12 10.51.16.png

  • Like 7

Share this post


Link to post
Share on other sites

Great work @benbyf!

I understand you wrote the tutorial to show that the module can do stuff on installing and uninstalling. There is another example you could use to handle creating pages and permissions (more info):

public static function getModuleInfo() {
	return array(

		// Some default stuff
		'title' => 'Title of the module',
		'version' => 001,
		'summary' => 'Summary of the module',
		'autoload' => false,
		'singular' => true,
		'icon' => 'bookmark',
		'permission' => 'name-of-the-permission',

		// Creates the page (and removes after uninstalling)
		'page' => array(
			'name' => 'name-of-the-page',
			'parent' => 'admin', // Or whatever
			'title' => 'Title of the Page',
			),	
		
		// Creates the permission (and removes after uninstalling)
		'permissions' => array(
			'name-of-the-permission' => 'Title of the permission'
			),
	);
}

Written in browser, so not tested. I guess you'll get the idea ;)

Edited by arjen
link added
  • Like 5

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 anderson
      Hi all,
      I'm a new to website building. Learned some CRASH course of js,jquery,php. Then I found CMS. Still learning around forum, youtube....
      Anyway, please help me with some beginer questions:
      1, About template - please correct me if I understand wrong : every page should be (or recommended) built on a template. So if in total I'll have 10 pages, 2 of them have same layout, I'll need 9 templates.  And, what fields a page includes, is not defined in page, but defined in the template that page uses. 
      2,  Where to see what modules I've installed? is it in "Modules - Site"? 
      3, I installed "PageTable Extended", then what?  As in a youtube tutorial, it should appear in Setup tab, but it doesn't.  What's in there: templates,fields,logs,comments. (I installed "Uikit 3 site_blog profile".)
      4, I did a search in Processwire website for the famous "repeater matrix" module, and can not find it, there's a Repeater, as well as a Matrix. Is it not a module?
      5, I watched this youtube tuts: https://www.youtube.com/watch?v=IHqnLQy9R1A
      Anybody familiar with this tuts please help: 
      After he analysed a target webpage layout he wanted to mimic, he created some fields, some template, then based on those he created a page and input some "content" in there, then clicked "view", it's just some text. So, here comes my question, he copied a folder "assets" (subfolders are: css,fonts,js,img) over, then the page have the appearance/layout he wanted to mimic. Where does that assets folder come from?
      Appreciate any help.
    • By mtwebit
      I've created a set of modules for importing (manipulating and displaying) data from external resources. A key requirement was to handle large (100k+) number of pages easily.
      Main features
      import data from CSV and XML sources in the background (using Tasker) purge, update or overwrite existing pages using selectors user configurable input <-> field mappings on-the-fly data conversion and composition (e.g. joining CSV columns into a single field) download external resources (files, images) during import handle page references by any (even numeric) fields How it works
      You can upload CSV or XML files to DataSet pages and specify import rules in their description.
      The module imports the content of the file and creates/updates child pages automatically.
      How to use it
      Create a DataSet page that stores the source file. The file's description field specifies how the import should be done:
      After saving the DataSet page an import button should appear below the file description.

      When you start the import the DataSet module creates a task (executed by Tasker) that will import the data in the background.
      You can monitor its execution and check its logs for errors.

      See the module's wiki for more details.
      The module was already used in three projects to import and handle large XML and CSV datasets. It has some rough edges and I'm sure it needs improvement so comments are welcome.
    • By dreerr
      TemplateEnginePug (formally TemplateEngineJade)
       
      This module adds Pug templates to the TemplateEngineFactory. It uses https://github.com/pug-php/pug to render templates.
      doctype html html(lang='en') head meta(http-equiv='content-type', content='text/html; charset=utf-8') title= $page->title link(rel='stylesheet', type='text/css', href=$config->urls->templates . 'styles/main.css') body include header.pug h1= $page->title if $page->editable() p: a(href=$page->editURL) Edit Project on GitHub: github.com/dreerr/TemplateEnginePug
      Project in modules directory: modules.processwire.com/modules/template-engine-pug/
       
      For common problems/features/questions about the Factory, use the TemplateEngineFactory thread.
       
    • By Robin S
      Pages At Bottom
      Keeps selected pages at the bottom of their siblings.
      A "bottom page" will stay at the bottom even if it is drag-sorted to a different location or another page is drag-sorted below it (after Page List is refreshed the bottom page will still be at the bottom).
      Newly added sibling pages will not appear below a bottom page.
      The module also prevents the API methods $pages->sort() and $pages->insertAfter() from affecting the position of bottom pages.
      Note: the module only works when the sort setting for children on the parent page/template is "Manual drag-n-drop".
      Why?
      Because you want some pages to always be at the bottom of their siblings for one reason or another. And someone requested it. 🙂
      Usage
      Install the Pages At Bottom module.
      Select one or more pages to keep at the bottom of their siblings. If you select more than one bottom page per parent then their sort order in the page list will be the same as the sort order in the module config.

       
      https://github.com/Toutouwai/PagesAtBottom
      https://modules.processwire.com/modules/pages-at-bottom/
    • By cosmicsafari
      Hi all,
      I have been asked by a client whether we can setup load balancing for their existing Processwire site.
      From my investigations on Google and within these forums, it definitely seems possible but as a newbie with a basic understanding of the subject im a bit lost.
      Does anyone know of any existing tutorials for settings up load balancing with PW?
      What items would need to be changed on their current stand alone install, is there a list of best practices worth consulting etc?
      As I understand it we would need to have some sort of copying mechanism (rsync script most likely) in order to make sure any uploaded assets are shared between the main server and the fallback ones, other than that im not sure what else would need to be ammended.
      Any thoughts/help would be greatly appreciated.