civicrm.shortcodes.php 21 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168
<?php
/*
 +--------------------------------------------------------------------+
 | CiviCRM version 4.5                                                |
 +--------------------------------------------------------------------+
 | Copyright CiviCRM LLC (c) 2004-2013                                |
 +--------------------------------------------------------------------+
 | This file is a part of CiviCRM.                                    |
 |                                                                    |
 | CiviCRM is free software; you can copy, modify, and distribute it  |
 | under the terms of the GNU Affero General Public License           |
 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception.   |
 |                                                                    |
 | CiviCRM is distributed in the hope that it will be useful, but     |
 | WITHOUT ANY WARRANTY; without even the implied warranty of         |
 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.               |
 | See the GNU Affero General Public License for more details.        |
 |                                                                    |
 | You should have received a copy of the GNU Affero General Public   |
 | License and the CiviCRM Licensing Exception along                  |
 | with this program; if not, contact CiviCRM LLC                     |
 | at info[AT]civicrm[DOT]org. If you have questions about the        |
 | GNU Affero General Public License or the licensing of CiviCRM,     |
 | see the CiviCRM license FAQ at http://civicrm.org/licensing        |
 +--------------------------------------------------------------------+
*/

/**
 *
 * @package CRM
 * @copyright CiviCRM LLC (c) 2004-2013
 *
 */


// this file must not accessed directly
if ( ! defined( 'ABSPATH' ) ) exit;


/**
 * Define CiviCRM_For_WordPress_Shortcodes Class
 */
class CiviCRM_For_WordPress_Shortcodes {


  /**
   * Declare our properties
   */

  // init property to store reference to Civi
  public $civi;
    
  // init property to store shortcodes
  public $shortcodes = array();
    
  // init property to store shortcode markup
  public $shortcode_markup = array();
  
  // count multiple passes of do_shortcode in a post
  public $shortcode_in_post = array();


  /**
   * Instance constructor
   *
   * @return object $this The object instance
   */
  function __construct() {
    
    // store reference to Civi object
    $this->civi = civi_wp();
    
    return $this;
    
  }


  /**
   * Register hooks to handle the presence of shortcodes in content
   *
   * @return void
   */
  public function register_hooks() {

    // register the CiviCRM shortcode
    add_shortcode( 'civicrm', array( $this, 'render_single' ) );
    
    // add CiviCRM core resources when a shortcode is detected in the post content
    add_action( 'wp', array( $this, 'prerender' ), 10, 1 );
        
  }


