Jump to content

Hanna Code


ryan

Recommended Posts

44 minutes ago, adrian said:

Thanks! I dig into Hanna code modul to see, how difficult would be to implement this storage ...

  • Like 1
Link to comment
Share on other sites

  • 2 weeks later...

Hi all,

distracted for a while by other (bigger) problems, I now came back to the situation discussed here in this thread in october:

On 27.10.2016 at 3:01 PM, ottogal said:

@Robin S

Good find, thank you!

After this change even my simple use of the function strstr() works -  to crop the string on both ends, setting free the href attribute value:


<?php
$f = (string) $file;
$f = strstr($f,'/site');
$audiofile = strstr($f,'">',true);
?>
<audio controls>
	<source src='<?= $audiofile?>' type='audio/mp3'> 
</audio>

Your second hint to use SimpleXMLElement() of course is a cleaner way to do it:


<?php
$a = new SimpleXMLElement($file);
$audiofile = $a['href']->__toString();
?>
<audio controls>
	<source src='<?= $audiofile?>' type='audio/mp3'> 
</audio>

 

For my Hanna Code call    [[mp3 audio='LINK']]    now I have this Hanna Code (mp3.php):  (and all works fine - :) )

<?php
$a = new SimpleXMLElement($audio);
$pagelink = $a['href']->__toString();
$pagename = basename($pagelink);
$ap = $pages->get("template=audio,parent=audiopool,name=$pagename");
$link = $ap->mp3->url;
?>
	<div class='block'>
		<audio  controls width='400'>
			<source src='<?= $link ?>' type='audio/mp3'> 
		</audio>
	</div>
	<p><?= $pagename ?></p>

But when I open the Hanna Code in the editor and click the button "Save & Test", I get the following messages:

Quote

Warning: SimpleXMLElement::__construct() [simplexmlelement.--construct]: Entity: line 1: parser error : Start tag expected, '<' not found in ....../site/assets/cache/HannaCode/mp3.php on line 4

Warning: SimpleXMLElement::__construct() [simplexmlelement.--construct]: LINK in ....../site/assets/cache/HannaCode/mp3.php on line 4

Warning: SimpleXMLElement::__construct() [simplexmlelement.--construct]: ^ in ....../site/assets/cache/HannaCode/mp3.php on line 4


ProcessWire: ProcessHannaCode: String could not be parsed as XML
......

The line number refers to the file  ....../site/assets/cache/HannaCode/mp3.php where  the line

Quote

if(!defined("PROCESSWIRE")) die("no direct access");

and a blank line are prepended - so  the line in question is, of course: 

Quote

$a = new SimpleXMLElement($audio);

What is wrong with the code, and how can I get rid of these Warnings?

Thankful for some clarification:

ottogal

Link to comment
Share on other sites

1 hour ago, ottogal said:

But when I open the Hanna Code in the editor and click the button "Save & Test", I get the following messages:

I think that's because when you use your Hanna tag in CKEditor your audio attribute is (or should be) valid link markup, e.g. <a href="/some/url/">LINK</a>

But in the Hanna Code test tab the attribute is not a valid link but simply the string "LINK" which cannot be parsed by SimpleXML. So probably nothing to worry about, but if the error message is a concern you can do some simple check to see if the attribute looks like it will be a link. For example, at the top of your Hanna code:

if(substr($audio, 0, 2) !== '<a') return;

 

  • Like 1
Link to comment
Share on other sites

A other solution to Hannacode in this case yould be working with a Textformatter....

If you in concern of usability you could let your user just put in the mp3 file in CKEEditor and let the Textformatter search for it (href regex for *.mp3*) and replace it with the player. So zero worrying about include audio files.

You could take a look at the Youtube Textformatter from Ryan:
https://github.com/ryancramerdesign/TextformatterVideoEmbed/blob/master/TextformatterVideoEmbed.module

...just as an additional option.

regards mr-fan

Link to comment
Share on other sites

