public function outputHeader()
    {
        ?>
        <div class="wrap">
            <table width="100%">
                <tbody>
                <tr>
                    <td align="left"><h2><?php 
        _e('Import / Export', 'add-actions-and-filters');
        ?>
</h2></td>
                    <td align="right">
                        <a href="<?php 
        echo $this->plugin->getAdminPageUrl();
        ?>
">
                            <img width="128" height="50"
                                 src="<?php 
        echo $this->plugin->getPluginFileUrl('img/icon-256x100.png');
        ?>
">
                        </a>
                    </td>
                </tr>
                </tbody>
            </table>
        </div>
        <?php 
    }
function AddActionsAndFilters_init($file)
{
    require_once 'AddActionsAndFilters_Plugin.php';
    $aPlugin = new AddActionsAndFilters_Plugin();
    // Install the plugin
    // NOTE: this file gets run each time you *activate* the plugin.
    // So in WP when you "install" the plugin, all that does it dump its files in the plugin-templates directory
    // but it does not call any of its code.
    // So here, the plugin tracks whether or not it has run its install operation, and we ensure it is run only once
    // on the first activation
    if (!$aPlugin->isInstalled()) {
        $aPlugin->install();
    } else {
        // Perform any version-upgrade activities prior to activation (e.g. database changes)
        $aPlugin->upgrade();
    }
    // Add callbacks to hooks
    $aPlugin->addActionsAndFilters();
    if (!$file) {
        $file = __FILE__;
    }
    // Register the Plugin Activation Hook
    register_activation_hook($file, array(&$aPlugin, 'activate'));
    // Register the Plugin Deactivation Hook
    register_deactivation_hook($file, array(&$aPlugin, 'deactivate'));
}
 public function display()
 {
     require_once 'AddActionsAndFilters_AdminViewUrlBuilder.php';
     $urlBuilder = new AddActionsAndFilters_AdminViewUrlBuilder();
     $cleanUrl = $urlBuilder->buildUrl();
     // no action value in it
     echo '<div class="wrap">';
     // Header
     $adminUrl = get_admin_url() . 'admin.php?page=';
     printf('<table width="%s"><tbody><tr><td><a href="%s"><img src="%s"/></a></td><td align="right"><span style="white-space: nowrap;"><a href="%s"><img src="%s"/></a><a href="%s"><img src="%s"/></a></span></td></tr></tbody></table>', '100%', $cleanUrl, $this->plugin->getPluginFileUrl('img/admin-banner.png'), $adminUrl . $this->plugin->getImportExportSlug(), $this->plugin->getPluginFileUrl('img/import-export.png'), $adminUrl . $this->plugin->getSettingsSlug(), $this->plugin->getPluginFileUrl('img/settings.png'));
     printf('<table><tbody><tr><td></td></tr></tbody></table>');
     $actions = new AddActionsAndFilters_AdminPageActions();
     printf('<a href="%s%s%s%s%s" class="page-title-action">%s</a>', get_admin_url(), 'admin.php?page=', $this->plugin->getAdminPageSlug(), '&action=', $actions->getEditKey(), __('Add New'));
     // Table Styles
     echo '<style type="text/css">';
     echo '.wp-list-table .column-id { width: 7%; }';
     echo '.wp-list-table .column-enabled { width: 10%; }';
     echo '.wp-list-table .column-shortcode { width: 7%; }';
     echo '.wp-list-table .column-name { width: 25%; }';
     echo '.wp-list-table .column-capability { width: 20%; }';
     echo '.wp-list-table .column-description { width: 31%; }';
     echo '.wp-list-table .item-inactive { font-style: italic; opacity: 0.6; filter: alpha(opacity = 60); /* MSIE */ }';
     echo '</style>';
     // Form for bulk actions
     printf('<form action="%s" method="post">', $cleanUrl);
     // Search box
     $this->table->search_box('search', 'search_id');
     // Code table
     $this->table->display();
     // Closing Tags
     echo '</form>';
     echo '</div>';
 }
 public function updateItem($item)
 {
     $this->ensureAllIndexesSet($item);
     $this->conformInputValues($item);
     global $wpdb;
     $this->plugin->ensureDatabaseTableInstalled();
     // ensure created in multisite
     $table = $this->plugin->getTableName();
     $sql = $wpdb->prepare("update {$table} set name = %s, description = %s, capability = %s, enabled = %d, shortcode = %d, buffer = %d, inadmin = %d, code = %s where id = %d", $item['name'], $item['description'], $item['capability'], $item['enabled'], $item['shortcode'], $item['buffer'], $item['inadmin'], $item['code'], $item['id']);
     $wpdb->query($sql);
     return $item['id'];
 }
    /**
     * Helper-function outputs the correct form element (input tag, select tag) for the given item
     * @param  $aOptionKey string name of the option (un-prefixed)
     * @param  $aOptionMeta mixed meta-data for $aOptionKey (either a string display-name or an array(display-name, option1, option2, ...)
     * @param  $savedOptionValue string current value for $aOptionKey
     * @return void
     */
    protected function createFormControl($aOptionKey, $aOptionMeta, $savedOptionValue)
    {
        if (is_array($aOptionMeta) && count($aOptionMeta) >= 2) {
            // Drop-down list
            $choices = array_slice($aOptionMeta, 1);
            ?>
            <p><select name="<?php 
            echo $aOptionKey;
            ?>
" id="<?php 
            echo $aOptionKey;
            ?>
">
                    <?php 
            foreach ($choices as $aChoice) {
                $selected = $aChoice == $savedOptionValue ? 'selected' : '';
                ?>
                        <option
                            value="<?php 
                echo $aChoice;
                ?>
" <?php 
                echo $selected;
                ?>
><?php 
                echo $this->plugin->getOptionValueI18nString($aChoice);
                ?>
</option>
                        <?php 
            }
            ?>
                </select></p>
            <?php 
        } else {
            // Simple input field
            ?>
            <p><input type="text" name="<?php 
            echo $aOptionKey;
            ?>
" id="<?php 
            echo $aOptionKey;
            ?>
"
                      value="<?php 
            echo esc_attr($savedOptionValue);
            ?>
" size="50"/></p>
            <?php 
        }
    }
 /**
  * Wrapper function for the shortcode code.
  * @param $atts array shortcode attributes
  * @param null|string $content shortcode content
  * @return string
  */
 public function handle_shortcode($atts, $content = null)
 {
     if (isset($this->codeItem['capability']) && $this->codeItem['capability'] && !current_user_can($this->codeItem['capability'])) {
         // if a capability is required and the user doesn't have it,
         // then let the short code do nothing.
         return '';
     }
     $buffer = isset($this->codeItem['buffer']) && $this->codeItem['buffer'];
     if ($buffer) {
         ob_start();
     }
     $result = eval($this->codeItem['code']);
     if ($result === FALSE) {
         $url = $this->plugin->getAdminPageUrl() . "&id={$this->codeItem['id']}&action=edit";
         $result = sprintf("<p>%s Plugin: Error in shortcode [<u><a href='%s' target='_blank'>%s</a></u>]</p>", $this->plugin->getPluginDisplayName(), $url, $this->codeItem['name']);
     }
     if ($buffer) {
         $output = ob_get_contents();
         ob_end_clean();
     } else {
         $output = '';
     }
     return $output . $result;
 }
 /**
  * @param $codeItem array
  */
 public function printErrorMessage($codeItem, $msg = null)
 {
     echo '<div style="background-color: white; text-decoration-color: black">';
     echo '<p>&nbsp;</p>';
     // helps prevent header from covering first line of output
     $url = $this->plugin->getAdminPageUrl() . "&id={$codeItem['id']}&action=edit";
     $name = $codeItem['name'] ? $codeItem['name'] : '(unamed)';
     echo '<p>';
     printf("%s Plugin: Error in user-provided code item named \"%s\". ", $this->plugin->getPluginDisplayName(), $name);
     echo '<br/>';
     if ($msg) {
         echo $msg;
         echo '<br/>';
     }
     printf("<u><a href='%s' target='_blank'>%s</a></u>", $url, __('Fix the code here', 'add-actions-and-filters'));
     echo '</p>';
     echo '<p>&nbsp;</p>';
     echo '</div>';
 }
 public function importScepShortCodes()
 {
     $dataModel = new AddActionsAndFilters_DataModel($this->plugin, null);
     foreach ($_REQUEST as $key => $value) {
         if ($value == 'true') {
             $shortCode = array();
             $shortCode['shortcode'] = true;
             $shortCode['name'] = $key;
             $shortCode['description'] = get_option("scep_description_{$key}");
             $shortCode['enabled'] = get_option("scep_enabled_{$key}");
             $shortCode['buffer'] = get_option("scep_buffer_{$key}");
             $shortCode['code'] = get_option("scep_phpcode_{$key}");
             $shortCode['inadmin'] = 0;
             $shortCode['capability'] = '';
             //$buffer = get_option("scep_buffer_$key");
             //$param = get_option("scep_param_$key");
             $id = $dataModel->saveItem($shortCode);
             $url = $this->plugin->getAdminPageUrl() . "&id={$id}&action=edit";
             echo __('Imported', 'add-actions-and-filters') . " <a target='_blank' href='{$url}'>{$key}</a></br>";
             // Deactivate SCEP shortcode
             update_option("scep_enabled_{$key}", 0);
         }
     }
 }
    /**
     * Output the main contents of the page including the code editor and metadata fields
     * @param $item array created by AddActionsAndFilters_DataModel
     */
    public function outputCodeEditor($item)
    {
        ?>
        <div class="wrap">

            <table width="100%">
                <tbody>
                <tr>
                    <td valign="top">
                        <label for="name"><?php 
        _e('Name');
        ?>
</label>
                    </td>
                    <td valign="top" nowrap>
                        <span id="sc_info_open" style="display: none;">[</span>
                        <input id="name" type="text" value="<?php 
        echo isset($item['name']) ? $item['name'] : '';
        ?>
" size="25"/>
                        <span id="sc_info_close" style="display: none;">]</span>
                    </td>
                    <td valign="top">
                        <label for="description"><?php 
        _e('Description');
        ?>
</label>
                    </td>
                    <td valign="top">
                        <textarea title="description" id="description"
                                  cols="80"><?php 
        echo isset($item['description']) ? $item['description'] : '';
        ?>
</textarea>
                    </td>
                </tr>
                <tr>
                    <td valign="top" colspan="2">
                        <input type="checkbox" id="activated" name="activated"
                               value="true" <?php 
        if (isset($item['enabled']) && $item['enabled']) {
            echo 'checked';
        }
        ?>
>
                        <label for="enabled"><?php 
        _e('Activated');
        ?>
</label>
                        &nbsp;&nbsp;&nbsp;&nbsp;
                        <input type="checkbox" id="shortcode" name="shortcode"
                               value="true" <?php 
        if (isset($item['shortcode']) && $item['shortcode']) {
            echo 'checked';
        }
        ?>
>
                        <label for="shortcode"><?php 
        _e('Shortcode');
        ?>
</label>
                    </td>
                    <td valign="top">
                        <label for="capability"><?php 
        _e('Execute only for', 'add-actions-and-filters');
        ?>
</label>
                    </td>
                    <td valign="top">
                        <select id="capability">
                            <option value=""></option>
                            <?php 
        $cap_found = false;
        foreach ($this->getCapabilityToRolesList() as $cap => $roles) {
            $roles = implode(', ', $roles);
            $selected = '';
            if (isset($item['capability']) && $cap == $item['capability']) {
                $selected = 'selected';
                $cap_found = true;
            }
            echo "<option value=\"{$cap}\" {$selected}>{$cap} ({$roles})</option>";
        }
        if (isset($item['capability']) && !$cap_found) {
            echo "<option value=\"{$item['capability']}\" selected>{$item['capability']}</option>";
        }
        ?>
                        </select>
                    </td>
                </tr>
                <tr>
                    <td colspan="3">
                    </td>
                    <td>
                        <div id="af_info_inadmin" style="display: none;">
                            <input type="checkbox" id="inadmin" name="inadmin"
                                   value="true" <?php 
        if (isset($item['inadmin']) && $item['inadmin']) {
            echo 'checked';
        }
        ?>
>
                            <label for="inadmin"><?php 
        _e('Execute also on Dashboard Pages', 'add-actions-and-filters');
        ?>
</label>
                        </div>
                        <div id="sc_info_buffer" style="display: none;">
                            <input type="checkbox" id="buffer" name="buffer"
                                   value="true" <?php 
        if (!isset($item['buffer']) || isset($item['buffer']) && $item['buffer']) {
            echo 'checked';
        }
        ?>
>
                            <label for="buffer"><?php 
        _e('Code echoes output');
        ?>
</label>
                        </div>
                    </td>
                </tr>
                </tbody>
            </table>


            <div id="sc_info_instructions_open" style="display: none;">
                <code>function handle_shortcode ( $atts, $content = null ) {</code><br/>
            </div>
            <textarea title="code" id="code"><?php 
        echo isset($item['code']) ? $item['code'] : '';
        ?>
</textarea>
            <div id="sc_info_instructions_close" style="display: none;">
                <code>}</code>
            </div>

            <script>
                var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
                    lineNumbers: true,
                    matchBrackets: true,
                    mode: "text/x-php",
                    indentUnit: 4,
                    indentWithTabs: true
                });
            </script>


            <div id="codesavestatus">&nbsp;</div>
            <?php 
        submit_button('Save', 'primary', 'savecode');
        ?>
            <script>
                jQuery(document).ready(function () {
                    jQuery('#savecode').click(function () {
                        var item = {
                            <?php 
        if (isset($item['id'])) {
            echo '"id": ' . $item['id'] . ',';
        }
        ?>
                            "name": jQuery('#name').val(),
                            "description": jQuery('#description').val(),
                            "enabled": jQuery('#activated').is(':checked'),
                            "shortcode": jQuery('#shortcode').is(':checked'),
                            "buffer": jQuery('#buffer').is(':checked'),
                            "inadmin": jQuery('#inadmin').is(':checked'),
                            "capability": jQuery('#capability').val(),
                            "code": editor.getValue()
                        };
                        jQuery.ajax(
                            {
                                "url": "<?php 
        echo admin_url('admin-ajax.php');
        ?>
?action=addactionsandfilters_save",
                                "type": "POST",
                                "data": item,
                                "success": function (data, textStatus) {
                                    window.location.replace('<?php 
        echo $this->plugin->getAdminPageUrl();
        ?>
&id=' + data + '&action=edit');
                                },
                                "error": function (textStatus, errorThrown) {
                                    jQuery("#codesavestatus").html(textStatus.statusText);
                                    console.log(textStatus);
                                    console.log(errorThrown);
                                },
                                "beforeSend": function () {
                                    jQuery("#codesavestatus").html('<img src="<?php 
        echo plugins_url('img/load.gif', __FILE__);
        ?>
">');
                                }
                            }
                        );
                    })
                });
            </script>

            <div id="sc_info_shortcode_instructions" style="display: none;">
                <table width="350px">
                    <tbody>
                    <tr>
                        <td><code>[shortcode arg="value"]</code></td>
                        <td><code>$atts['arg']</code></td>
                    </tr>
                    <tr>
                        <td><code>[shortcode]content[/shortcode]</code></td>
                        <td><code>$content</code></td>
                    </tr>
                    </tbody>
                </table>
            </div>
        </div>
        <div id="af_info_instructions" style="display: none;">

            <?php 
        $action_example = 'function email_friends( $post_ID ) {
    $friends = \'bob@example.org, susie@example.org\';
    wp_mail( $friends, "sally\'s blog updated", \'I just put something on my blog: http://blog.example.com\' );
    return $post_ID;
}
add_action( \'publish_post\', \'email_friends\' );';
        $filter_example = 'function prefix_title( $title, $id = null ) {
    return "The title is: $title";
}
add_filter( \'the_title\', \'prefix_title\', 10, 2 );';
        ?>
            <table>
                <tbody>
                <tr>
                    <td><h3 style="margin:0">Add Action</h3></td>
                    <td><a href="https://codex.wordpress.org/Function_Reference/add_action" target="_blank">add_action(
                            $hook, $function_to_add, $priority, $accepted_args );</a></td>
                </tr>
                <tr>
                    <td colspan="2">
                        <pre><code><?php 
        echo $action_example;
        ?>
</code></pre>
                    </td>
                </tr>
                <tr>
                    <td><h3 style="margin:0">Add Filter</h3></td>
                    <td><a href="https://codex.wordpress.org/Function_Reference/add_filter" target="_blank">add_filter(
                            $tag, $function_to_add, $priority, $accepted_args );</a></td>
                </tr>
                <tr>
                    <td colspan="2">
                        <pre><code><?php 
        echo $filter_example;
        ?>
</code></pre>
                    </td>
                </tr>
                </tbody>
            </table>

        </div>

        <script>
            function displayShortCodeToggle() {
                if (jQuery('#shortcode').is(':checked')) {
                    jQuery('[id^=sc_info]').show();
                    jQuery('[id^=af_info]').hide();
                } else {
                    jQuery('[id^=sc_info]').hide();
                    jQuery('[id^=af_info]').show();
                }
            }
            displayShortCodeToggle();

            jQuery('#shortcode').click(function () {
                displayShortCodeToggle();
            });
            jQuery('#name').keyup(function () {
                displayShortCodeToggle();
            });
        </script>

        <?php 
    }
 /**
  * Handle the URL request for the WP dashboard admin page.
  * Handle any actions indicated in the URL GET parameters
  */
 function handleAdminPageUrl()
 {
     $this->plugin->securityCheck();
     // set-screen-option callback - does not work
     // this is the work-around
     if (isset($_REQUEST['wp_screen_options']) && is_array($_REQUEST['wp_screen_options'])) {
         AddActionsAndFilters_ViewAdminPage::setScreenOptionCallback($_REQUEST['wp_screen_options']['option'], $_REQUEST['wp_screen_options']['value']);
     }
     require_once 'AddActionsAndFilters_DataModelConfig.php';
     require_once 'AddActionsAndFilters_DataModel.php';
     // Look for Sorting, ordering and searching
     $config = new AddActionsAndFilters_DataModelConfig();
     if (isset($_REQUEST['orderby'])) {
         $config->setOrderby($_REQUEST['orderby']);
     }
     if (isset($_REQUEST['order'])) {
         $config->setAsc($_REQUEST['order'] != 'desc');
     }
     if (isset($_REQUEST['s'])) {
         $config->setSearch($_REQUEST['s']);
     }
     // Init DataModel and Table
     $dataModel = new AddActionsAndFilters_DataModel($this->plugin, $config);
     require_once 'AddActionsAndFilters_CodeListTable.php';
     $table = new AddActionsAndFilters_CodeListTable($dataModel);
     // May be changed if a different page is to be displayed
     $showAdminPage = true;
     // Look for actions to be performed
     $action = $table->current_action();
     if ($action && $action != -1) {
         require_once 'AddActionsAndFilters_AdminPageActions.php';
         $actions = new AddActionsAndFilters_AdminPageActions();
         $ids = null;
         if (isset($_REQUEST['cb']) && is_array($_REQUEST['cb'])) {
             // check nonce which is on the bulk action form only
             if ($table->verifyBulkNonce($_REQUEST['_wpnonce'])) {
                 $ids = $_REQUEST['cb'];
             }
         } else {
             if (isset($_REQUEST['id'])) {
                 $ids = array($_REQUEST['id']);
             } else {
                 if (isset($_REQUEST['ids'])) {
                     $ids = explode(',', $_REQUEST['ids']);
                 }
             }
         }
         // Perform Actions
         if ($action == $actions->getEditKey()) {
             $item = isset($_REQUEST['id']) ? $dataModel->getDataItem($_REQUEST['id']) : array();
             $showAdminPage = false;
             // show edit page instead
             $this->plugin->displayEditPage($item);
         } else {
             if ($ids) {
                 switch ($action) {
                     case $actions->getActivateKey():
                         $dataModel->activate($ids, true);
                         break;
                     case $actions->getDeactivateKey():
                         $dataModel->activate($ids, false);
                         break;
                     case $actions->getDeleteKey():
                         $dataModel->delete($ids);
                         break;
                     case $actions->getExportKey():
                         if (!empty($ids)) {
                             require_once 'AddActionsAndFilters_ViewImportExport.php';
                             $view = new AddActionsAndFilters_ViewImportExport($this->plugin);
                             $view->outputBulkExport($ids);
                         }
                         break;
                     default:
                         break;
                 }
             }
         }
     }
     // Display Admin Page
     if ($showAdminPage) {
         $table->prepare_items();
         $this->displayAdminTable($table);
     }
 }