  /**
   * Determine if a CiviCRM shortcode is present in any of the posts about to be displayed
   * Callback method for 'wp' hook, always called from WP front-end
   *
   * @param object $wp The WP object, present but not used
   * @return void
   */
  public function prerender( $wp ) {

    /**
     * At this point, all conditional tags are available
     * @see http://codex.wordpress.org/Conditional_Tags
     */
    
    // bail if this is a 404
    if ( is_404() ) return;
    
    // a counter's useful
    $shortcodes_present = 0;
    
    // let's loop through the results
    // this also has the effect of bypassing the logic in
    // https://github.com/civicrm/civicrm-wordpress/pull/36
    if ( have_posts() ) {
      while ( have_posts() ) : the_post();
        
        global $post;
      
        // check for existence of shortcode in content
        if ( has_shortcode( $post->post_content, 'civicrm' ) ) {
          
          // if on first instance...
          if ( !isset( $this->shortcode_present ) ) {
          
            // add core resources for front end
            add_action( 'wp', array( $this->civi, 'front_end_page_load' ), 100 );
            
          }
          
          // get CiviCRM shortcodes in this post
          $shortcodes_array = $this->get_for_post( $post->post_content );
          
          // sanity check
          if ( !empty( $shortcodes_array ) ) {
            
            // add it to our property
            $this->shortcodes[$post->ID] = $shortcodes_array;
            
            // bump shortcode counter
            $shortcodes_present += count( $this->shortcodes[$post->ID] );
          
          }
          
        }
        
      endwhile;
    }
    
    // reset loop
    rewind_posts();
    
    // did we get any?
    if ( $shortcodes_present ) {
      
      // how should we handle multiple shortcodes?
      if ( $shortcodes_present > 1 ) {
        
        // let's add dummy markup
        foreach( $this->shortcodes AS $post_id => $shortcode_array ) {
        
          // set flag if there are multple shortcodes in this post
          $multiple = ( count( $shortcode_array ) > 1 ) ? 1 : 0;
          
          foreach( $shortcode_array AS $shortcode ) {
            
169
            // mimic invoke in multiple shortcode context
170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332
            $this->shortcode_markup[$post_id][] = $this->render_multiple( $post_id, $shortcode, $multiple );
            
          }
          
        }
        
      } else {
        
        // since we have only one shortcode, run the_loop again
        // the DB query has already been done, so this has no significant impact
        if ( have_posts() ) {
          while ( have_posts() ) : the_post();
          
            global $post;
            
            // is this the post?
            if ( ! array_key_exists( $post->ID, $this->shortcodes ) ) {
              continue;
            }
            
            // the shortcode must be the first item in the shortcodes array
            $shortcode = $this->shortcodes[$post->ID][0];
            
            // check to see if a shortcode component has been repeated?
            $atts = $this->get_atts( $shortcode );
            
            // test for hijacking
            if ( isset( $atts['hijack'] ) AND $atts['hijack'] == '1' ) {
              add_filter( 'civicrm_context', array( $this, 'get_context' ) );
            }
            
            // store corresponding markup
            $this->shortcode_markup[$post->ID][] = do_shortcode( $shortcode );
            
            // test for hijacking
            if ( isset( $atts['hijack'] ) AND $atts['hijack'] == '1' ) {
              
              // ditch the filter
              remove_filter( 'civicrm_context', array( $this, 'get_context' ) );
              
              // set title
              global $civicrm_wp_title;
              $post->post_title = $civicrm_wp_title;
              
              // override page title
              add_filter( 'wp_title', array( $this->civi, 'override_page_title' ), 50, 3 );
    
              // overwrite content
              add_filter( 'the_content', array( $this, 'get_content' ) );
              
            }
            
          endwhile;
        }
        
        // reset loop
        rewind_posts();
    
      }
      
    }
      
    // flag that we have parsed shortcodes
    $this->shortcodes_parsed = TRUE;
    
    // broadcast this as well
    do_action( 'civicrm_shortcodes_parsed' );
  
  }


  /**
   * Handles CiviCRM-defined shortcodes
   *
   * @param array Shortcode attributes array
   * @return string HTML for output
   */
  public function render_single( $atts ) {
    
    // check if we've already parsed this shortcode
    global $post;
    if ( is_object($post) ) {
      if ( !empty( $this->shortcode_markup ) ) {
        if ( isset( $this->shortcode_markup[$post->ID] ) ) {
          
          // set counter flag
          if ( ! isset( $this->shortcode_in_post[$post->ID] ) ) {
            $this->shortcode_in_post[$post->ID] = 0;
          } else {
            $this->shortcode_in_post[$post->ID]++;
          }
          
          // this shortcode must have been rendered
          return $this->shortcode_markup[$post->ID][$this->shortcode_in_post[$post->ID]];
          
        }
      }
    }
    
    // preprocess shortcode attributes
    $args = $this->preprocess_atts( $atts );
    
    // invoke() requires environment variables to be set
    foreach ( $args as $key => $value ) {
      if ( $value !== NULL ) {
        $_REQUEST[$key] = $_GET[$key] = $value;
      }
    }

    // kick out if not CiviCRM
    if (!$this->civi->initialize()) {
      return '';
    }

    // check permission
    $argdata = $this->civi->get_request_args();
    if ( ! $this->civi->users->check_permission( $argdata['args'] ) ) {
      return $this->civi->users->get_permission_denied();;
    }

    // CMW: why do we need this? Nothing that follows uses it...
    require_once ABSPATH . WPINC . '/pluggable.php';
    
    ob_start(); // start buffering
    $this->civi->invoke(); // now, instead of echoing, shortcode output ends up in buffer
    $content = ob_get_clean(); // save the output and flush the buffer
    return $content;

  }