Thanks mr-fan - that seems to be a nice idea! I for sure will take a nearer look into it - after my actual problems hopefully will be solved... (I've got a similar Hanna Code to display a Video, using the jQuery plugin VideoJS - which mostly works well, but not on some mobile devices, e.g. on WinPhone 8 or iPhone...)

Link to comment
Share on other sites

  • 2 months later...

Hi all

i've used Hannacode to include a php page with a form. The "action" of this form is to another page that have another php file include. Last php file get post var and print the result. The problem is that when i submit the form 8/10 the new page loading but site freeze. If i reload the page (and re-submit the form) it works. I don't know if it depends to hannacode or processwire.  I have another site on same server written in pure php but i never have this type of problem.

Thank in advance.

 

 

 

Below the result page php code:

Hannacode

<?php
    include (wire('config')->paths->templates.'_form-application-result.php');
?>

_form-application-result.php

<?php
	foreach ($input->post as $k=>$v) {


      if ($v != '' && $k != 'g-recaptcha-response') {
        $session->set($k,trim($v));
  ?>

        <div class="row">
            <div class="col-sm-3"><?= ucwords(str_replace('_',' ',$k)) ?></div>
            <div class="col-sm-9"><?= strtoupper($v) ?></div>
        </div>

  <?
      }

    }

 

Link to comment
Share on other sites

  • 2 weeks later...

It's harder to edit files inside Ace editor where you can't get proper debugging, type hinting, autocomplete etc. So what I propose is a way to hook into the module. Then we could:

<?php 
// filtered hook for some specific Hanna code
wire()->addHook('TextformatterHannaCode::getPHP(name="random-post")', function(HookEvent $e) {
  // the arguments specified by the user, inside an associated array
  $args = $e->arguments(0);
  // build markup, 
  // since $vars parameter is an array 
  // we can pass it directly as variables for the template
  $e->return = wireRenderFile('template/file', $vars);
  $e->replace = true;
});

and then inside a php file, you perform your checks, build your markup with given parameters, and return it. Making this function hookable is quite easy, this is enough

<?php 
public function getPHP($name, $code, array $attrs) {}
// would become
public function ___getPHP($name, $code, array $attrs) {}
// just prefixing alone probably woudn't allow filtering hooks though.

 

Link to comment
Share on other sites

1 hour ago, abdus said:

It's harder to edit files inside Ace editor where you can't get proper debugging, type hinting, autocomplete etc.

Actually AceEditor does support this stuff pretty well - I use it in Tracy's Console and Template Editor panels. Perhaps someone could put together a PR for the Hanna code module to add these?

Link to comment
Share on other sites

1 hour ago, abdus said:

It's harder to edit files inside Ace editor where you can't get proper debugging, type hinting, autocomplete etc. So what I propose is a way to hook into the module.

I also dislike editing code outside of my IDE. The workaround currently is pretty simple - just set this for all your PHP Hanna codes:

include($config->paths->templates . 'hannas/' . $hanna->name . '.php');

But I'm in favour of anything that would make it even easier.

  • Like 1
Link to comment
Share on other sites

3 hours ago, adrian said:

Perhaps someone could put together a PR for the Hanna code module to add these?

I made a PR for it.

https://github.com/ryancramerdesign/ProcessHannaCode/pull/19

Changes include:

  • Updating module to ProcessWire namespace. This requires standard library classes be prefixed with \ (PDO -> \PDO etc.)
  • Changing internal references inside ProcessHannaCode for TextFormatterHannaCode to use the module instance in $this->hanna instead.
  • Changing getPHPgetJS, and adding getText method for hooking.

This allows hooking into TextformatterHannaCode::getPHP, TextformatterHannaCode::getJS and TextformatterHannaCode::getText. Inside these hooks you check for the hanna code name, then do as you wish, like so

wire()->addHookBefore('TextformatterHannaCode::getPHP', function (HookEvent $e) {
    if($e->arguments(0) === 'refer') {
        $e->replace = true;
        $args = $e->arguments(2);
        // $e->return = wireRenderFile('refer', $args);
        $e->return = 'rendered template output';
    }
});
 
  • Like 1
Link to comment
Share on other sites

Hmm, one surprising advantage would be addition of shortcodes like in Wordpress. Modules can require, (install if necessary), then hook into Hanna Code and define their own shortcodes to be used in fields. One example would be

<?php
class EmbedShortcodes extends Wire implements Module
{
    public static function getModuleInfo()
    {
        return [
            'title' => 'Shortcodes',
            'version' => '0.0.1',
            'author' => 'abdus',
            'summary' => 'Adds `embed` shortcode',
            'href' => 'https://abdus.co',
            'autoload' => true, // set to true if module should auto-load at boot
            'requires' => [
                'TextformatterHannaCode',
            ],
            'installs' => ['TextformatterHannaCode'],
        ];
    }

    public function ready() {
        $this->addHook('TextformatterHannaCode::getPHP', $this, 'renderEmbed');
    }

    protected function renderEmbed(HookEvent $e) {
        if($e->arguments(0) === 'embed') {
            $e->replace = true;
            $e->return = '<div>embedded output</div>';
        }
    }
}

This works fine for predefined hanna codes, but, for arbitrary shortcodes, it requires a change in the logic of the module where it fetches available hanna codes from database here

<?php
protected function getReplacement($name, array $attrs, &$consume) {

    $database = $this->wire('database');

    $sql = 'SELECT `id`, `type`, `code` FROM hanna_code WHERE `name`=:name';
    $query = $database->prepare($sql);
    bd($name, 'before');
    $query->bindValue(':name', $name, \PDO::PARAM_STR);
    $query->execute();
    if(!$query->rowCount()) return false;
    // here if it cannot find the hanna code it does nothing.
  
    // rest of the function
}

It should be refactored instead into ___getReplacement(), which allows defining access to hanna codes outside the DB.

Once done, we can just [[embed url=youtube.com/asdfgh]] to embed a video etc.

  • Like 1
Link to comment
Share on other sites

  • 1 month later...

Just a suggestion but it'd be really useful if there was

 

  1. a Description field available when creating a HannaCode. I like to keep my HC names short and choppy and a description would greatly help users later on establishing what the HC is for or does
  2. a Description column on the HannaCode overview page too pulling in above Description

It would also be great to be able to see a list of pages where HCs are used within RTEs or templates but that (for me) isn't such a biggie.

 

  • Like 3
Link to comment
Share on other sites

  • 1 month later...

Hi,

I've just installed the Hanna Code module. I wanted to try it out first with something simple - using something like [[title]] to easily insert the current page's title in a textarea.

However, when I try to add a new Hanna Code, if I choose the PHP option, I get a 403 error whenever I hit save.

Could there be a permission I need to change somewhere? Please help!

Thanks,

Margaret

PS. I'm running PW 3.0.62

EDIT: Never mind, it's now working.

I'm not entirely sure how, but I got it to work.

For the benefit of any other newcomers who might experience a similar issue in the future...

First I created a Text/HTML Hanna Code called figurename and just made it output <strong>Boo!</strong>. It let me save it and it worked on my page.

I then edited that code by changing it to PHP - it let me save. I then changed the code to echo $page->title and it let me save again. It now works! :)

