anttiviljami / wp-pdf-templates

Add PDF templates to your WordPress theme
https://wordpress.org/plugins/wp-pdf-templates
GNU General Public License v3.0
42 stars 18 forks source link

Plugin Conflicts (Easy Digital Downloads, and Awesome Support) #9

Open adaptifyDesigns opened 8 years ago

adaptifyDesigns commented 8 years ago

@anttiviljami Hi again Antti,

I wanted to let you know that the developer of the Awesome Support plugin continued to troubleshoot the issue of your PDF templates not working when FETCH_COOKIES_ENABLED was set to true.

Please read this thread to better understand what I am referring to.

The consensus seems to be that it is an issue with how your plugin handles PHP Sessions. He actually couldn't get your plugin to work AT ALL on his site, whether or not FETCH_COOKIES_ENABLED was defined. He eventually discovered that it was a conflict between your plugin and Easy Digital Downloads (EDD), which is an extremely well known, popular, and quality plugin. So I thought you might want to look into this issue.

He provided a very temporary and "messy" fix, which you can see in the above-linked thread. It may help you to understand the root of the problem.

Pleas take a look and see if you can make a fix ASAP. I would really like to be able to use both your plugin as well as the Awesome Support plugin.

Thanks!

adaptifyDesigns commented 8 years ago

+1 +1,000,000

Any insights here?

Based on the findings of other reputable plugin developers, I'd feel a lot safer if you could take a look at your code and perhaps come up with a fix for the issues outlined above.

Keep me posted.

Thanks.

anttiviljami commented 8 years ago

Hi!

The use of PHP sessions in WordPress plugins in itself is very ugly. ugh But you do have a fair point. Because this plugin requires two parallel PHP heaps to coexist alongside each other, I suppose we have no choice but to unlock the current PHP session if one exists. Apparently you can't have two php heaps using the same session.

Please try the fix here and report if it works, and I'll merge it to master:

https://github.com/Seravo/wp-pdf-templates/pull/11

anttiviljami commented 8 years ago

Thanks for your contribution in finding this issue. :)

anttiviljami commented 8 years ago

Sorry, messed up the first pull request and closed it. Here's a working one: https://github.com/Seravo/wp-pdf-templates/pull/11

adaptifyDesigns commented 8 years ago

Hi Antti,

Thanks so much for getting back to me on this!

Unfortunately I could not get anything to work, hardly at all! Can you please clarify which lines of code to replace (exactly) in the version of wp-pdf-templates.php that is in the current version of the plugin available on the WP Repo?

At first I just replaced my version of wp-pdf-templates.php with the latest version you linked to... that was a mistake, because it became clear that the plugin on github is MUCH different than the plugin I have installed (from the Wordpress repo). So replacing that file totally broke the plugin. Even the file structure was different (it kept failing because it was trying to require_once(vendor/autoload.php) which didn't exist (even the vender directory didn't exist).

So then I wiped the plugin entirely, and re-installed the one from the Wordpress repo.