  /**
   * Return a generic display for a shortcode instead of a CiviCRM invocation
   *
   * @param int $post_id The containing WordPress post ID
   * @param str $shortcode The shortcode being parsed
   * @param bool $multiple Boolean flag, TRUE if post has multiple shortcodes, FALSE otherwise
   * @return str $markup Generic markup for multiple instances
   */
  private function render_multiple( $post_id = FALSE, $shortcode = FALSE, $multiple = 0 ) {
    
    // get attributes
    $atts = $this->get_atts( $shortcode );
    
    // pre-process shortcode and retrieve args
    $args = $this->preprocess_atts( $atts );
    
    // get data for this shortcode
    $data = $this->get_data( $atts, $args );
    
    // sanity check
    if ( $data === FALSE ) return '';
    
    // did we get a title?
    $title = __( 'Content via CiviCRM', 'civicrm' );
    if ( ! empty( $data['title'] ) ) $title = $data['title'];
    
    // init title flag
    $show_title = TRUE;
    
    // default link
    $link = get_permalink( $post_id );
    
333 334 335
    // default to no class
    $class = '';
    
336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358
    // do we have multiple shortcodes?
    if ( $multiple != 0 ) {
      
      $links = array();    
      foreach( $args AS $var => $arg ) {
        if ( ! empty( $arg ) AND $var != 'q' ) {
          $links[] = $var . '=' . $arg;
        }
      }
      $query = implode( '&', $links );
      
      $config = CRM_Core_Config::singleton();
      
      // $path, $query, $absolute, $fragment, $htmlize, $frontend, $forceBackend
      $link = $config->userSystem->url($args['q'], $query, FALSE, NULL, FALSE, FALSE, TRUE);
      
      // FIXME: unfortunately, there's a bug in $config->userSystem->url() that prevents
      // it from returning the correct URL when on an archive...
      $split = explode( '?', $link );
      
      // we should try and discover the wpBasePage, but anywhere with a Civi querystring will work
      $link = get_permalink( $post_id ) . '?' . $split[1];
      
359 360 361
      // add a class for styling purposes
      $class = ' civicrm-shortcode-multiple';
        
362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380
    }
    
    // test for hijacking
    if ( !$multiple ) {
      
      if ( isset( $atts['hijack'] ) AND $atts['hijack'] == '1' ) {
        
        // add title to array
        $this->post_titles[$post_id] = $data['title'];
        
        // override title
        add_filter( 'the_title', array( $this, 'get_title' ), 100, 2 );
        
        // overwrite content
        add_filter( 'the_content', array( $this, 'get_content' ) );
        
        // don't show title
        $show_title = FALSE;
        
381 382 383
        // add a class for styling purposes
        $class = ' civicrm-shortcode-single';
        
384 385 386 387 388 389 390 391 392 393 394 395 396
      }
      
    }
  
    /*
    print_r( array(
      'atts' => $atts,
      'args' => $args,
      'data' => $data,
      'link' => $link,
    ) );
    */
    
397
    // set some template variables
398
    
399 400
    // description
    $description = FALSE;
401
    if ( isset( $data['text'] ) AND ! empty( $data['text'] ) ) {
402
      $description = $data['text'];
403 404 405
    }
    
    // provide an enticing link
406
    $more_link = sprintf(
407 408 409
      '<a href="%s">%s</a>',
      $link,
      apply_filters( 'civicrm_shortcode_more_link', __( 'Find out more...', 'civicrm' ) )
410
    );
411 412 413
    
    // let's have a footer
    $civi = __( 'CiviCRM.org - Growing and Sustaining Relationships', 'civicrm' );
414 415 416 417
    $logo = '<div class="empowered-by-logo"><span>' . __( 'CiviCRM', 'civicrm' ) . '</span></div>';
    $civi_link = '<a href="http://civicrm.org/" title="' . $civi . '" target="_blank" class="empowered-by-link">' . $logo . '</a>';
    $empowered = sprintf( __( 'Empowered by %s', 'civicrm' ), $civi_link );
    $footer = apply_filters( 'civicrm_shortcode_footer', $empowered );
418
    
419 420
    // start buffering
    ob_start();
421
    
422 423 424 425 426 427
    // include template
    include( CIVICRM_PLUGIN_DIR . 'assets/templates/civicrm.shortcode.php' );
    
    // save the output and flush the buffer
    $markup = ob_get_clean();

428
    // allow plugins to override
429
    return apply_filters( 'civicrm_shortcode_render_multiple', $markup, $post_id, $shortcode );
430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798
    
  }


