Plugin Directory

Changeset 1414159


Ignore:
Timestamp:
05/10/2016 08:21:02 PM (10 years ago)
Author:
ema-digital
Message:

updating to rollbar v.1.1.0

Location:
rollbar-logging/trunk
Files:
5 added
5 edited

Legend:

Unmodified
Added
Removed
  • rollbar-logging/trunk/README.txt

    r1370860 r1414159  
    44Tags: rollbar, developer, error logging, error tracking
    55Requires at least: 4.4
    6 Tested up to: 4.4.2
    7 Stable tag: 1.0.0
     6Tested up to: 4.5.1
     7Stable tag: 1.1.0
    88License: GPLv2 or later
    99License URI: http://www.gnu.org/licenses/gpl-2.0.html
     
    4747== Changelog ==
    4848
     49= 1.1.0 =
     50* Added option to pause all logging
     51* New interface for configuration
     52* Adding new option to ignore specific JavaScript errors on the front end.
     53
    4954= 1.0.0 =
    5055* Initial Release
    5156
    5257== Upgrade Notice ==
     58= 1.1.0 =
     59* Easier configuration options
    5360
    5461= 1.0.0 =
  • rollbar-logging/trunk/lib/RollbarAdminConfig.php

    r1370860 r1414159  
    1111   */
    1212  public function __construct() {
    13       add_action( 'admin_menu', array( $this, 'add_plugin_page' ) );
    14       add_action( 'admin_init', array( $this, 'page_init' ) );
     13    add_action( 'admin_menu', array( $this, 'add_plugin_page' ) );
     14    add_action( 'admin_init', array( $this, 'page_init' ) );
     15    add_action( 'admin_init', array( $this, 'add_options_sections' ) );
     16    add_action( 'admin_init', array( $this, 'add_global_options_fields' ) );
     17    add_action( 'admin_init', array( $this, 'add_js_options_fields' ) );
     18    add_action( 'admin_init', array( $this, 'add_php_options_fields' ) );
     19    add_action( 'admin_enqueue_scripts', array( $this, 'load_scripts' ) );
     20   
    1521  }
    1622
     
    2733      array( $this, 'create_admin_page' )
    2834    );
     35   
     36  }
     37 
     38  public function load_scripts($hook) {
     39    if( $hook !== 'settings_page_rollbar-logging-config' ) {
     40      return;
     41    }
     42   
     43    wp_register_script( 'rollbar-logging', plugin_dir_url( dirname( __FILE__ ) ) . 'js/admin.js', array('jquery'), '1.0.0' );
     44    wp_enqueue_script('rollbar-logging');
     45   
     46    wp_register_style( 'rollbar-logging', plugin_dir_url( dirname( __FILE__ ) ) . 'css/style.css', array(), '1.0.0' );
     47    wp_enqueue_style('rollbar-logging');
     48   
    2949  }
    3050
     
    3757    ?>
    3858    <div class="wrap">
    39       <h2><?php _e( 'Rollbar Logging Config', 'rollbar-logging' ); ?></h2>
    40       <form method="post" action="options.php">
     59      <h1><?php _e( 'Rollbar Logging Configuration', 'rollbar-logging' ); ?></h1>
     60      <form method="post" action="options.php" id="rollbar-logging-form">
    4161      <?php
    4262        // This prints out all hidden setting fields
    4363        settings_fields( 'rollbar_config_options' );
    44         do_settings_sections( 'rollbar-config-setting-admin' );
     64        do_settings_sections( 'rollbar-config-global-setting-admin' );
     65      ?>
     66      <ul class="rollbar-logging-tabs">
     67        <li><a class="rollbar-logging-js-handle" href="#rollbar-logging-js"><?php _e( 'JavaScript', 'rollbar-logging' ); ?></a></li>
     68        <li><a class="rollbar-logging-php-handle" href="#rollbar-logging-php"><?php _e( 'PHP', 'rollbar-logging' ); ?></a></li>
     69      </ul>
     70      <div class="rollbar-logging-tab-panel rollbar-logging-js-tab" id="rollbar-logging-js">
     71        <?php do_settings_sections( 'rollbar-config-javascript-setting-admin' ); ?>
     72      </div>
     73      <div class="rollbar-logging-tab-panel rollbar-logging-php-tab" id="rollbar-logging-php">
     74        <?php do_settings_sections( 'rollbar-config-php-setting-admin' ); ?>
     75      </div>
     76      <?php
    4577        submit_button();
    4678      ?>
     
    5991      array( $this, 'sanitize' ) // Sanitize
    6092    );
    61 
     93  }
     94 
     95  public function add_options_sections() {
     96    // Sections
    6297    add_settings_section(
    63       'rollbar_config_section', // ID
    64       'Tokens and Environment', // Title
     98      'rollbar_config_global_section', // ID
     99      __( 'Global Settings', 'rollbar-logging' ), // Title
    65100      array( $this, 'print_config_info' ), // Callback
    66       'rollbar-config-setting-admin' // Page
     101      'rollbar-config-global-setting-admin' // Page
    67102    );
    68103   
    69104    add_settings_section(
    70       'rollbar_config_options_section', // ID
    71       'Extra Options', // Title
     105      'rollbar_config_javascript_section', // ID
     106      __( 'JavaScript', 'rollbar-logging' ), // Title
     107      array( $this, 'print_config_info' ), // Callback
     108      'rollbar-config-javascript-setting-admin' // Page
     109    );
     110   
     111    add_settings_section(
     112      'rollbar_config_php_section', // ID
     113      __( 'PHP', 'rollbar-logging' ), // Title
    72114      array( $this, 'print_options_info' ), // Callback
    73       'rollbar-config-setting-admin' // Page
    74     );
    75 
     115      'rollbar-config-php-setting-admin' // Page
     116    );
     117 
     118  }
     119 
     120  public function add_global_options_fields() {
     121    add_settings_field(
     122      'environment',
     123      __( 'Environment Name', 'rollbar-logging' ),
     124      array( $this, 'environment_callback' ),
     125      'rollbar-config-global-setting-admin',
     126      'rollbar_config_global_section'
     127    );
     128   
     129    add_settings_field(
     130      'pause_all',
     131      __( 'Pause all logging', 'rollbar-logging' ),
     132      array( $this, 'pause_all_callback' ),
     133      'rollbar-config-global-setting-admin',
     134      'rollbar_config_global_section'
     135    );
     136  }
     137 
     138  public function add_php_options_fields() {
     139    add_settings_field(
     140      'post_server_item', // ID
     141      __( 'Server Access Token (post_server_item)', 'rollbar-logging' ), // Title
     142      array( $this, 'post_server_item_callback' ), // Callback
     143      'rollbar-config-php-setting-admin', // Page
     144      'rollbar_config_php_section' // Section
     145    );
     146  }
     147 
     148  public function add_js_options_fields() {
    76149    add_settings_field(
    77150      'post_client_item', // ID
    78       'Client Access Token (post_client_item)', // Title
     151      __( 'Client Access Token (post_client_item)', 'rollbar-logging' ), // Title
    79152      array( $this, 'post_client_item_callback' ), // Callback
    80       'rollbar-config-setting-admin', // Page
    81       'rollbar_config_section' // Section
    82     );
    83 
    84     add_settings_field(
    85       'post_server_item',
    86       'Server Access Token (post_server_item)',
    87       array( $this, 'post_server_item_callback' ),
    88       'rollbar-config-setting-admin',
    89       'rollbar_config_section'
    90     );
    91    
    92     add_settings_field(
    93       'environment',
    94       'Environment Name',
    95       array( $this, 'environment_callback' ),
    96       'rollbar-config-setting-admin',
    97       'rollbar_config_section'
    98     );
    99    
     153      'rollbar-config-javascript-setting-admin', // Page
     154      'rollbar_config_javascript_section' // Section
     155    );
     156
    100157    add_settings_field(
    101158      'verbose',
    102       'Verbose',
    103       array( $this, 'verbose_callback' ),
    104       'rollbar-config-setting-admin',
    105       'rollbar_config_options_section'
     159      __( 'Verbose', 'rollbar-logging' ),
     160      array( $this, 'verbose_callback' ), // Callback
     161      'rollbar-config-javascript-setting-admin',
     162      'rollbar_config_javascript_section'
    106163    );
    107164   
    108165    add_settings_field(
    109166      'jquery',
    110       'Include jQuery Plugin',
    111       array( $this, 'jquery_callback' ),
    112       'rollbar-config-setting-admin',
    113       'rollbar_config_options_section'
    114     );
     167      __( 'Include jQuery plugin', 'rollbar-logging' ),
     168      array( $this, 'jquery_callback' ), // Callback
     169      'rollbar-config-javascript-setting-admin',
     170      'rollbar_config_javascript_section'
     171    );
     172   
     173    add_settings_field(
     174      'errors_to_ignore',
     175      __( 'Errors to ignore (1 per line)', 'rollbar-logging' ),
     176      array( $this, 'errors_to_ignore_callback' ), // Callback
     177      'rollbar-config-javascript-setting-admin',
     178      'rollbar_config_javascript_section'
     179    );
     180   
    115181  }
    116182
     
    127193      'environment',
    128194      'verbose',
    129       'jquery'
     195      'jquery',
     196      'pause_all',
     197      'errors_to_ignore'
    130198    );
    131199   
    132200    foreach( $input_keys as $key ) {
    133201      if( isset( $input[$key] ) ) {
    134         $new_input[$key] = trim( sanitize_text_field( $input[$key] ) );
     202        if( $key !== 'errors_to_ignore' ) {
     203          $new_input[$key] = trim( sanitize_text_field( $input[$key] ) );
     204        }
     205        else {
     206          // do not trim textarea
     207          $new_input[$key] = wp_kses( $input[$key] );
     208        }
    135209      }
    136210    }
     
    199273    );
    200274  }
     275 
     276  public function pause_all_callback() {
     277    printf(
     278      '<input type="checkbox" id="pause_all" name="rollbar_logging_config[pause_all]" value="1" %s />',
     279      isset( $this->options['pause_all'] ) ? 'checked="checked"' : ''
     280    );
     281  }
     282 
     283  public function errors_to_ignore_callback() {
     284    printf(
     285      '<textarea id="errors_to_ignore" rows="8" name="rollbar_logging_config[errors_to_ignore]">%s</textarea>',
     286      isset( $this->options['errors_to_ignore'] ) ? esc_textarea( $this->options['errors_to_ignore'] ) : ''
     287    );
     288  }
    201289}
  • rollbar-logging/trunk/lib/RollbarJSLogging.php

    r1370860 r1414159  
    1515  public function init() {
    1616    $verbose = 'false';
     17    $enabled = 'true';
    1718   
    1819    if( isset( $this->option['verbose'] ) ) {
     
    2021    }
    2122   
    22     if( isset( $this->option ) && isset( $this->option['post_client_item'] ) &&  !empty( $this->option['post_client_item'] ) ):
     23    if( isset( $this->option['pause_all'] ) ) {
     24      $enabled = 'false';
     25    }
     26   
     27    if( isset( $this->option ) && isset( $this->option['post_client_item'] ) && !empty( $this->option['post_client_item'] ) ):
    2328    ?>
     29   
    2430    <script>
    2531      var _rollbarConfig = {
     
    2733        captureUncaught: true,
    2834        verbose: <?php echo $verbose; ?>,
     35        enabled: <?php echo $enabled; ?>,
     36        ignoredMessages: [<?php echo $this->ignore(); ?>],
    2937        payload: {
    3038          environment: <?php echo isset( $this->option['environment'] ) ? trim( wp_json_encode( $this->option['environment'] ) ) : '' ?>
     
    3240      };
    3341      // Rollbar Snippet
    34       !function(r){function o(e){if(t[e])return t[e].exports;var n=t[e]={exports:{},id:e,loaded:!1};return r[e].call(n.exports,n,n.exports,o),n.loaded=!0,n.exports}var t={};return o.m=r,o.c=t,o.p="",o(0)}([function(r,o,t){"use strict";var e=t(1).Rollbar,n=t(2);_rollbarConfig.rollbarJsUrl=_rollbarConfig.rollbarJsUrl||"https://d37gvrvc0wt4s1.cloudfront.net/js/v1.8/rollbar.min.js";var a=e.init(window,_rollbarConfig),i=n(a,_rollbarConfig);a.loadFull(window,document,!_rollbarConfig.async,_rollbarConfig,i)},function(r,o){"use strict";function t(r){return function(){try{return r.apply(this,arguments)}catch(o){try{console.error("[Rollbar]: Internal error",o)}catch(t){}}}}function e(r,o,t){window._rollbarWrappedError&&(t[4]||(t[4]=window._rollbarWrappedError),t[5]||(t[5]=window._rollbarWrappedError._rollbarContext),window._rollbarWrappedError=null),r.uncaughtError.apply(r,t),o&&o.apply(window,t)}function n(r){var o=function(){var o=Array.prototype.slice.call(arguments,0);e(r,r._rollbarOldOnError,o)};return o.belongsToShim=!0,o}function a(r){this.shimId=++s,this.notifier=null,this.parentShim=r,this._rollbarOldOnError=null}function i(r){var o=a;return t(function(){if(this.notifier)return this.notifier[r].apply(this.notifier,arguments);var t=this,e="scope"===r;e&&(t=new o(this));var n=Array.prototype.slice.call(arguments,0),a={shim:t,method:r,args:n,ts:new Date};return window._rollbarShimQueue.push(a),e?t:void 0})}function l(r,o){if(o.hasOwnProperty&&o.hasOwnProperty("addEventListener")){var t=o.addEventListener;o.addEventListener=function(o,e,n){t.call(this,o,r.wrap(e),n)};var e=o.removeEventListener;o.removeEventListener=function(r,o,t){e.call(this,r,o&&o._wrapped?o._wrapped:o,t)}}}var s=0;a.init=function(r,o){var e=o.globalAlias||"Rollbar";if("object"==typeof r[e])return r[e];r._rollbarShimQueue=[],r._rollbarWrappedError=null,o=o||{};var i=new a;return t(function(){if(i.configure(o),o.captureUncaught){i._rollbarOldOnError=r.onerror,r.onerror=n(i);var t,a,s="EventTarget,Window,Node,ApplicationCache,AudioTrackList,ChannelMergerNode,CryptoOperation,EventSource,FileReader,HTMLUnknownElement,IDBDatabase,IDBRequest,IDBTransaction,KeyOperation,MediaController,MessagePort,ModalWindow,Notification,SVGElementInstance,Screen,TextTrack,TextTrackCue,TextTrackList,WebSocket,WebSocketWorker,Worker,XMLHttpRequest,XMLHttpRequestEventTarget,XMLHttpRequestUpload".split(",");for(t=0;t<s.length;++t)a=s[t],r[a]&&r[a].prototype&&l(i,r[a].prototype)}return r[e]=i,i})()},a.prototype.loadFull=function(r,o,e,n,a){var i=function(){var o;if(void 0===r._rollbarPayloadQueue){var t,e,n,i;for(o=new Error("rollbar.js did not load");t=r._rollbarShimQueue.shift();)for(n=t.args,i=0;i<n.length;++i)if(e=n[i],"function"==typeof e){e(o);break}}"function"==typeof a&&a(o)},l=!1,s=o.createElement("script"),u=o.getElementsByTagName("script")[0],p=u.parentNode;s.crossOrigin="",s.src=n.rollbarJsUrl,s.async=!e,s.onload=s.onreadystatechange=t(function(){if(!(l||this.readyState&&"loaded"!==this.readyState&&"complete"!==this.readyState)){s.onload=s.onreadystatechange=null;try{p.removeChild(s)}catch(r){}l=!0,i()}}),p.insertBefore(s,u)},a.prototype.wrap=function(r,o){try{var t;if(t="function"==typeof o?o:function(){return o||{}},"function"!=typeof r)return r;if(r._isWrap)return r;if(!r._wrapped){r._wrapped=function(){try{return r.apply(this,arguments)}catch(o){throw o._rollbarContext=t()||{},o._rollbarContext._wrappedSource=r.toString(),window._rollbarWrappedError=o,o}},r._wrapped._isWrap=!0;for(var e in r)r.hasOwnProperty(e)&&(r._wrapped[e]=r[e])}return r._wrapped}catch(n){return r}};for(var u="log,debug,info,warn,warning,error,critical,global,configure,scope,uncaughtError".split(","),p=0;p<u.length;++p)a.prototype[u[p]]=i(u[p]);r.exports={Rollbar:a,_rollbarWindowOnError:e}},function(r,o){"use strict";r.exports=function(r,o){return function(t){if(!t&&!window._rollbarInitialized){var e=window.RollbarNotifier,n=o||{},a=n.globalAlias||"Rollbar",i=window.Rollbar.init(n,r);i._processShimQueue(window._rollbarShimQueue||[]),window[a]=i,window._rollbarInitialized=!0,e.processPayloads()}}}}]);
     42      !function(r){function e(t){if(o[t])return o[t].exports;var n=o[t]={exports:{},id:t,loaded:!1};return r[t].call(n.exports,n,n.exports,e),n.loaded=!0,n.exports}var o={};return e.m=r,e.c=o,e.p="",e(0)}([function(r,e,o){"use strict";var t=o(1).Rollbar,n=o(2);_rollbarConfig.rollbarJsUrl=_rollbarConfig.rollbarJsUrl||"https://d37gvrvc0wt4s1.cloudfront.net/js/v1.9/rollbar.min.js";var a=t.init(window,_rollbarConfig),i=n(a,_rollbarConfig);a.loadFull(window,document,!_rollbarConfig.async,_rollbarConfig,i)},function(r,e){"use strict";function o(r){return function(){try{return r.apply(this,arguments)}catch(e){try{console.error("[Rollbar]: Internal error",e)}catch(o){}}}}function t(r,e,o){window._rollbarWrappedError&&(o[4]||(o[4]=window._rollbarWrappedError),o[5]||(o[5]=window._rollbarWrappedError._rollbarContext),window._rollbarWrappedError=null),r.uncaughtError.apply(r,o),e&&e.apply(window,o)}function n(r){var e=function(){var e=Array.prototype.slice.call(arguments,0);t(r,r._rollbarOldOnError,e)};return e.belongsToShim=!0,e}function a(r){this.shimId=++c,this.notifier=null,this.parentShim=r,this._rollbarOldOnError=null}function i(r){var e=a;return o(function(){if(this.notifier)return this.notifier[r].apply(this.notifier,arguments);var o=this,t="scope"===r;t&&(o=new e(this));var n=Array.prototype.slice.call(arguments,0),a={shim:o,method:r,args:n,ts:new Date};return window._rollbarShimQueue.push(a),t?o:void 0})}function l(r,e){if(e.hasOwnProperty&&e.hasOwnProperty("addEventListener")){var o=e.addEventListener;e.addEventListener=function(e,t,n){o.call(this,e,r.wrap(t),n)};var t=e.removeEventListener;e.removeEventListener=function(r,e,o){t.call(this,r,e&&e._wrapped?e._wrapped:e,o)}}}var c=0;a.init=function(r,e){var t=e.globalAlias||"Rollbar";if("object"==typeof r[t])return r[t];r._rollbarShimQueue=[],r._rollbarWrappedError=null,e=e||{};var i=new a;return o(function(){if(i.configure(e),e.captureUncaught){i._rollbarOldOnError=r.onerror,r.onerror=n(i);var o,a,c="EventTarget,Window,Node,ApplicationCache,AudioTrackList,ChannelMergerNode,CryptoOperation,EventSource,FileReader,HTMLUnknownElement,IDBDatabase,IDBRequest,IDBTransaction,KeyOperation,MediaController,MessagePort,ModalWindow,Notification,SVGElementInstance,Screen,TextTrack,TextTrackCue,TextTrackList,WebSocket,WebSocketWorker,Worker,XMLHttpRequest,XMLHttpRequestEventTarget,XMLHttpRequestUpload".split(",");for(o=0;o<c.length;++o)a=c[o],r[a]&&r[a].prototype&&l(i,r[a].prototype)}return e.captureUnhandledRejections&&(i._unhandledRejectionHandler=function(r){var e=r.reason,o=r.promise,t=r.detail;!e&&t&&(e=t.reason,o=t.promise),i.unhandledRejection(e,o)},r.addEventListener("unhandledrejection",i._unhandledRejectionHandler)),r[t]=i,i})()},a.prototype.loadFull=function(r,e,t,n,a){var i=function(){var e;if(void 0===r._rollbarPayloadQueue){var o,t,n,i;for(e=new Error("rollbar.js did not load");o=r._rollbarShimQueue.shift();)for(n=o.args,i=0;i<n.length;++i)if(t=n[i],"function"==typeof t){t(e);break}}"function"==typeof a&&a(e)},l=!1,c=e.createElement("script"),d=e.getElementsByTagName("script")[0],p=d.parentNode;c.crossOrigin="",c.src=n.rollbarJsUrl,c.async=!t,c.onload=c.onreadystatechange=o(function(){if(!(l||this.readyState&&"loaded"!==this.readyState&&"complete"!==this.readyState)){c.onload=c.onreadystatechange=null;try{p.removeChild(c)}catch(r){}l=!0,i()}}),p.insertBefore(c,d)},a.prototype.wrap=function(r,e){try{var o;if(o="function"==typeof e?e:function(){return e||{}},"function"!=typeof r)return r;if(r._isWrap)return r;if(!r._wrapped){r._wrapped=function(){try{return r.apply(this,arguments)}catch(e){throw e._rollbarContext=o()||{},e._rollbarContext._wrappedSource=r.toString(),window._rollbarWrappedError=e,e}},r._wrapped._isWrap=!0;for(var t in r)r.hasOwnProperty(t)&&(r._wrapped[t]=r[t])}return r._wrapped}catch(n){return r}};for(var d="log,debug,info,warn,warning,error,critical,global,configure,scope,uncaughtError,unhandledRejection".split(","),p=0;p<d.length;++p)a.prototype[d[p]]=i(d[p]);r.exports={Rollbar:a,_rollbarWindowOnError:t}},function(r,e){"use strict";r.exports=function(r,e){return function(o){if(!o&&!window._rollbarInitialized){var t=window.RollbarNotifier,n=e||{},a=n.globalAlias||"Rollbar",i=window.Rollbar.init(n,r);i._processShimQueue(window._rollbarShimQueue||[]),window[a]=i,window._rollbarInitialized=!0,t.processPayloads()}}}}]);
    3543      // End Rollbar Snippet
    3644    </script>
     
    4654  }
    4755 
     56  public function ignore() {
     57    $messages = '';
     58   
     59    if( isset( $this->option['errors_to_ignore'] ) && !empty( $this->option['errors_to_ignore'] ) ) {
     60      $messages = $this->option['errors_to_ignore'];
     61     
     62      $messages = preg_split("/\r\n|\n|\r/", $messages);
     63      $temp = array();
     64     
     65      if( is_array( $messages ) ) {
     66       
     67        foreach( $messages as $message ) {
     68          $temp[] = wp_json_encode($message);
     69        }
     70       
     71        $messages = implode(',', $temp);
     72      }
     73    }
     74   
     75    return $messages;
     76   
     77  }
     78 
    4879}
  • rollbar-logging/trunk/lib/RollbarPHPLogging.php

    r1370860 r1414159  
    1414    $option = get_option( 'rollbar_logging_config' );
    1515   
    16     if( isset( $option ) && isset( $option['post_server_item'] ) && !empty( $option['post_server_item'] ) ) {
    17       // The config options are eventually used in a curl request. Escape accordingly.
    18       $config = array(
    19         // required
    20         'access_token' => trim( urlencode( $option['post_server_item'] ) ),
    21         // optional - environment name. any string will do.
    22         'environment' => isset( $option['post_client_item'] ) ? trim( urlencode( $option['environment'] ) ) : '',
     16    if( !isset( $option['pause_all'] ) ) {
     17      if( isset( $option ) && isset( $option['post_server_item'] ) && !empty( $option['post_server_item'] ) ) {
     18        // The config options are eventually used in a curl request. Escape accordingly.
     19        $config = array(
     20          // required
     21          'access_token' => trim( urlencode( $option['post_server_item'] ) ),
     22          // optional - environment name. any string will do.
     23          'environment' => isset( $option['post_client_item'] ) ? trim( urlencode( $option['environment'] ) ) : '',
     24         
     25        );
     26     
     27        Rollbar::init( $config );
    2328       
    24       );
     29      }
    2530     
    26       Rollbar::init( $config );
    2731    }
    2832  }
  • rollbar-logging/trunk/vendor/rollbar.php

    r1370860 r1414159  
    11<?php
     2include 'Level.php';
     3
    24/**
    35 * Singleton-style wrapper around RollbarNotifier
     
    57 * Unless you need multiple RollbarNotifier instances in the same project, use this.
    68 */
     9if ( !defined( 'BASE_EXCEPTION' ) ) {
     10    define( 'BASE_EXCEPTION', version_compare( phpversion(), '7.0', '<' )? '\Exception': '\Throwable' );
     11}
     12
    713class Rollbar {
    814    /** @var RollbarNotifier */
     
    4652    }
    4753
    48     public static function report_message($message, $level = 'error', $extra_data = null, $payload_data = null) {
     54    public static function report_message($message, $level = Level::ERROR, $extra_data = null, $payload_data = null) {
    4955        if (self::$instance == null) {
    5056            return;
     
    116122    public $use_error_reporting = false;
    117123    public $proxy = null;
     124    public $include_error_code_context = false;
     125    public $include_exception_code_context = false;
    118126
    119127    private $config_keys = array('access_token', 'base_api_url', 'batch_size', 'batched', 'branch',
    120128        'capture_error_backtraces', 'code_version', 'environment', 'error_sample_rates', 'handler',
    121129        'agent_log_location', 'host', 'logger', 'included_errno', 'person', 'person_fn', 'root',
    122         'scrub_fields', 'shift_function', 'timeout', 'report_suppressed', 'use_error_reporting', 'proxy');
     130        'scrub_fields', 'shift_function', 'timeout', 'report_suppressed', 'use_error_reporting', 'proxy',
     131        'include_error_code_context', 'include_exception_code_context');
    123132
    124133    // cached values for request/server/person data
     134    private $_php_context = null;
    125135    private $_request_data = null;
    126136    private $_server_data = null;
     
    138148
    139149    private $_curl_ipresolve_supported;
     150
     151    /** @var iSourceFileReader $_source_file_reader */
     152    private $_source_file_reader;
    140153
    141154    public function __construct($config) {
     
    145158            }
    146159        }
     160        $this->_source_file_reader = new SourceFileReader();
    147161
    148162        if (!$this->access_token && $this->handler != 'agent') {
     
    178192    public function report_exception($exc, $extra_data = null, $payload_data = null) {
    179193        try {
    180             if (!$exc instanceof Exception) {
    181                 throw new Exception('Report exception requires an instance of Exception.');
     194            if ( !is_a( $exc, BASE_EXCEPTION ) ) {
     195                throw new Exception(sprintf('Report exception requires an instance of %s.', BASE_EXCEPTION ));
    182196            }
    183197
     
    192206    }
    193207
    194     public function report_message($message, $level = 'error', $extra_data = null, $payload_data = null) {
     208    public function report_message($message, $level = Level::ERROR, $extra_data = null, $payload_data = null) {
    195209        try {
    196210            return $this->_report_message($message, $level, $extra_data, $payload_data);
     
    238252
    239253    /**
    240      * @param Exception $exc
     254     * @param \Throwable|\Exception $exc
    241255     */
    242     protected function _report_exception(Exception $exc, $extra_data = null, $payload_data = null) {
     256    protected function _report_exception( $exc, $extra_data = null, $payload_data = null) {
    243257        if (!$this->check_config()) {
    244258            return;
     
    261275
    262276        // request, server, person data
    263         $data['request'] = $this->build_request_data();
     277        if ('http' === $this->_php_context) {
     278            $data['request'] = $this->build_request_data();
     279        }
    264280        $data['server'] = $this->build_server_data();
    265281        $data['person'] = $this->build_person_data();
     
    338354
    339355        // set error level and error constant name
    340         $level = 'info';
     356        $level = Level::INFO;
    341357        $constant = '#' . $errno;
    342358        switch ($errno) {
    343359            case 1:
    344                 $level = 'error';
     360                $level = Level::ERROR;
    345361                $constant = 'E_ERROR';
    346362                break;
    347363            case 2:
    348                 $level = 'warning';
     364                $level = Level::WARNING;
    349365                $constant = 'E_WARNING';
    350366                break;
    351367            case 4:
    352                 $level = 'critical';
     368                $level = Level::CRITICAL;
    353369                $constant = 'E_PARSE';
     370        break;
    354371            case 8:
    355                 $level = 'info';
     372                $level = Level::INFO;
    356373                $constant = 'E_NOTICE';
    357374                break;
    358375            case 256:
    359                 $level = 'error';
     376                $level = Level::ERROR;
    360377                $constant = 'E_USER_ERROR';
    361378                break;
    362379            case 512:
    363                 $level = 'warning';
     380                $level = Level::WARNING;
    364381                $constant = 'E_USER_WARNING';
    365382                break;
    366383            case 1024:
    367                 $level = 'info';
     384                $level = Level::INFO;
    368385                $constant = 'E_USER_NOTICE';
    369386                break;
    370387            case 2048:
    371                 $level = 'info';
     388                $level = Level::INFO;
    372389                $constant = 'E_STRICT';
    373390                break;
    374391            case 4096:
    375                 $level = 'error';
     392                $level = Level::ERROR;
    376393                $constant = 'E_RECOVERABLE_ERROR';
    377394                break;
    378395            case 8192:
    379                 $level = 'info';
     396                $level = Level::INFO;
    380397                $constant = 'E_DEPRECATED';
    381398                break;
    382399            case 16384:
    383                 $level = 'info';
     400                $level = Level::INFO;
    384401                $constant = 'E_USER_DEPRECATED';
    385402                break;
     
    605622
    606623    /**
    607      * @param Exception $exc
     624     * @param \Throwable|\Exception $exc
    608625     * @param mixed $extra_data
    609626     * @return array
    610627     */
    611     protected function build_exception_trace(Exception $exc, $extra_data = null)
     628    protected function build_exception_trace($exc, $extra_data = null)
    612629    {
    613630        $message = $exc->getMessage();
     
    629646
    630647    /**
    631      * @param Exception $exc
     648     * @param \Throwable|\Exception $exc
    632649     * @param array $extra_data
    633650     * @return array
    634651     */
    635     protected function build_exception_trace_chain(Exception $exc, $extra_data = null)
     652    protected function build_exception_trace_chain( $exc, $extra_data = null)
    636653    {
    637654        $chain = array();
     
    640657        $previous = $exc->getPrevious();
    641658
    642         while ($previous instanceof Exception) {
     659        while ( is_a( $previous, BASE_EXCEPTION ) ) {
    643660            $chain[] = $this->build_exception_trace($previous);
    644661            $previous = $previous->getPrevious();
     
    649666
    650667    /**
    651      * @param Exception $exc
     668     * @param \Throwable|\Exception $exc
    652669     * @return array
    653670     */
    654     protected function build_exception_frames(Exception $exc) {
     671    protected function build_exception_frames($exc) {
    655672        $frames = array();
    656673
    657674        foreach ($exc->getTrace() as $frame) {
    658             $frames[] = array(
     675            $framedata = array(
    659676                'filename' => isset($frame['file']) ? $frame['file'] : '<internal>',
    660677                'lineno' =>  isset($frame['line']) ? $frame['line'] : 0,
     
    662679                // TODO include args? need to sanitize first.
    663680            );
     681            if($this->include_exception_code_context && isset($frame['file']) && isset($frame['line'])) {
     682                $this->add_frame_code_context($frame['file'], $frame['line'], $framedata);
     683            }
     684            $frames[] = $framedata;
    664685        }
    665686
     
    668689
    669690        // add top-level file and line to end of the reversed array
    670         $frames[] = array(
    671             'filename' => $exc->getFile(),
    672             'lineno' => $exc->getLine()
     691        $file = $exc->getFile();
     692        $line = $exc->getLine();
     693        $framedata = array(
     694            'filename' => $file,
     695            'lineno' => $line
    673696        );
     697        if($this->include_exception_code_context) {
     698            $this->add_frame_code_context($file, $line, $framedata);
     699        }
     700        $frames[] = $framedata;
    674701
    675702        $this->shift_method($frames);
     
    703730                }
    704731
    705                 $frames[] = array(
     732                $framedata = array(
    706733                    // Sometimes, file and line are not set. See:
    707734                    // http://stackoverflow.com/questions/4581969/why-is-debug-backtrace-not-including-line-number-sometimes
     
    710737                    'method' => $frame['function']
    711738                );
     739                if($this->include_error_code_context && isset($frame['file']) && isset($frame['line'])) {
     740                    $this->add_frame_code_context($frame['file'], $frame['line'], $framedata);
     741                }
     742                $frames[] = $framedata;
    712743            }
    713744
     
    716747
    717748            // add top-level file and line to end of the reversed array
    718             $frames[] = array(
     749            $framedata = array(
    719750                'filename' => $errfile,
    720751                'lineno' => $errline
    721752            );
     753            if($this->include_error_code_context) {
     754                $this->add_frame_code_context($errfile, $errline, $framedata);
     755            }
     756            $frames[] = $framedata;
    722757
    723758            $this->shift_method($frames);
     
    747782            }
    748783            $server_data['host'] = $this->host;
     784            $server_data['argv'] = isset($_SERVER['argv']) ? $_SERVER['argv'] : null;
    749785
    750786            if ($this->branch) {
     
    787823    }
    788824
    789     protected function build_base_data($level = 'error') {
     825    protected function build_base_data($level = Level::ERROR) {
     826        if (null === $this->_php_context) {
     827            $this->_php_context = $this->get_php_context();
     828        }
     829
    790830        $data = array(
    791831            'timestamp' => time(),
     
    794834            'language' => 'php',
    795835            'framework' => 'php',
     836            'php_context' => $this->_php_context,
    796837            'notifier' => array(
    797838                'name' => 'rollbar-php',
     
    814855
    815856        if ($this->access_token) {
    816           $payload['access_token'] = $this->access_token;
     857            $payload['access_token'] = $this->access_token;
    817858        }
    818859
     
    893934    }
    894935
     936    protected function get_php_context() {
     937        return php_sapi_name() === 'cli' || defined('STDIN') ? 'cli' : 'http';
     938    }
     939
    895940    protected function make_api_call($action, $access_token, $post_data) {
    896941        $url = $this->base_api_url . $action . '/';
     
    920965
    921966        if ($this->_curl_ipresolve_supported) {
    922           curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
     967            curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
    923968        }
    924969
     
    9831028        $this->_agent_log = fopen($this->agent_log_location . '/rollbar-relay.' . getmypid() . '.' . microtime(true) . '.rollbar', 'a');
    9841029    }
     1030
     1031    protected function add_frame_code_context($file, $line, array &$framedata) {
     1032        $source = $this->get_source_file_reader()->read_as_array($file);
     1033        if (is_array($source)) {
     1034            $source = str_replace(array("\n", "\t", "\r"), '', $source);
     1035            $total = count($source);
     1036            $line = $line - 1;
     1037            $framedata['code'] = $source[$line];
     1038            $offset = 6;
     1039            $min = max($line - $offset, 0);
     1040            if ($min !== $line) {
     1041                $framedata['context']['pre'] = array_slice($source, $min, $line - $min);
     1042            }
     1043            $max = min($line + $offset, $total);
     1044            if ($max !== $line) {
     1045                $framedata['context']['post'] = array_slice($source, $line + 1, $max - $line);
     1046            }
     1047        }
     1048    }
     1049
     1050    protected function get_source_file_reader() { return $this->_source_file_reader; }
    9851051}
    9861052
     
    9901056
    9911057class Ratchetio extends Rollbar {}
     1058
     1059interface iSourceFileReader {
     1060
     1061    /**
     1062     * @param string $file_path
     1063     * @return string[]
     1064     */
     1065    public function read_as_array($file_path);
     1066}
     1067
     1068class SourceFileReader implements iSourceFileReader {
     1069
     1070    public function read_as_array($file_path) { return file($file_path); }
     1071}
Note: See TracChangeset for help on using the changeset viewer.