Jump to content

MoritzLost

Members
  • Content Count

    313
  • Joined

  • Last visited

  • Days Won

    15

MoritzLost last won the day on November 24 2020

MoritzLost had the most liked content!

Community Reputation

831 Excellent

About MoritzLost

  • Rank
    Sr. Member

Contact Methods

  • Website URL
    https://moritzlost.de

Profile Information

  • Gender
    Male
  • Location
    Cologne, Germany

Recent Profile Visitors

1,439 profile views
  1. What do you want to achieve? Do you want to get all images for a project out of the system to use them externally? Or do you want to restructure how/where ProcessWire saves images in general? For the first case, you can write a little script to iterate recursively through all fields, including any repeater / repeater matrix sub-fields, to get an array of images. Then you can use that to copy all the images to one folder (using $files->copy(), for example), get a link of filenames (see Pagefile::filename()) or do whatever you want with them, like export their meta data as JSON or anything else. Super quick and dirty, will probably not work right away, but you get the idea: function getImages(Page $page): [] { $images = new PageImages; $fields = array_map(function($field){ return $field->name; }, iterator_to_array($page->fields)); foreach ($fields as $field) { $value = $page->get($field); $type = $page->fields->{$field}->getFieldType(); if ($type instanceof FieldtypeImage) { $images->import($value); } elseif ($type instanceof FieldtypeRepeater) { $images->import(getImages($value)); } } return $images; } $images = getImages($page);
  2. Don't overthink it. You're gonna need a way to reference a specific field anyway. Hiding the name away behind a constant, config or whatever isn't going to change that. If you're worried about changing field names, you should instead invest the time to find better names for your fields. Why would your field names change? Probably because the data they hold or the thing they represent have changed - both of those cases will require adjustments in the templates anyway. I've never understood the benefit of "hiding" a property or method name behind a constant. I mean, what are you gonna do if the field name behind it changes? Let's say I have the field field_for_thing_a and use a constant FIELD_NAME_THING_A to hide the dirty, dirty field name string behind a nice, verbose constant. Now I need to rename the field to field_for_different_thing_b. Am I just gonna leave the constant in place? So FIELD_NAME_THING_A now references something completely different? No, I'm gonna rename it, in which case I could just find+replace the name of the thing itself and will introduce a BC break anyway. But if the field needs to change, it's not backwards compatible anyway. The only backwards compatibility I'm maintaining at this point is unreadable cargo cult code πŸ™ƒ Of course, there are exceptions. Depends on what you're building. If you're talking about a module which might need to access a user-defined field, by all means, store the field name in a variable (it's gonna be pulled from the database anyway if it's configured in the module settings). Maybe I'm way off base here. What problem are you actually trying to solve? Maintainability is a spectrum and doesn't exist in a vacuum. What maintenance burden do you want to avoid?
  3. @adrian Awesome, thanks for the fix adrian, you're my hero 🀩 Didn't know about the OPT + Enter shortcut, that's handy indeed! I removed the snippet through the Console panel, that bit worked fine, I guess the problem was just the shortcut trying to load a snippet after it had been deleted. Anyway, thanks again!
  4. Hi @adrian, I'm having a small but annoying issue with the Console panel in the debug bar. I'm using the Console to quickly try out code snippets, so most of the time I enter some code and hit CMD + Enter to run it. I've rarely ever used the option to save snippets on the right side. Now I tried to save a snippet which somehow broke the CMD + Enter shortcut. After saving a snippet, hitting CMD + Enter always wipes out whatever I have entered in the code input and restore that snippet from disk, instead of running the code I entered in the code input. Clicking the "Run" button above the code will execute the code I entered normally, it's only the keyboard command that's not working. So I tried removing the snippet and clearing the "Enter filename" input on the right. Still, after entering some code in the code input and hitting CMD + Enter, it will still try to load the (deleted) saved snippet from disk – I can see an error in the debug bar: PHP Warning: file_get_contents([...]/site/templates/TracyDebugger/snippets/new.php): failed to open stream: No such file or directory in .../includes/ConsoleSnippets.php:16). Since the snippet file does not exist, it will wipe out the code I entered in the Console window completely. Am I doing something wrong, or could this be a bug in the JS code handling the keyboard shortcut? I don't need the snippets, I just want to CMD + Enter Shortcut back to execute the code I entered in the Console window ^^' Thanks!
  5. Quick tip: Displaying hCaptcha in the correct language By default, hCaptcha displays its interface in the visitor's browser language, which means it may differ from the current language of your site. You might want to change that to always use your site's language, or the current language if you have a multi-language site. You can use the hook InputfieldHCaptcha::getScriptOptions to adjust the language of the hCaptcha interface dynamically. Here's a snippet with a couple of options for setting the language: // site/ready.php wire()->addHookAfter('InputfieldHCaptcha::getScriptOptions', function (HookEvent $e) { $options = $e->return; // option 1: for single-language sites, you can just hardcode a specific language $options['hl'] = 'de'; // option 2: for multi-language sites, you can use the translation api $options['hl'] = _x('de', 'hCaptcha Language'); // option 3: you can also add a custom field to your language template to hold the language code $options['hl'] = wire('user')->language->language_code; $e->return = $options; }); For option 2, make sure to add a translation for the language code in every language. For option 3, first set $config->advanced = true in your config.php so you can edit the language template. You have to create the language_code field yourself and add it to the template, then set the language code in each of your languages. For all options, make sure to use the correct language code as listed here.
  6. Thanks @adrian! Sorry I forgot to mention the versions ^^ The site I ran into this problem is still on PHP 7.4, but the update fixed the problem nonetheless. Thanks for the quick response!
  7. ProcessCacheControl version 1.1.0 released I just released an updated version of this module which fixes some issues with the asset version management feature. In particular: When using CacheControlTools::getAssetVersion while no asset version existed (for the specified category), the implicitly generated version incorrectly expired after one day. This is now fixed, so asset versions will not expirate anymore until manually cleared. Asset versions are no stored using WireCache::expireNever instead of WireCache::expireReserved. This means they will be deleted when using $cache->deleteAll(), when previously you had to explicity specify them by namespace to clear the cached versions. Links: Full changelog for version 1.1.0 ProcessCacheControl in the modules directory
  8. Hi @adrian, I've got another small issue between TracyDebugger and one of my modules. Not sure if the problem is Tracy, my module or the core, anyway ... The problem is my ProcessCacheControl module, which comes with two module files: ProcessCacheControl itself, which is a Process module, and the helper module CacheControlTools, which implements the Module interface but extends Wire (instead of WireData). When dumping an instance of the CacheControlTools module, I get a fatal exception: Steps to reproduce: Install ProcessCacheControl In the console or any template, try to dump an instance of the module using d / bd: d($modules->get('CacheControlTools')); The stack trace indicates TD.php#L281 as the cause. Specifically, $var->get('title|name') results in Wire->__callUnknown which results in the error above (see attached screenshot). I guess the debugger assumes that the module extend WireData instead of Wire? If I change the module to extend WireData, the exception goes away. Though I would like to keep it extending Wire, since that module doesn't hold any data or state, so extending WireData doesn't make any sense. Maybe this could be handled by Tracy? Thanks!
  9. @fruid I'd still test your mail with the mail-tester tool mentioned above to make sure your email doesn't appear "spammy". Depending on your settings and whether you're sending through the mail server of your hosting your mail may appear to be unauthenticated. Anyway, it's curious that WireMailSmtp isn't working but WireMailPHPMailer is, are you using the same settings for both? By the way, I'd be slightly wary when the provider tells you to use port 587. In general, TLS-encrypted mail should use port 465. Port 587 is for STARTTLS, which starts SSL-encryption only after a connection has been established, which means you're susceptible to a man-in-the-middle attack. Your hoster only supports port 25 (plain text) and 587 (STARTTLS), that's a red flag. Anyway, if you're using the suggested settings for SMTP connections by your hoster and they're not working, I'd just talk to them to see what might be the problem.
  10. Yes, that's correct. The default value is only used for the interface, it's not applied to any existing pages. You can fix that in two ways: 1. Anywhere you use the value in your code, assume the default if no value is set. Something like this: // default to behavior option one $behaviorField = $fields->get('speciality_text_behavior'); $textBehavior = $page->speciality_text_behavior->id ?: $behaviorField->type->getOptions($behaviorField)->get('id=1')->id; You could also put that in a hook to get that behaviour anywhere you use this field. 2. Write a script to manually change the value of all pages with an empty value in that field to your new default: $valueMissing = $pages->find('speciality_text_behavior=""'); foreach ($valueMissing as $p) { $p->of(false); $p->speciality_text_behavior = 1; $p->save(); } You can quickly execute that snippet in the Tracy Debugger console module. BTW am I the only one who's annoyed by the field name? "speciality" in British English but "behavior" in American English, who does that πŸ˜…
  11. Not necessarily. The username of your email account is independent from the sender address – this is why, for example, you can have one email account with multiple associated email addresses. Though some providers don't make that distinction clear, and nowadays your username is usually the primary email address, so most people (in my experience) are not aware that those are two different things. WireMailSmtp needs the username of the account to log in, and often this is the same as the sender address, but it doesn't have to be. This is why you can specify the username and sender address separately. WireMailSmtp doesn't care about the domain the sender address belongs to, any restrictions regarding that are done by the mail provider. What matters for verification and spam prevention is the domain you're sending from. If you're sending from @your-domain.com and you've properly set up the SPF and DKIM records for your mail server, your mail server can send emails from every address @your-domain.com without problems. Of course, any mail provider / server tool can add any restrictions for sender addresses they want on top of that. For example, if you send your Email through Gmail, it probably won't let you use a sender address that doesn't belong to your account. So it comes down to what email provider you're using.
  12. In theory, no, you can use any field you want for the From field in the e-mail. In practice however, many email providers will block this, as it's essentially spoofing. And even if your provider doesn't reject emails like this entirely, they will probably go directly to the spam folder, as your server probably is not authorised to send mail from this domain (using SPF, DKIM or similar methods). The mails might even be rejected entirely, depending on DMARC records. And for good reason – you wouldn't want just anybody to be able to send spam that appears to have been sent from your address, right? You shouldn't send unauthenticated emails, and by the way you also shouldn't send emails without SSL – but that's a separate issue. Yes, it is. That's what the reply-to field in an email is for. This way, you can have a sender address (From field) that's clearly coming from your domain (something like no-reply@your-domain.com) and a different recipient for answers, which is the correct way to approach this. That said, I have encountered one hosting provider that blocks emails where either the from OR the reply-to email don't belong to a domain that is registered with that provider. In this case, you'd have to find a workaround, like sending the email to both recipients and instructing them to hit reply all. Or integrate messaging into your application instead of using email. Alternatively, you might use mailto links with pre-filled recipient, subject line and body and instruct your users to send their own mail. Which might be cleaner in terms of email security / authentication, though it depends on your application.
  13. You need a reference to the instance, so the $PageGridCSS variable in your case. That's because there can be different instances of the same class with different states and holding different data. So yes, if you create a new instance in a specific context, only that context has access to the variable. If you want to pass it around, you need to provide utility methods or pass specific instances of a class as parameters. Usually, the instances of a set of classes are linked together by properties referencing each other. For example, in my example code above, the PageGridData contains a list of PageGridItem instances, which can be accessed by key or iterated over using the utility methods provided by WireArray. Each PageGridItem then has a reference to the PageGridCSS instance belonging to it (that's the $cssRules property in my example code). For example: function doStuff(PageGridData $data) { $key = 1234; // $item will be an instance of PageGridItem $item = $data->get($key); // $cssRules will be an instance of PageGridCSS $cssRules = $item->cssRules; // ... } Does that help? The best way to pass around data depends on the application flow. For ProcessWire modules, the main module class will usually have helper methods to access specific classes of the module. For example, my module TrelloWire contains a separate class (ProcessWire\TrelloWire\TrelloWireAPI) that handles all requests to the Trello API. The main module file has a utility method to get an instance of that class with the API key and token configured in the module settings. Another example is the TrelloWireCard class, which holds all the data used to create a Trello card through the API. This one is also a module, so you can access it using $modules->get() to get an empty instance. But the main module class also has a utility method to create an instance populated with data from a regular page and the module configuration. This method is used by the module internally, but can be hooked to overwrite specific fields or used to build your own application or business logic on top of the module.
  14. @jploch Ok, so currently you have a procedural approach, which is fine for a fixed use-case. My proposed solution might be overkill for what you're trying to achieve. And it will definitely be more work - and maybe the more general application for your module (which I don't even know the scope or precise purpose of) that I'm imagining isn't even what you're trying to achieve. So before you start refactoring, consider if it will actually be of benefit to your module! And of course, if you have to use code that you don't fully understand the purpose of, it won't help you in the end. If what you have is working fine for your use-case, maybe you don't need all that stuff. So just take my approach with a grain of salt πŸ™‚ I would start by creating classes that represent the building blocks of your page builder. That would probably include a class that represents a list of CSS rules (that can use WireArray), a class for individual items (with a reference to a list of CSS rules) and a class for a list of items (this again can use WireArray). Decoding JSON would probably be the responsibility of the latter. Though of course you can also go with a more eleborate approach to transforming JSON to classes like the builder pattern. Here's a start (I wrote this in the browser, so it will need some polish and might include some errors, but hopefully it communicates the idea behind it): // this class represents a list of CSS rules, as included in your JSON data class PageGridCSS extends WireArray { /** This class gets methods to set, get and remove CSS rules, and render them to CSS. */ } class PageGridItem { // PHP 7.4+, for older PHP versions use a protected property with getters and setters public int $id; // each item holds a reference to a set of rules public PageGridCSS $cssRules; /** This class gets properties and methods corresponding to the data it represents */ } class PageGridData extends WireArray { // guarantee that this can only hold PageGridItem objects public isValidItem ($item) { return $item instanceof PageGridItem; } // make PageGridItems accessible by their ID public function getItemKey($item) { return $item->id; } // convert json to the appropriate classes public static fromJSON (string $json): PageGridData { $items = json_deocde($data)['items']; $dataList = new self(); foreach ($items as $item) { $dataItem = new PageGridItem(); $dataItem->id = $item->id; /** Add all the properties to the item, catching missing or malformed data */ $dataList->add($dataItem); } return $dataList; } public renderCSS() { // render the CSS for the items this instance contains } } Why even do all this? Currently, your dynamic template makes a couple of assumptions that I, as a user of your module, may not agree with. For example: It always includes style tags. What if I want to save the output in a CSS file and serve it statically? You infer the context (backend / frontend) which doesn't always work reliably. I also can think of some reasons why I would like to get the code for the frontend in the backend - for example, to save it to a field. Your ".breakpoint-{...}" classes may interfere with my own stylesheets, so I could use a way to rename them. Maybe I want only a part of the stylesheet, like the rules for a specific breakpoint. ... Making all this modular and giving users access to the functionality through a well-defined API with utility methods allows me to customize all this and access the parts that I want to use, changing those that I need to. Though again, maybe I'm totally wrong regarding the intent and scope of your module. This way a fun exercise to think through anyway, hopefully it will be helpful to you or others looking for something similar πŸ™‚ Hm, maybe that stuff would make a good article for processwire.dev ... πŸ™ƒ
  15. Then the user is your own module. All the points in my post above still apply – your module has to make some assumptions about the structure of the JSON data. Even if the data is only consumed internally, passing unstructred data around can cause unexpected errors at any point. So it's still better to parse the data into a representation that makes guarantees a specific data structure, and raise errors during parsing (as opposed to a random error anywhere in your module's lifecycle that's hard to track down). Also, will your module not allow customization through, for example, custom page builder elements or hooks? As soon as that's the case, developers using your module will have to use your data, so it should provide a uniform interface to accessing that data. Basically, any ProcessWire class representing some sort of collection, so you can check out those. For example, check out Pagefiles, FieldsArray and PageArray which all extend WireArray. See how they make use of all the utility methods WireArray provides and override just the methods they need to customize to adapt the WireArray to a specific type of data? For example, check out FieldsArray::isValidKey only allows Field objects to be added to it, so adding anything else will immediately throw an error. You can use this to map your pagebuilder items to a specific class and then have a class like PageBuilderItems extending WireArray that only accepts this class as items. This will go a long way towards having a uniform data structure. Again, don't mix up storage and representation. For storage, I would prefer the second example you posted, with items being an array instead of a map and the ID being just a regular property. Simply because arrays are more convenient to create, parse and map (in JS especially, but also in PHP). Though again, it doesn't matter as soon as you parse the data. The representation your module (or others, see above) uses to access the data can provide utility methods, like accessing an item by key. Regarding the last point specifically, WireArray can help you with this. The documentation is kind of handwaivy about how WireArrays handle item keys – WireArray::add doesn't take the key as an argument, but WireArray::get allows you to get an item by key, so where does the key come from? If you check the source code, turns out WireArray automatically infers a key based on the item – see WireArray::getItemKey. Your custom class can extend this to use the ID property of a given item as the key. For example, FieldsArray::getItemKey does exactly this. This allows you to use page IDs to access items without having to store your data specifically as a map. On top of that, you can use all the other utility methods WireArray provides to access elements in the any way you like.
Γ—
Γ—
  • Create New...