  /**
   * In order to hijack the page, we need to override the context
   *
   * @return str Overridden context code
   */
  public function get_context() {
    return 'nonpage';
  }


  /**
   * In order to hijack the page, we need to override the content
   *
   * @return str Overridden content
   */
  public function get_content( $content ) {
    
    global $post;
    
    // is this the post?
    if ( ! array_key_exists( $post->ID, $this->shortcode_markup ) ) {
      return $content;
    }
    
    // bail if it has multiple shortcodes
    if ( count( $this->shortcode_markup[$post->ID] ) > 1 ) {
      return $content;
    }
    
    return $this->shortcode_markup[$post->ID][0];
    
  }


  /**
   * In order to hijack the page, we need to override the title
   *
   * @return str Overridden title
   */
  public function get_title( $title, $post_id ) {
    
    // is this the post?
    if ( ! array_key_exists( $post_id, $this->shortcode_markup ) ) {
      return $title;
    }
    
    // bail if it has multiple shortcodes
    if ( count( $this->shortcode_markup[$post_id] ) > 1 ) {
      return $title;
    }
    
    $title = $this->post_titles[$post_id];
    //print_r( $this->post_titles );
    
    return $title;
    
  }


  /**
   * Detect and return CiviCRM shortcodes in post content
   *
   * @param $content The content to parse
   * @return array $shortcodes Array of shortcodes
   */
  private function get_for_post( $content ) {
  
    // init return array
    $shortcodes = array();
      
    // attempt to discover all instances of the shortcode
    $pattern = get_shortcode_regex();
    
    if ( 
      preg_match_all( '/' . $pattern . '/s', $content, $matches )
      && array_key_exists( 2, $matches )
      && in_array( 'civicrm', $matches[2] ) )
    {
    
      // get keys for our shortcode
      $keys = array_keys( $matches[2], 'civicrm' );
      
      foreach( $keys AS $key ) {
        $shortcodes[] = $matches[0][$key];
      }
      
    }
    
    return $shortcodes;
    
  }


  /**
   * Return attributes for a given CiviCRM shortcode
   *
   * @param $shortcode The shortcode to parse
   * @return array $shortcode_atts Array of shortcode attributes
   */
  private function get_atts( $shortcode ) {
    
    // strip all but attributes definitions
    $text = str_replace( '[civicrm ', '', $shortcode );
    $text = str_replace( ']', '', $text );
    
    // extract attributes
    $shortcode_atts = shortcode_parse_atts( $text );
    
    return $shortcode_atts;
    
  }


  /**
   * Preprocess CiviCRM-defined shortcodes
   *
   * @param array $atts Shortcode attributes array
   * @return void
   */
  public function preprocess_atts( $atts ) {
    
    extract( shortcode_atts( array(
      'component' => 'contribution',
      'action' => NULL,
      'mode' => NULL,
      'id' => NULL,
      'cid' => NULL,
      'gid' => NULL,
      'cs' => NULL,
      'force' => NULL,
      ),
      $atts
    ) );

    $args = array(
      'reset' => 1,
      'id'    => $id,
      'force' => $force,
    );

    switch ( $component ) {

      case 'contribution':

        if ( $mode == 'preview' || $mode == 'test' ) {
          $args['action'] = 'preview';
        }
        $args['q'] = 'civicrm/contribute/transact';
        break;

      case 'event':

        switch ( $action ) {
          case 'register':
            $args['q'] = 'civicrm/event/register';
            if ( $mode == 'preview' || $mode == 'test' ) {
              $args['action'] = 'preview';
            }
            break;

          case 'info':
            $args['q'] = 'civicrm/event/info';
            $_REQUEST['page'] = $_GET['page'] = 'CiviCRM';
            break;

          default:
            echo '<p>' . __( 'Do not know how to handle this shortcode', 'civicrm' ) . '</p>';
            return;
        }
        break;

      case 'user-dashboard':

        $args['q'] = 'civicrm/user';
        unset( $args['id'] );
        break;

      case 'profile':

        if ($mode == 'edit') {
          $args['q'] = 'civicrm/profile/edit';
        }
        elseif ($mode == 'view') {
          $args['q'] = 'civicrm/profile/view';
        }
        elseif ($mode == 'search') {
          $args['q'] = 'civicrm/profile';
        }
        else {
          $args['q'] = 'civicrm/profile/create';
        }
        $args['gid'] = $gid;
        break;


      case 'petition':

        $args['q'] = 'civicrm/petition/sign';
        $args['sid'] = $args['id'];
        unset($args['id']);
        break;

      default:

        echo '<p>' . __( 'Do not know how to handle this shortcode', 'civicrm' ) . '</p>';
        return;

    }

    return $args;

  }