Then I tried to compare the wp-pdf-templates.php file you linked to (gitHub version) to the one I had from the WP repo, and saw quite a few differences, so I just replaced the entire _use_pdf_template() function (lines 183 to 267 in your version... starts on 177 in WP repo's version) to hopefully catch all the important changes.

... That didn't work either... *sigh... this time the pdf loaded, but did not load the proper template, instead loading the default index-pdf.php (I think because the version you linked to has some weird ://localhost stuff going on... not sure).

So then I copied the entire conditional:

if(isset($wp_query->query_vars['pdf']) || isset($wp_query->query_vars['pdf-preview'])) {

      // we want a html template
      $header = 'Accept:text/html' . "\n";

      // since we're always requesting this from localhost, we need to set the Host
      // header for WordPress to route our request correctly
      $header = 'Host:' . $url['host'] . "\n";

      if( defined('FETCH_COOKIES_ENABLED') && FETCH_COOKIES_ENABLED ) {

        // unlock the session file if a session exists
        if ( !empty( session_id() ) ) {
          session_write_close(); // you can't have two parallel php heaps with the same session id
          // we don't need the session after this point anyway so it should be fine
          // the file_get_contents heap will have its own session and do whatever it needs to
        }

        // pass cookies from current request
        if( isset( $_SERVER['HTTP_COOKIE'] ) ) {
          $header .= 'Cookie: ' . $_SERVER['HTTP_COOKIE'] . "\n";
        }
      }

      // create a request context for file_get_contents
      $context = stream_context_create(array(
        'http' => array(
          'method' => 'GET',
          'header' => $header,
        ),
        'ssl' => array(
          'verify_peer' => false, // since we're using localhost, HTTPS doesn't need peer verification
          'verify_peer_name' => false,
        ),
      ));

      // load the generated html from the template endpoint
      $html = file_get_contents($link, false, $context);

    /*print_r($link);
    die();*/

      // process the html output
      $html = apply_filters('pdf_template_html', $html);

      // pass for printing
      _print_pdf($html);

    }

... And that didn't work either! This time I the pdf template failed to load very quickly, and I got an error so long it was cut off in the error log:

PHP Fatal error:  Uncaught exception 'DOMPDF_Exception' with message 'Requested HTML document contains no data.' in /wp-content/plugins/wp-pdf-templates/dompdf/include/frame_tree.cls.php:122\nStack trace:\n#0 /wp-content/plugins/wp-pdf-templates/dompdf/include/dompdf.cls.php(676): Frame_Tree->build_tree()\n#1 /wp-content/plugins/wp-pdf-templates/dompdf/include/dompdf.cls.php(846): DOMPDF->_process_html()\n#2 /wp-content/plugins/wp-pdf-templates/wp-pdf-templates.php(345): DOMPDF->render()\n#3 /wp-content/plugins/wp-pdf-templates/wp-pdf-templates.php(252): _print_pdf('')\n#4 [internal function]: _use_pdf_template('')\n#5 /wp-includes/plugin.php(503): call_user_func_array('_use_pdf_templa...', Array)\n#6 /wp-includes/template-loader.php(12): do_action('template_redire...')\n#7 /nas/wp/www/cluster-41944/ad in /wp-content/plugins/wp-pdf-templates/dompdf/include/frame_tree.cls.php on line 122, referer: https://warmupandworkout.com/my-account/current-month/

So then I just replaced the following snippet:

// we want a html template
      $header = 'Accept:text/html' . "\n";

      // since we're always requesting this from localhost, we need to set the Host
      // header for WordPress to route our request correctly
      $header = 'Host:' . $url['host'] . "\n";

      if( defined('FETCH_COOKIES_ENABLED') && FETCH_COOKIES_ENABLED ) {

        // unlock the session file if a session exists
        if ( !empty( session_id() ) ) {
          session_write_close(); // you can't have two parallel php heaps with the same session id
          // we don't need the session after this point anyway so it should be fine
          // the file_get_contents heap will have its own session and do whatever it needs to
        }

        // pass cookies from current request
        if( isset( $_SERVER['HTTP_COOKIE'] ) ) {
          $header .= 'Cookie: ' . $_SERVER['HTTP_COOKIE'] . "\n";
        }
      }

      // create a request context for file_get_contents
      $context = stream_context_create(array(
        'http' => array(
          'method' => 'GET',
          'header' => $header,
        ),
        'ssl' => array(
          'verify_peer' => false, // since we're using localhost, HTTPS doesn't need peer verification
          'verify_peer_name' => false,
        ),
      ));

... and that, my friend, also did not work... :-( Upon trying to load a pdf template, I got the following error:

PHP Fatal error:  Uncaught exception 'DOMPDF_Exception' with message 'Requested HTML document contains no data.' in /wp-content/plugins/wp-pdf-templates/dompdf/include/frame_tree.cls.php:122\nStack trace:\n#0 /wp-content/plugins/wp-pdf-templates/dompdf/include/dompdf.cls.php(676): Frame_Tree->build_tree()\n#1 /wp-content/plugins/wp-pdf-templates/dompdf/include/dompdf.cls.php(846): DOMPDF->_process_html()\n#2 /wp-content/plugins/wp-pdf-templates/wp-pdf-templates.php(339): DOMPDF->render()\n#3 /wp-content/plugins/wp-pdf-templates/wp-pdf-templates.php(246): _print_pdf('')\n#4 [internal function]: _use_pdf_template('')\n#5 /wp-includes/plugin.php(503): call_user_func_array('_use_pdf_templa...', Array)\n#6 /wp-includes/template-loader.php(12): do_action('template_redire...')\n#7 /nas/wp/www/cluster-41944/ad in /wp-content/plugins/wp-pdf-templates/dompdf/include/frame_tree.cls.php on line 122, referer: https://warmupandworkout.com/my-account/current-month/

Do you have any idea what's going on?

I'm SUPER confused about how to implement the change you linked to...

Can you tell me exactly what lines of code to replace in the version that is currently on the WP Repo?

Thanks!

adaptifyDesigns commented 8 years ago

@anttiviljami Hi again Antti,

I know you're probably really busy. I just wanted to offer to pay you something in order to encourage you to prioritize this fix.

I'm trying to launch my website on Sunday (two days from now), and the PDF functionality is ESSENTIAL for the business model.

What would it take (in terms of money) to get you to focus on this and work with me to get it resolved in the next 48 hours?

Let me know,

Thanks.

anttiviljami commented 8 years ago

Hi!

Sounds like you have some other issues here as well as just the session thing. Would you be able to give me direct access to your installation so I can take a deeper look?

adaptifyDesigns commented 8 years ago

@anttiviljami Yes for sure. Would you need ftp access? Or can you just use the plugin editor from within the Admin?

You'll need to provide me with your email address so I can create a user and have the password reset link sent to you. Feel free to send me your email address directly to my email: colinsafranek(at)gmail.com

Before you look further, a few things:

I'm hosted on WP-Engine. If you go the "WP Engine" menu page in the Admin, scroll down a bit and you'll find links to access the Live Site Error Logs, and also links to purge all caches if necessary.

Be aware that I'm using a temporary fix in my wp-pdf-templates.php file on lines 226-227 and 232-233, which is allowing me to use the Awesome Support plugin. Currently the pdf templates are working because of this fix. If you remove those lines, AND the Awesome Support plugin is active, the PDF templates will stop working.

My main goals here are to:

  1. be able to use the Awesome Support plugin,
  2. keep FETCH_COOKIES_ENABLED set to TRUE in order to access the $user object within the PDF templates,
  3. ensure the PDF templates are being loaded as fast and efficiently as possible.

In my wp-config.php I've got the following customizations specific to WP PDF Templates:

/** 
 * enable cookies for plugin Wordpress PDF Templates
 * https://wordpress.org/plugins/wp-pdf-templates/faq/
 */
define('FETCH_COOKIES_ENABLED', true);

/**
 * Disable PDF Caching
 */
define('DISABLE_PDF_CACHE', true);

Also, here are some links to test the PDF functionality with:

In my functions.php on lines 200-206 I've added pdf support for the page and session-plan post types only:

/* =============================================================================
   add pdf print support to post type 'affiliate-program' (plugin dep: Wordpress PDF Templates)
   https://wordpress.org/plugins/wp-pdf-templates/faq/
   ========================================================================== */
    if(function_exists('set_pdf_print_support')) {
      set_pdf_print_support( array( 'page', 'session-plan' ) ); 
    }

Ok, thank you for your willingness to help me out!

Please email me with your preferred contact email so I can get you set up with WP creds for my site.

Thanks!

adaptifyDesigns commented 8 years ago

@anttiviljami

Hey Antti,

if you don't want to email me, just give me a way to get you login credentials in a private chat or something. I don't want to post them to a public forum.

Let me know.

adaptifyDesigns commented 8 years ago

@anttiviljami

Dude, I really need some help here.

I'm launching this site live tomorrow evening (Sunday).

It's limping along currently, using the temporary fix I outlined above, but I just ran into another major issue.

Since I'm launching to the public very soon, I removed the define('DISABLE_PDF_CACHE', true); line my from wp-config.php. Now the pdf templates will not load. It gets hung up during the pdf generation, and the chrome pdf loading icon just gets stuck. The page loads, but there is no pdf generated!

Please help!!!!!!

anttiviljami commented 8 years ago

Hi, sorry for disappearing. Was away for the weekend with no internet access. Email me at antti@seravo.fi if you would still like some help with this.

adaptifyDesigns commented 8 years ago

@anttiviljami Hi Antti,

I added you as a user to my staging site (because the site is now live to the public).

Yes, I would still very much like your help with this. I think the issue with the sessions is one you should solve for the plugin, not just for me, but so people who use plugins like Easy Digital Downloads can still use WP PDF Templates also.

I discovered another issue with my setup (besides all that I've written above), and that is with the caching functionality.

First of all the post title needs to sanitized, or the post permalink should be used when creating the cached filename, otherwise, special characters in the post title (like /) will cause issues with the file_put_contents function.

But also, if cookies are enabled, allowing me to query $user info and restrict content based on user role, BUT caching is also enabled, the cached file gets served to the user, regardless of their role.

I would like to propose the addition of another configuration setting to the plugin which would restrict PDF templates only to logged in users, or only to users of a certain role/capability.

It could look something like this:

if ( isset($wp_query->query_vars['pdf-template']) && is_user_logged_in() && current_user_can('manage_options') ) {
    //... normal functionality runs
} else {
    // Redirect them to the my-account/login page:
    wp_redirect( home_url() . '/my-account/' ); 
    exit;
}

Let me know what you think about that.

anttiviljami commented 8 years ago

Hi!

I've uploaded the current version of the plugin with the fix from https://github.com/Seravo/wp-pdf-templates/issues/9.

Can you check if this helped with your problem?

adaptifyDesigns commented 8 years ago

@anttiviljami

Ok, so the PDF functions are executing, because a PDF is being generated, but the template system is not working.

In my functions.php I have declared PDF support for:

/* =============================================================================
   add pdf print support to post type 'affiliate-program' (plugin dep: Wordpress PDF Templates)
   https://wordpress.org/plugins/wp-pdf-templates/faq/
   ========================================================================== */
    if(function_exists('set_pdf_print_support')) {
      set_pdf_print_support( array( 'page', 'session-plan' ) ); 
    }

Here are some single-session-plan.php posts to test (you must be logged in to wordpress to view these pages):

  1. http://adaptify.staging.wpengine.com/session-plan/october-21-2015/
  2. http://adaptify.staging.wpengine.com/session-plan/october-21-2015/pdf-preview
  3. http://adaptify.staging.wpengine.com/session-plan/october-21-2015/pdf

As you can see, the plugin is defaulting to the blog/index page, instead of serving the single-session-plan-pdf.php template. That template is working as expected with the previous version of the plugin.

But the change you made from #9 seems to have solved the sessions issue, in that the pdf generation now works while: a. the Awesome Support plugin is active, and b. the FETCH_COOKIES_ENABLED constant is set to TRUE.

But obviously there are some kinks to be worked out.

adaptifyDesigns commented 8 years ago

@anttiviljami

On further testing, I found that the standard page.php template does work as expected:

  1. http://adaptify.staging.wpengine.com/8-day-on-ramp/8-day-onramp-syllabus-pdf/
  2. http://adaptify.staging.wpengine.com/8-day-on-ramp/8-day-onramp-syllabus-pdf/pdf-preview
  3. http://adaptify.staging.wpengine.com/8-day-on-ramp/8-day-onramp-syllabus-pdf/pdf

Also, the PDF template works for the following custom templates:

  1. one-month-session-plans.php - http://adaptify.staging.wpengine.com/my-account/current-month/ one-month-session-plans-pdf.php - http://adaptify.staging.wpengine.com/my-account/current-month/pdf/
  2. two-weeks-sample-session-plans.php - http://adaptify.staging.wpengine.com/sample-session-plans/ two-weeks-sample-session-plans-pdf.php - http://adaptify.staging.wpengine.com/sample-session-plans/pdf/

So all the custom page templates are working. Really, the only template that isn't working is the single-session-plan-pdf.php template.

Any thoughts on why that might be?

We're getting closer though! I've confirmed that the issue with sessions is in fact solved. I'm restricting content based on the user role/capability, and with cookies enabled, this is working for the pdfs, allowing me to serve a "restricted content" message to those without access. And it is running alongside the Awesome Support plugin. So that is great! Now we just have to figure out why the custom post type template isn't working.

Let me know what you think.

Thanks so much for your help!

adaptifyDesigns commented 8 years ago

@anttiviljami

We're so close!

Just gotta troubleshoot the custom post-type-specific pdf templates and why they are defaulting to the index (blog) page template.

Thanks!

anttiviljami commented 8 years ago

I can't help with debugging this without access to your error logs and source files.

You could try debugging this function https://github.com/Seravo/wp-pdf-templates/blob/master/wp-pdf-templates.php#L264-L293 and see why the logic is defaulting to {your-theme}/index-pdf.php.

adaptifyDesigns commented 8 years ago

So, I've gotten a little closer to figuring out what's going wrong. The only thing I can't understand is why this issue did not arise before now.

Basically I figured out that the single-session-plan-pdf.php templates WP PDF was failing to render were the ones for posts with status 'future'. If the post status is 'published' your plugin has no problem finding and serving it. But if it has 'future' status, then the default index-pdf.php template is called.

This is the filter I'm using to allow 'future' posts to be viewed:

/* =============================================================================
   Show Single Future Posts
   ========================================================================== */
    add_filter('the_posts', 'wuwo_show_future_posts');
    function wuwo_show_future_posts($posts){
       global $wp_query, $wpdb;
       if( is_single() && $wp_query->post_count ==0 || is_singular() && $wp_query->post_count ==0 ){
          $posts = $wpdb->get_results($wp_query->request);
       }
       return $posts;
    };

As you can see the filter hook is the_posts. Is there anything that you may have changed in your plugin's logic that would cause it to be fetching the template after the_posts hook?

adaptifyDesigns commented 8 years ago

Ya, I still can't figure out how to get around this issue, except to manually set the status of the post to 'publish' from within the admin.

I tried using another method of automatically setting 'future' postst to 'publish':

remove_action('future_post', '_future_post_hook');

add_filter( 'wp_insert_post_data', 'futurenow_do_not_set_posts_to_future' );

function futurenow_do_not_set_posts_to_future( $data ) {
    if ( $data['post_status'] == 'future' && $data['post_type'] == 'session-plan' )
        $data['post_status'] = 'publish';
    return $data;
}

But that did not fix the issue either. The only thing that has worked has been to set the post's status manually via the admin interface.

Any ideas why this is?

Also, have you taken a look at this issue yet? That is the final piece to my puzzle.

Thanks for your help!

adaptifyDesigns commented 8 years ago

@anttiviljami

One more thing: is the version of the plugin you installed on my staging site, the same as the one that is available via the wordpress repo?

Seems there were some major restructures of the file directories, etc.

If I decide to use the version on my staging site on my live site, will I be able to safely update when new versions are released?

Thanks.

anttiviljami commented 8 years ago

The version of your staging site is from https://github.com/Seravo/wp-pdf-templates/issues/9 and differs quite a bit from the wordpress.org stable release.

The plugin is agnostic as to what the post status is. I see no reason for this behaviour. The only thing I would guess is that again, the secondary php heap can't access the future post template for some reason.

I'd appreciate if you found a solution to this issue. Definitely will merge.

adaptifyDesigns commented 8 years ago

@anttiviljami

Sorry man. I wish I could figure out why this is happening, but I am not advanced enough to understand the issue very well. My solution was to use the plugin "The Future Is Now" which uses the following function to change any post with a future publish date to publish status:

remove_action('future_post', '_future_post_hook');

add_filter( 'wp_insert_post_data', 'futurenow_do_not_set_posts_to_future' );

function futurenow_do_not_set_posts_to_future( $data ) {
    if ( $data['post_status'] == 'future' && $data['post_type'] == 'session-plan' )
        $data['post_status'] = 'publish';
    return $data;
}

I changed the post_type to session-plan to meet my own needs, then went into the WP Admin and bulk edited all my session-plan posts, changing their status to 'publish'. It worked, so that now all the posts with future dates have the 'publish' status, and your plugin successfully fetches them for PDF generation.

I went ahead and did the same to my live site, so I'm ready to start using version #9, but I'll wait till you push that to the stable WP Repo. Do you plan to do that anytime soon?

Thanks for your help!