I did notice when I initially tried to set up the PHP one it included the opening php tag in the code window, but when I changed the Text one to be PHP that opening tag was omitted. I did a test by adding it back in and once again got the 403 error when I tried to save.

Maybe it's something different in 3.0+, but evidently you can no longer include <?php, even though in the Hanna Code usage notes it says "you may use them when/if necessary".

Link to comment
Share on other sites

  • 3 months later...

Okay folks, I am trying to put a character limit on a body of text. I am using the following function, which is place in the _func.php file:

function wordLimiter($str, $limit = 120, $endstr = '…'){
    $str = strip_tags($str);
    if(strlen($str) <= $limit) return $str;

    $out = substr($str, 0, $limit);
    $pos = strrpos($out, " ");
    if ($pos>0) {
        $out = substr($out, 0, $pos);
    }
    return $out .= $endstr;
}

 

This works just fine on it's own. When placed in Hanna code I get a fatal error, "Call to undefined function wordLimiter()". Code in hanna

<?php 
echo "<div class=\"grid_xs-1\">";

foreach ($pages->find("template=property") as $properties) {
   //attempt at defining $summ to call wordLimitor()
    $summ = wordLimiter($properties->body);
    
    echo "
    <div class=\"col-5 card property\">
        <a href=\"{$properties->url}\">
            <img src=\"{$properties->images->first->size(500,500)->url}\">
        </a>
    </div>
    <div class=\"col-7\">
        <h3>{$properties->title}</h3>
        <p>{$summ}</p>
    </div>
    <div class=\"col-12 grid details\">
        <div class=\"col\">
            <i class=\"fa fa-dollar\" aria-hidden=\"true\"></i> 
            {$properties->price}</div>
        <div class=\"col\">
            <i class=\"fa fa-bed\" aria-hidden=\"true\"></i> 
            {$properties->bedroom}</div>
        <div class=\"col\">
            <i class=\"fa fa-bath\" aria-hidden=\"true\"></i> 
            {$properties->bathroom} </div>
        <div class=\"col\">
            <i class=\"fa fa-arrows\" aria-hidden=\"true\"></i> 
            {$properties->square_feet} SqFt</div>
    </div>";
}
echo "</div>";


I have also tried placing the function wordLimiter() at the top of the Hanna but it give a different error, " Cannot redeclare wordLimiter() "

Am I missing something here? Limitation somewhere?

Link to comment
Share on other sites

5 minutes ago, adrian said:

Might be a namespace issue - try calling it with:


$summ = \wordLimiter($properties->body);

or:


$summ = \ProcessWire\wordLimiter($properties->body);

Not sure what namespace your _func.php file is in.

in _func.php is namespace ProcessWire;

Same errors when given fix was attempted.

Link to comment
Share on other sites

Not sure I have tried to access a function inside a Hanna code before so defining in the code might make sense, or include() 'ing the file.

Or in the Hanna code wrap the function definition in a if(function_exists()) wrapper so the function will only be defined once.

Link to comment
Share on other sites

Hmm, in the same conditions (functions used in other templates, defined in _func.php) i currently have the same error (Call to undefined function). The _func.php file is included ( include_once() ) without an error but the functions seem not be be defined in Hanna code. Would maybe @ryan know?

Link to comment
Share on other sites

9 hours ago, loukote said:

Hmm, in the same conditions (functions used in other templates, defined in _func.php) i currently have the same error (Call to undefined function). The _func.php file is included ( include_once() ) without an error but the functions seem not be be defined in Hanna code. Would maybe @ryan know?

I gave up on the idea. It is messy, but I ended up putting function in template PHP. Works that way. I just rather not have it all spit up into different files. Hard to imagine this being a common bug

Link to comment
Share on other sites

Assuming _func.php is under templates folder, you need to include _func.php in your hanna code like this:

<?php 

include_once $config->paths->templates . '_func.php';

echo "<div class=\"grid_xs-1\">";
foreach ($pages->find("template=property") as $properties) {
// ...

 

  • Like 1
Link to comment
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
×
×
  • Create New...