  /**
   * Post-process CiviCRM-defined shortcodes
   *
   * @param array $atts Shortcode attributes array
   * @param array $args Shortcode arguments array
   * @return void
   */
  public function get_data( $atts, $args ) {
    
    // init return array
    $data = array();
    
    if (!$this->civi->initialize()) {
      return FALSE;
    }

    // get the Civi entity via the API
    $params = array( 
      'version' => 3,
      'page' => 'CiviCRM',
      'q' => 'civicrm/ajax/rest',
      'sequential' => '1',
    );
    
    switch ( $atts['component'] ) {

      case 'contribution':

        // add event ID
        $params['id'] = $args['id'];
        
        // call API
        $civi_entity = civicrm_api( 'contribution_page', 'getsingle', $params );
        
        // set title
        $data['title'] = $civi_entity['title'];
        
        // set text, if present
        $data['text'] = '';
        if ( isset( $civi_entity['intro_text'] ) ) {
          $data['text'] = $civi_entity['intro_text'];
        }
        
        break;

      case 'event':

        // add event ID
        $params['id'] = $args['id'];
        
        // call API
        $civi_entity = civicrm_api( 'event', 'getsingle', $params );
        
        // set title
        switch ( $atts['action'] ) {
          case 'register':
            $data['title'] = sprintf( 
              __( 'Register for %s', 'civicrm' ),
              $civi_entity['title']
            );
            break;

          case 'info':
          default:
            $data['title'] = $civi_entity['title'];
            break;
        }
        
        // set text, if present
        $data['text'] = '';
        if ( isset( $civi_entity['summary'] ) ) {
          $data['text'] = $civi_entity['summary'];
        }
        if (
          // summary is not present or is empty
          ( !isset($civi_entity['summary']) OR empty($civi_entity['summary']) )
          AND 
          // we do have a description
          isset( $civi_entity['description'] ) AND !empty( $civi_entity['description'] ) 
        ) {
          // override with description
          $data['text'] = $civi_entity['description'];
        }
        
        break;

      case 'user-dashboard':

        // set title
        $data['title'] = __( 'Dashboard', 'civicrm' );
        break;

      case 'profile':
        
        // add event ID
        $params['id'] = $args['gid'];
        
        // call API
        $civi_entity = civicrm_api( 'uf_group', 'getsingle', $params );
    
        // set title
        $data['title'] = $civi_entity['title'];
        
        // set text to empty
        $data['text'] = '';
        break;


      case 'petition':

        // add petition ID
        $params['id'] = $atts['id'];
        
        // call API
        $civi_entity = civicrm_api( 'survey', 'getsingle', $params );
        
        // set title
        $data['title'] = $civi_entity['title'];
        
        // set text, if present
        $data['text'] = '';
        if ( isset( $civi_entity['instructions'] ) ) {
          $data['text'] = $civi_entity['instructions'];
        }
        
        break;

      default:
        
        // do we need to protect against malformed shortcodes?
        break;

    }

    /*
    print_r( array(
      'atts' => $atts,
      'args' => $args,
      'civi_entity' => $civi_entity,
      'data' => $data,
    ) );
    */
      
    return $data;

  }


} // class CiviCRM_For_WordPress_Shortcodes ends