Plugin Directory

Changeset 1303067


Ignore:
Timestamp:
12/08/2015 03:25:29 PM (10 years ago)
Author:
fabifott
Message:

3.1.04

  • FileBrowser: new option Inline Add to toggle the display of Add File/Category links
  • Async Uploader: Added error message on invalid server response after upload
  • Prevent direct script access for Editor Plugin, Post Browser and AJAX
  • PHP 7 compatibility: mysql_close only called if exists
Location:
wp-filebase
Files:
290 added
6 deleted
36 edited

Legend:

Unmodified
Added
Removed
  • wp-filebase/trunk

    • Property svn:ignore
      •  

        old new  
        11.git
         2nbproject
  • wp-filebase/trunk/classes/AdmInstallExt.php

    r1113324 r1303067  
    22
    33class WPFB_AdmInstallExt {
    4    
    5     static function PluginsApiFilter($res, $action, $args)
    6     {
    7         global $user_ID;
    8         $res = wpfb_call('ExtensionLib','QueryAvailableExtensions');
    9         if($user_ID && !empty($res->info['tag_time']))
    10             update_user_option($user_ID, 'wpfb_ext_tagtime', $res->info['tag_time']);   
    11         return $res;
    12     }
    13    
    14     static function PluginActionLinksFilter($action_links, $plugin) {
    15         $plugin = (object)$plugin;
    16         if(strpos($action_links[0],'button-disabled') === false) {
    17             if(!empty($plugin->dependencies_unmet)) {
    18                 $action_links[0] = '<a class="button" onclick="return confirm(\'This extension requires WP-Filebase Pro. Do you want to learn more about an upgrade?\');" href="' . esc_attr ($plugin->dependencies_url) . '" target="_blank" aria-label="' . esc_attr( sprintf( __( 'Install extension %s' ), $plugin->name ) ) . '">'. __( 'Install' )  . '</a>';
    19             } elseif(!empty($plugin->need_to_buy)) {
    20                 $action_links[0] = '<a class="buy-now button button-primary" href="' . esc_attr ($plugin->buy_url) . '" target="_blank" aria-label="' . esc_attr( sprintf( __( 'Buy extension %s' ), $plugin->name ) ) . '">'. sprintf( __( 'Buy now (%s)' ), $plugin->license_price ) . '</a>';
    21             } elseif(!empty($plugin->license_required)) {
    22                 $action_links[0] = '<a class="buy-now button thickbox" href="' . esc_attr ($plugin->add_url) . '" data-title="' . esc_attr( sprintf( __( 'Add extension %s' ), $plugin->name ) ) . '">'. __( 'Add License' ) . '</a>';
    23             }
    24         }
    25         if(!empty($plugin->need_to_buy))
    26             $action_links[1] = '<a href="' . esc_attr ($plugin->homepage) . '" class="no_thickbox" target="_blank">'.__('More Details').'</a>';
    27        
    28         if(!empty($plugin->requires_pro)) {
    29             $action_links[] = '<span class="wp-ui-notification wpfb-pro" title="This extension requires WP-Filebase Pro">pro</span>';
    30         }
    31         return $action_links;
    32     }
    33    
    34     static function Display()
    35     {
    36         add_filter( 'plugins_api', array(__CLASS__, 'PluginsApiFilter'), 10, 3 );
    37         add_filter( 'plugin_install_action_links', array(__CLASS__, 'PluginActionLinksFilter'), 10, 2 );
    38         add_filter( 'install_plugins_nonmenu_tabs', create_function('$tabs', '$tabs[]="new";return $tabs;'));
    39         self::DisplayInstallPlugins();
    40     }
    41    
    42     static function DisplayInstallPlugins() {
    43 if ( ! current_user_can('install_plugins') )
    44     wp_die(__('You do not have sufficient permissions to install plugins on this site.'));
     4
     5    static function PluginsApiFilter($res, $action, $args) {
     6        global $user_ID;
     7        $res = wpfb_call('ExtensionLib', 'QueryAvailableExtensions');
     8        if (!$res || empty($res->info)) {
     9            wp_die('WP-Filebase extension directory is currently not available.');
     10            return false;
     11        }
     12        if ($user_ID && !empty($res->info['tag_time']))
     13            update_user_option($user_ID, 'wpfb_ext_tagtime', $res->info['tag_time']);
     14        return $res;
     15    }
     16
     17    static function PluginActionLinksFilter($action_links, $plugin) {
     18        $plugin = (object) $plugin;
     19        if (strpos($action_links[0], 'button-disabled') === false) {
     20            if (!empty($plugin->dependencies_unmet)) {
     21                $action_links[0] = '<a class="button" onclick="return confirm(\'This extension requires WP-Filebase Pro. Do you want to learn more about an upgrade?\');" href="' . esc_attr($plugin->dependencies_url) . '" target="_blank" aria-label="' . esc_attr(sprintf(__('Install extension %s'), $plugin->name)) . '">' . __('Install') . '</a>';
     22            } elseif (!empty($plugin->need_to_buy)) {
     23                $action_links[0] = '<a class="buy-now button button-primary" href="' . esc_attr($plugin->buy_url) . '" target="_blank" aria-label="' . esc_attr(sprintf(__('Buy extension %s'), $plugin->name)) . '">' . sprintf(__('Buy now (%s)'), $plugin->license_price) . '</a>';
     24            } elseif (!empty($plugin->license_required)) {
     25                $action_links[0] = '<a class="buy-now button thickbox" href="' . esc_attr($plugin->add_url) . '" data-title="' . esc_attr(sprintf(__('Add extension %s'), $plugin->name)) . '">' . __('Add License') . '</a>';
     26            }
     27        }
     28        if (!empty($plugin->need_to_buy))
     29            $action_links[1] = '<a href="' . esc_attr($plugin->homepage) . '" class="no_thickbox" target="_blank">' . __('More Details') . '</a>';
     30
     31        if (!empty($plugin->requires_pro)) {
     32            $action_links[] = '<span class="wp-ui-notification wpfb-pro" title="This extension requires WP-Filebase Pro">pro</span>';
     33        }
     34        return $action_links;
     35    }
     36
     37    static function Display() {
     38        add_filter('plugins_api', array(__CLASS__, 'PluginsApiFilter'), 10, 3);
     39        add_filter('plugin_install_action_links', array(__CLASS__, 'PluginActionLinksFilter'), 10, 2);
     40        add_filter('install_plugins_nonmenu_tabs', create_function('$tabs', '$tabs[]="new";return $tabs;'));
     41        self::DisplayInstallPlugins();
     42    }
     43
     44    static function DisplayInstallPlugins() {
     45        if (!current_user_can('install_plugins'))
     46            wp_die(__('You do not have sufficient permissions to install plugins on this site.'));
    4547
    4648
    4749
    48 global $tab;
    49 $tab = $_GET['tab'] = 'new'; // required for list table (in 3.5.1)
     50        global $tab;
     51        $tab = $_GET['tab'] = 'new'; // required for list table (in 3.5.1)
    5052
    51 $wp_list_table = _get_list_table('WP_Plugin_Install_List_Table');
    52 $pagenum = $wp_list_table->get_pagenum();
    53 $wp_list_table->orderby = 'order';
    54 $wp_list_table->prepare_items();
    55 $total_pages = $wp_list_table->get_pagination_arg( 'total_pages' );
     53        $wp_list_table = _get_list_table('WP_Plugin_Install_List_Table');
     54        $pagenum = $wp_list_table->get_pagenum();
     55        $wp_list_table->orderby = 'order';
     56        $wp_list_table->prepare_items();
     57        $total_pages = $wp_list_table->get_pagination_arg('total_pages');
    5658
    57 if ( $pagenum > $total_pages && $total_pages > 0 ) {
    58     WPFB_AdminLite::JsRedirect( add_query_arg( 'paged', $total_pages ) );
    59     exit;
    60 }
     59        if ($pagenum > $total_pages && $total_pages > 0) {
     60            WPFB_AdminLite::JsRedirect(add_query_arg('paged', $total_pages));
     61            exit;
     62        }
    6163
    62 $title = __( 'Add Extensions' );
     64        $title = __('Add Extensions');
    6365
    64 wp_print_scripts( 'plugin-install' );
     66        wp_print_scripts('plugin-install');
     67        ?>
     68        <style type="text/css" media="screen">
     69            .vers.column-rating, .column-downloaded { display: none; }
     70            #TB_ajaxWindowTitle { display: none; }
     71        </style>
    6572
    66 ?>
    67 <style type="text/css" media="screen">
    68     .vers.column-rating, .column-downloaded { display: none; }
    69     #TB_ajaxWindowTitle { display: none; }
    70 </style>
     73        <div class="wrap">
     74            <h2><?php echo esc_html($title); ?></h2>
    7175
    72 <div class="wrap">
    73 <h2><?php   echo esc_html( $title );    ?></h2>
    74 
    75 <?php
     76        <?php
    7677//$wp_list_table->views();
    7778//echo '<br class="clear" />';
    78 ?>
    79     <form id="plugin-filter" action="" method="post">
    80         <?php $wp_list_table->display(); ?>
    81     </form>
    82 </div>
    83 <script>
    84     jQuery('a.buy-now').click(function(e) {
    85         if(jQuery(this).text() === 'Refresh') {
    86             window.location.reload();
    87             return false;
    88         }
    89         jQuery(this).text('Refresh');
    90         return true;
    91     });
    92     </script>
    93 <?php
    94     }
     79        ?>
     80            <form id="plugin-filter" action="" method="post">
     81            <?php $wp_list_table->display(); ?>
     82            </form>
     83        </div>
     84        <script>
     85            jQuery('a.buy-now').click(function (e) {
     86                if (jQuery(this).text() === 'Refresh') {
     87                    window.location.reload();
     88                    return false;
     89                }
     90                jQuery(this).text('Refresh');
     91                return true;
     92            });
     93        </script>
     94        <?php
     95    }
     96
    9597}
  • wp-filebase/trunk/classes/Admin.php

    r1254671 r1303067  
    655655        jQuery.ajax({
    656656            url: wpfbConf.ajurl,
    657             data: {action:"catinfo","id":catId},
    658             dataType: "json",
     657            data: {wpfb_action:"catinfo",id:catId},
    659658            success: (function(data){jQuery('#<?php echo $name ?>_inherited_permissions_label').html(data.roles_str);})
    660659        });
  • wp-filebase/trunk/classes/AdminBar.php

    r1254671 r1303067  
    1313    if ( !empty($current_object) && !empty($current_object->post_type) && $current_object->ID > 0) {
    1414        $is_filebrowser = ($current_object->ID == WPFB_Core::$settings->file_browser_post_id);
    15         $link = esc_attr(WPFB_Core::PluginUrl('editor_plugin.php?manage_attachments=1&post_id='.$current_object->ID));
     15        $link = esc_attr(admin_url('?wpfilebase-screen=editor-plugin&manage_attachments=1&post_id='.$current_object->ID));
    1616        $wp_admin_bar->add_menu( array( 'parent' => WPFB, 'id' => WPFB.'-attachments', 'title' => __('Manage attachments','wp-filebase'), 'href' => $link,
    1717        'meta' => array('onclick' => 'window.open("'.$link.'", "wpfb-manage-attachments", "width=680,height=400,menubar=no,location=no,resizable=no,status=no,toolbar=no,scrollbars=yes");return false;')));
     
    2525    if($is_filebrowser) {
    2626        $wp_admin_bar->add_menu(array('parent' => WPFB, 'id' => WPFB.'-toggle-drag-drop', 'title' => get_user_option('wpfb_set_fbdd') ? __('Disable file browser Drag &amp; Drop','wp-filebase') : __('Enable file browser Drag &amp; Drop','wp-filebase'), 'href' => 'javascript:;',
    27         'meta' => array('onclick' => 'jQuery.ajax({url:wpfbConf.ajurl,type:"POST",data:{action:"set-user-setting",name:"fbdd",value:'.(get_user_option('wpfb_set_fbdd')?0:1).'},async:false});location.reload();return false;')));
     27        'meta' => array('onclick' => 'jQuery.ajax({url:wpfbConf.ajurl,type:"POST",data:{wpfb_action:"set-user-setting",name:"fbdd",value:'.(get_user_option('wpfb_set_fbdd')?0:1).'},async:false});location.reload();return false;')));
    2828    }
    2929   
  • wp-filebase/trunk/classes/AdminGuiFileBrowser.php

    r1254671 r1303067  
    5555        e.stopPropagation();
    5656        var t = jQuery(e.currentTarget).parents('li').first();     
    57         var d = {action: 'delete'};
     57        var d = {wpfb_action: 'delete'};
    5858        var tid = t.attr('id').split('-');
    5959        d[tid[tid.length-2]+'_id'] = +tid[tid.length-1];
  • wp-filebase/trunk/classes/AdminGuiFiles.php

    r1254671 r1303067  
    9898            if(!empty($_POST['deleteit'])) {
    9999                foreach ( (array)$_POST['delete'] as $file_id ) {                   
    100                     if(is_object($file = WPFB_File::GetFile($file_id))  && $file->CurUserCanEdit())
     100                    if(is_object($file = WPFB_File::GetFile($file_id)) && $file->CurUserCanDelete())
    101101                        $file->Remove(true);
    102102                }
  • wp-filebase/trunk/classes/AdminGuiManage.php

    r1254671 r1303067  
    99        wpfb_loadclass('ExtensionLib');
    1010        $res = WPFB_ExtensionLib::QueryAvailableExtensions();
    11         if(!$res) return false;
     11        if(!$res || empty($res->info)) return false;
    1212        $tag_time = $res->info['tag_time'];
    13         set_transient('wpfb_ext_tagtime', $tag_time, 3600);
     13        set_transient('wpfb_ext_tagtime', $tag_time, 0  + 6 * HOUR_IN_SECONDS);
    1414    }
    1515   
     
    338338                foreach($ids as $id) {
    339339                    $id = intval($id);                 
    340                     if(($file=WPFB_File::GetFile($id))!=null && $file->CurUserCanEdit()) {
     340                    if(($file=WPFB_File::GetFile($id))!=null && $file->CurUserCanDelete()) {
    341341                        $file->Remove(true);
    342342                        $nd++;
  • wp-filebase/trunk/classes/AdminGuiSettings.php

    r1254671 r1303067  
    11<?php
     2
    23class WPFB_AdminGuiSettings {
    3 static function Display()
    4 {
    5     global $wpdb;
    6 
    7     wpfb_loadclass('Admin', 'Output');
    8     WPFB_Core::PrintJS(); // prints wpfbConf.ajurl
    9    
    10     wp_register_script('jquery-imagepicker', WPFB_PLUGIN_URI.'extras/jquery/image-picker/image-picker.min.js', array('jquery'), WPFB_VERSION);
    11     wp_register_style('jquery-imagepicker', WPFB_PLUGIN_URI.'extras/jquery/image-picker/image-picker.css', array(), WPFB_VERSION);
    12 
    13     if(!current_user_can('manage_options')) {
    14         wp_die(__('Cheatin&#8217; uh?').'<!-- manage_options -->');
    15     }
    16    
    17     // nonce and referer check (security)
    18     if((!empty($_POST['reset']) || !empty($_POST['submit'])) && !check_admin_referer('wpfb-update-settings','wpfb-nonce'))
    19         wp_die(__('Cheatin&#8217; uh?'));
    20    
    21     $post = stripslashes_deep($_POST);
    22    
    23     $action = ( !empty($post['action']) ? $post['action'] : ( !empty($_GET['action']) ? $_GET['action'] : '' ) );
    24     $messages = array();
    25     $errors = array();
    26    
    27     $options = get_option(WPFB_OPT_NAME);
    28     $option_fields = WPFB_Admin::SettingsSchema();
    29    
    30     if(isset($post['reset']))
    31     {   
    32         // keep templates
    33         $file_tpl = WPFB_Core::$settings->template_file;
    34         $cat_tpl = WPFB_Core::$settings->template_cat;
    35         wpfb_loadclass('Setup');
    36         WPFB_Setup::ResetOptions();
    37        
    38         WPFB_Core::UpdateOption('template_file', $file_tpl);
    39         WPFB_Core::UpdateOption('template_cat', $cat_tpl);     
    40        
    41         $new_options = get_option(WPFB_OPT_NAME);
    42         $messages = array_merge($messages, WPFB_Admin::SettingsUpdated($options, $new_options));
    43         unset($new_options);
    44         $messages[] = __('Settings reseted.','wp-filebase');       
    45         $options = get_option(WPFB_OPT_NAME);
    46     }
    47     elseif(isset($post['submit']))
    48     {       
    49         // cleanup
    50         foreach($option_fields as $opt_tag => $opt_data)
    51         {
    52             if(isset($post[$opt_tag]))
    53             {
    54                 if(!is_array($post[$opt_tag]))     
    55                     $post[$opt_tag] = trim($post[$opt_tag]);
    56                
    57                 switch($opt_data['type'])
    58                 {
    59                     case 'number':
    60                         $post[$opt_tag] = intval($post[$opt_tag]);
    61                         break;
    62                     case 'select':
    63                         // check if value is in options array, if not set to default
    64                         if(!in_array($post[$opt_tag], array_keys($opt_data['options'])))
    65                             $post[$opt_tag] = $opt_data['default'];
    66                         break;
    67                        
    68                     case 'roles':
    69                         $post[$opt_tag] = array_values(array_filter($post[$opt_tag]));
    70                         // the following must not be removed! if the roles array is empty, permissions are assumed to be set for everyone!
    71                         // so make sure that the admin is explicitly set!
    72                         if(!empty($opt_data['not_everyone']) && !in_array('administrator', $post[$opt_tag])) {
    73                             if(!is_array($post[$opt_tag])) $post[$opt_tag] = array();
    74                             array_unshift($post[$opt_tag],'administrator');
    75                         }
    76                         break;
    77                    
    78                     case 'cat':
    79                         $post[$opt_tag] = (empty($post[$opt_tag]) || is_null($cat = WPFB_Category::GetCat($post[$opt_tag]))) ? 0 : intval($post[$opt_tag]);
    80                         break;
    81                 }                       
    82             }
    83         }
    84        
    85         $post['upload_path'] = str_replace(ABSPATH, '', $post['upload_path']);
    86         $options['upload_path'] = str_replace(ABSPATH, '', $options['upload_path']);
    87        
    88         $post['download_base'] = trim($post['download_base'], '/');
    89         if(WPFB_Admin::WPCacheRejectUri($post['download_base'] . '/', $options['download_base'] . '/'))
    90             $messages[] = sprintf(__('/%s/ added to rejected URIs list of WP Super Cache.','wp-filebase'), $post['download_base']);
    91        
    92         $tpl_file = ($post['template_file']);
    93         $tpl_cat = ($post['template_cat']);
    94         if(!empty($tpl_file) && (empty($options['template_file_parsed']) || $tpl_file != $options['template_file']))
    95         {
    96             wpfb_loadclass('TplLib');
    97             $tpl_file = WPFB_TplLib::Parse($tpl_file);
    98             $result = WPFB_TplLib::Check($tpl_file);
    99            
    100             if(!$result['error']) {
    101                 $options['template_file_parsed'] = $tpl_file;
    102                 $messages[] = __('File template successfully parsed.','wp-filebase');
    103             } else {
    104                 $errors[] = sprintf(__('Could not parse template: error (%s) in line %s.','wp-filebase'), $result['msg'], $result['line']);
    105             }
    106         }
    107        
    108         if(!empty($tpl_cat) && (empty($options['template_cat_parsed']) || $tpl_cat != $options['template_cat']))
    109         {
    110             wpfb_loadclass('TplLib');
    111             $tpl_cat = WPFB_TplLib::Parse($tpl_cat);
    112             $result = WPFB_TplLib::Check($tpl_cat);
    113            
    114             if(!$result['error']) {
    115                 $options['template_cat_parsed'] = $tpl_cat;
    116                 $messages[] = __('Category template successfully parsed.','wp-filebase');
    117             } else {
    118                 $errors[] = sprintf(__('Could not parse template: error (%s) in line %s.','wp-filebase'), $result['msg'], $result['line']);
    119             }
    120         }
    121        
    122        
    123         $fb_sub_pages = get_pages(array('child_of' => $options['file_browser_post_id']));
    124         if($options['file_browser_post_id'] > 0 && count($fb_sub_pages))
    125         {
    126             $messages[] = sprintf(__('Warning: The Filebrowser page <b>%s</b> has at least one subpage <b>%s</b>. This will cause unexpected behavior, since all requests to the subpages are redirected to the File Browser Page. Please choose a Page that does not have any subpages for File Browser.','wp-filebase'),
    127                         get_the_title($post['file_browser_post_id']), get_the_title($fb_sub_pages[0]->ID));
    128         }
    129        
    130         // save options
    131         foreach($option_fields as $opt_tag => $opt_data)
    132         {
    133             $val = isset($post[$opt_tag]) ? $post[$opt_tag] : '';
    134             $options[$opt_tag] = ($val);
    135         }
    136        
    137         // make sure a short tag exists, if not append one
    138         $select_opts = array('languages', 'platforms', 'licenses', 'requirements', 'custom_fields');
    139         foreach($select_opts as $opt_tag) {
    140             if(empty($options[$opt_tag])) {
    141                 $options[$opt_tag] = '';
    142                 continue;
    143             }
    144             $lines = explode("\n", $options[$opt_tag]);
    145             $lines2 = array();
    146             for($i = 0; $i < count($lines); $i++) {
    147                 $lines[$i] = str_replace('||','|',trim($lines[$i], "|\r"));
    148                 if(empty($lines[$i]) || $lines[$i] == '|')  continue;
    149                 $pos = strpos($lines[$i], '|');
    150                 if($pos <= 0) $lines[$i] .= '|'. sanitize_key(substr($lines[$i], 0, min(8, strlen($lines[$i]))));
    151                 $lines2[] = $lines[$i];
    152             }
    153             $options[$opt_tag] = implode("\n", $lines2);
    154         }
    155        
    156         $old_options = get_option(WPFB_OPT_NAME);
    157         update_option(WPFB_OPT_NAME, $options);
    158         WPFB_Core::$settings = (object)$options;
    159        
    160         $messages = array_merge($messages, WPFB_Admin::SettingsUpdated($old_options, $options));
    161 
    162         if(count($errors) == 0)
    163             $messages[] = __('Settings updated.','wp-filebase');
    164        
    165         //refresh any description which can contain opt values
    166         $option_fields = WPFB_Admin::SettingsSchema();
    167     }
    168    
    169     if(WPFB_Core::$settings->allow_srv_script_upload)
    170         $messages[] = __('WARNING: Script upload enabled!','wp-filebase');
    171        
    172     $upload_path = WPFB_Core::$settings->upload_path;
    173     if(!empty($old_options) && path_is_absolute($upload_path) && !path_is_absolute($old_options['upload_path']))
    174     {
    175         $rel_path  = str_replace('\\','/',$upload_path);
    176         $rel_path = substr($rel_path, strpos($rel_path, '/')+1);
    177         $messages[] = sprintf(__('NOTICE: The upload path <code>%s</code> is rooted to the filesystem. You should remove the leading slash if you want to use a folder inside your Wordpress directory (i.e: <code>%s</code>)','wp-filebase'), $upload_path, $rel_path);
    178     }
    179    
    180     $action_uri = admin_url('admin.php') . '?page=' . $_GET['page'] . '&amp;updated=true';
    181 
    182     if (!empty($messages)) :
    183     $message = '';
    184     foreach($messages as $msg)
    185         $message .= '<p>' . $msg . '</p>';
    186 ?>
    187 <div id="message" class="updated fade"><?php echo $message; ?></div>
    188 <?php
    189     endif;
    190 
    191     if (!empty($errors)) :
    192     $error = '';
    193     foreach($errors as $err)
    194         $error .= '<p>' . $err . '</p>';
    195 ?>
    196 <div id="message" class="error fade"><?php echo $error; ?></div>
    197 <?php endif; ?>
    198 <script type="text/javascript">
    199 /* Option tabs */
    200 jQuery(document).ready( function() {
    201     try { jQuery('#wpfb-tabs').tabs(); }
    202     catch(ex) {}
    203     /*if(typeof(CKEDITOR) != 'undefined') {
    204         CKEDITOR.plugins.addExternal('wpfilebase', ajaxurl+'/../../wp-content/plugins/wp-filebase/extras/ckeditor/');
    205         alert( ajaxurl+'/../../wp-content/plugins/wp-filebase/extras/ckeditor/');
    206     }*/
    207 });
    208 </script>
    209 
    210 <div class="wrap">
    211 <div id="icon-options-general" class="icon32"><br /></div>
    212 <h2><?php echo WPFB_PLUGIN_NAME; echo ' '; _e("Settings"/*def*/); ?></h2>
    213 
    214 <form method="post" action="<?php echo $action_uri; ?>" name="wpfilebase-options">
    215     <?php wp_nonce_field('wpfb-update-settings', 'wpfb-nonce'); ?>
    216     <p class="submit">
    217     <input type="submit" name="submit" value="<?php _e('Save Changes'/*def*/) ?>" class="button-primary" />
    218     </p>
    219     <?php
    220    
    221     $misc_tags = array('disable_id3','search_id3','thumbnail_path','use_path_tags','no_name_formatting');
    222     if(function_exists('wp_admin_bar_render'))
    223         $misc_tags[] = 'admin_bar';
    224    
    225    
    226     $limits = array('bitrate_unregistered', 'bitrate_registered', 'traffic_day', 'traffic_month', 'traffic_exceeded_msg', 'file_offline_msg', 'daily_user_limits', 'daily_limit_subscriber', 'daily_limit_contributor', 'daily_limit_author', 'daily_limit_editor', 'daily_limit_exceeded_msg');
    227    
    228    
    229    
    230     $option_categories = array(
    231         __('Common','wp-filebase')                  => array('upload_path','search_integration' /*'cat_drop_down'*/),
    232         __('Display','wp-filebase')                 => array('file_date_format','thumbnail_size','auto_attach_files', 'attach_loop','attach_pos', 'filelist_sorting', 'filelist_sorting_dir', 'filelist_num', /* TODO: remove? 'parse_tags_rss',*/ 'decimal_size_format','search_result_tpl','disable_css'),
    233         __('File Browser','wp-filebase')                => array('file_browser_post_id','file_browser_cat_sort_by','file_browser_cat_sort_dir','file_browser_file_sort_by','file_browser_file_sort_dir','file_browser_fbc', 'late_script_loading', 'folder_icon', 'small_icon_size',
    234         'disable_footer_credits','footer_credits_style',
    235                     ),
    236         __('Download','wp-filebase')                => array('hide_links', 'disable_permalinks', 'download_base', 'force_download', 'range_download', 'http_nocache', 'ignore_admin_dls', 'accept_empty_referers','allowed_referers' /*,'dl_destroy_session'*/,'use_fpassthru'),
    237         __('Form Presets','wp-filebase')            => array('default_author','default_roles', 'default_cat', 'default_direct_linking','languages', 'platforms', 'licenses', 'requirements', 'custom_fields'),
    238         __('Limits','wp-filebase')                  => $limits,
    239         __('Security','wp-filebase')                => array('allow_srv_script_upload', 'fext_blacklist', 'frontend_upload', 'hide_inaccessible', 'inaccessible_msg', 'inaccessible_redirect', 'cat_inaccessible_msg', 'login_redirect_src', 'protect_upload_path', 'private_files'),
    240         __('Templates and Scripts','wp-filebase')   => array('template_file', 'template_cat', 'dlclick_js' ),
    241         __('Sync','wp-filebase')                        => array('cron_sync', 'base_auto_thumb', 'remove_missing_files','fake_md5' ),
    242         __('Misc')                          => $misc_tags,
    243     );
    244     ?>
    245     <div id="wpfb-tabs">
    246         <ul class="wpfb-tab-menu">
    247             <?php foreach ( $option_categories as $key => $val ) {
    248                 echo '<li><a href="#'.sanitize_title($key).'">'.esc_html($key).'</a></li>';
    249             } ?>
    250         </ul>
    251     <?php
    252     $page_option_list = '';
    253     $n = 0;
    254     foreach($option_categories as $opt_cat => $opt_cat_fields) {
    255         //echo "\n".'<h3>'.$opt_cat.'</h3>';   
    256         echo "\n\n".'<div id="'. sanitize_title($opt_cat) .'" class="wpfilebase-opttab"><h3>'.$opt_cat.'</h3><table class="form-table">';
    257         foreach($opt_cat_fields as $opt_tag)
    258         {
    259            
    260             $field_data = $option_fields[$opt_tag];
    261             $opt_val = $options[$opt_tag];
    262             echo "\n".'<tr valign="top">'."\n".'<th scope="row">' . $field_data['title']. '</th>'."\n".'<td>';
    263             $style_class = '';
    264             if(!empty($field_data['class']))
    265                 $style_class .= ' class="'.$field_data['class'].'"';
    266             if(!empty($field_data['style']))
    267                 $style_class .= ' style="'.$field_data['style'].'"';
    268             switch($field_data['type'])
    269             {
    270                 case 'text':
    271                 case 'number':
    272                 case 'checkbox':
    273                     echo '<input name="' . $opt_tag . '" type="' . $field_data['type'] . '" id="' . $opt_tag . '"';
    274                     echo ((!empty($field_data['class'])) ? ' class="' . $field_data['class'] . '"' : '');
    275                     if($field_data['type'] == 'checkbox') {
    276                         echo ' value="1" ';
    277                         checked('1', $opt_val);
    278                     } elseif($field_data['type'] == 'number')
    279                         echo ' value="' . intval($opt_val) . '" size="5" style="text-align: right"';
    280                     else {
    281                         echo ' value="' . esc_attr($opt_val) . '"';
    282                         if(isset($field_data['size']))
    283                             echo ' size="' . (int)$field_data['size'] . '"';
    284                     }
    285                     echo $style_class . ' />';
    286                     break;
    287                    
    288                 case 'textarea':
    289                     $code_edit = (strpos($opt_tag, 'template_') !== false || (isset($field_data['class']) && strpos($field_data['class'], 'code') !== false));
    290                     $nowrap = !empty($field_data['nowrap']);
    291                     echo '<textarea name="' . $opt_tag . '" id="' . $opt_tag . '"';
    292                     if($nowrap || $code_edit) {
    293                         echo ' cols="100" wrap="off" style="width: 100%;' . ($code_edit ?  'font-size: 10px;' : '') . '"';
    294                     } else
    295                         echo ' cols="50"';
    296                     echo ' rows="' . ($code_edit ? 20 : 5) . '"';
    297                     echo $style_class;
    298                     echo '>';
    299                     echo esc_html($opt_val);
    300                     echo '</textarea>';
    301                     break;
    302                 case 'select':
    303                     echo '<select name="' . $opt_tag . '" id="' . $opt_tag . '">';
    304                     foreach($field_data['options'] as $opt_v => $opt_n)
    305                         echo '<option value="' . esc_attr($opt_v) . '"' . (($opt_v == $opt_val) ? ' selected="selected" ' : '') . $style_class . '>' . ((!is_numeric($opt_v) && $opt_v !== $opt_n) ? (esc_html($opt_v) . ': ') : '') . esc_html($opt_n) . '</option>';
    306                     echo '</select>';
    307                     break;
    308                    
    309                 case 'roles':
    310                     WPFB_Admin::RolesCheckList($opt_tag, $opt_val, empty($field_data['not_everyone']));
    311                     break;
    312                
    313                                 case 'icon':
    314                     wp_print_scripts('jquery-imagepicker');
    315                     wp_print_styles('jquery-imagepicker');
    316                    
    317                     echo '<select class="image-picker show-html" name="' . $opt_tag . '" id="' . $opt_tag . '">';
    318                     ?>
    319                         <?php
    320                         foreach($field_data['icons'] as $icon)
    321                             echo '<option data-img-src="'.$icon['url'].'" value="'.$icon['path'].'" ' . (($icon['path'] === $opt_val) ? ' selected="selected" ' : '').'>'.basename($icon['path']).'</option>';
    322                         ?>
    323                     </select>
    324                     <script type="text/javascript">
    325                     jQuery(document).ready( function() { jQuery("#<?php echo $opt_tag; ?>").imagepicker(); });
    326                     </script>
    327                     <?php
    328                     break;
    329                                    
    330                    
    331                 case 'cat':
    332                     echo "<select name='$opt_tag' id='$opt_tag'>";
    333                     echo WPFB_Output::CatSelTree(array('selected'=>$opt_val));
    334                     echo "</select>";
    335                     break;
    336             }
    337            
    338             if(!empty($field_data['unit']))
    339                 echo ' ' . $field_data['unit'];
    340                
    341             if(!empty($field_data['desc']))
    342                 echo "\n".'<br />' . str_replace('%value%', is_array($opt_val) ? join(', ', $opt_val) : $opt_val, $field_data['desc']);
    343             echo "\n</td>\n</tr>";     
    344             $page_option_list .= $opt_tag . ',';
    345         }
    346        
    347         echo '</table></div>'."\n";
    348     }
    349     ?>
    350 </div> <!--wpfilebase-opttabs-->
    351     <input type="hidden" name="action" value="update" />
    352     <input type="hidden" name="page_options" value="<?php echo $page_option_list; ?>" />
    353     <p class="submit">
    354     <input type="submit" name="submit" value="<?php _e('Save Changes') ?>" class="button-primary" />
    355     <input type="submit" name="reset" value="<?php _e('Restore Default Settings','wp-filebase') ?>" onclick="return confirm('<?php _e('All settings (except default file and category template) will be set to default values. Continue?','wp-filebase'); ?>')" class="button delete" style="float: right;" />
    356     </p>
    357 </form>
    358 </div>  <!-- wrap -->   
    359 <?php
     4
     5    static function Display() {
     6        global $wpdb;
     7
     8        wpfb_loadclass('Admin', 'Output');
     9        WPFB_Core::PrintJS(); // prints wpfbConf.ajurl
     10
     11        wp_register_script('jquery-imagepicker', WPFB_PLUGIN_URI . 'extras/jquery/image-picker/image-picker.min.js', array('jquery'), WPFB_VERSION);
     12        wp_register_style('jquery-imagepicker', WPFB_PLUGIN_URI . 'extras/jquery/image-picker/image-picker.css', array(), WPFB_VERSION);
     13
     14        if (!current_user_can('manage_options')) {
     15            wp_die(__('Cheatin&#8217; uh?') . '<!-- manage_options -->');
     16        }
     17
     18        // nonce and referer check (security)
     19        if ((!empty($_POST['reset']) || !empty($_POST['submit'])) && !check_admin_referer('wpfb-update-settings', 'wpfb-nonce'))
     20            wp_die(__('Cheatin&#8217; uh?'));
     21
     22        $post = stripslashes_deep($_POST);
     23
     24        $action = (!empty($post['action']) ? $post['action'] : (!empty($_GET['action']) ? $_GET['action'] : '' ) );
     25        $messages = array();
     26        $errors = array();
     27
     28        $options = get_option(WPFB_OPT_NAME);
     29        $option_fields = WPFB_Admin::SettingsSchema();
     30
     31        if (isset($post['reset'])) {
     32            // keep templates
     33            $file_tpl = WPFB_Core::$settings->template_file;
     34            $cat_tpl = WPFB_Core::$settings->template_cat;
     35            wpfb_loadclass('Setup');
     36            WPFB_Setup::ResetOptions();
     37
     38            WPFB_Core::UpdateOption('template_file', $file_tpl);
     39            WPFB_Core::UpdateOption('template_cat', $cat_tpl);
     40
     41            $new_options = get_option(WPFB_OPT_NAME);
     42            $messages = array_merge($messages, WPFB_Admin::SettingsUpdated($options, $new_options));
     43            unset($new_options);
     44            $messages[] = __('Settings reseted.', 'wp-filebase');
     45            $options = get_option(WPFB_OPT_NAME);
     46        } elseif (isset($post['submit'])) {
     47            // cleanup
     48            foreach ($option_fields as $opt_tag => $opt_data) {
     49                if (isset($post[$opt_tag])) {
     50                    if (!is_array($post[$opt_tag]))
     51                        $post[$opt_tag] = trim($post[$opt_tag]);
     52
     53                    switch ($opt_data['type']) {
     54                        case 'number':
     55                            $post[$opt_tag] = intval($post[$opt_tag]);
     56                            break;
     57                        case 'select':
     58                            // check if value is in options array, if not set to default
     59                            if (!in_array($post[$opt_tag], array_keys($opt_data['options'])))
     60                                $post[$opt_tag] = $opt_data['default'];
     61                            break;
     62
     63                        case 'roles':
     64                            $post[$opt_tag] = array_values(array_filter($post[$opt_tag]));
     65                            // the following must not be removed! if the roles array is empty, permissions are assumed to be set for everyone!
     66                            // so make sure that the admin is explicitly set!
     67                            if (!empty($opt_data['not_everyone']) && !in_array('administrator', $post[$opt_tag])) {
     68                                if (!is_array($post[$opt_tag]))
     69                                    $post[$opt_tag] = array();
     70                                array_unshift($post[$opt_tag], 'administrator');
     71                            }
     72                            break;
     73
     74                        case 'cat':
     75                            $post[$opt_tag] = (empty($post[$opt_tag]) || is_null($cat = WPFB_Category::GetCat($post[$opt_tag]))) ? 0 : intval($post[$opt_tag]);
     76                            break;
     77                    }
     78                }
     79            }
     80
     81            $post['upload_path'] = str_replace(ABSPATH, '', $post['upload_path']);
     82            $options['upload_path'] = str_replace(ABSPATH, '', $options['upload_path']);
     83
     84            $post['download_base'] = trim($post['download_base'], '/');
     85            if (WPFB_Admin::WPCacheRejectUri($post['download_base'] . '/', $options['download_base'] . '/'))
     86                $messages[] = sprintf(__('/%s/ added to rejected URIs list of WP Super Cache.', 'wp-filebase'), $post['download_base']);
     87
     88            $tpl_file = ($post['template_file']);
     89            $tpl_cat = ($post['template_cat']);
     90            if (!empty($tpl_file) && (empty($options['template_file_parsed']) || $tpl_file != $options['template_file'])) {
     91                wpfb_loadclass('TplLib');
     92                $tpl_file = WPFB_TplLib::Parse($tpl_file);
     93                $result = WPFB_TplLib::Check($tpl_file);
     94
     95                if (!$result['error']) {
     96                    $options['template_file_parsed'] = $tpl_file;
     97                    $messages[] = __('File template successfully parsed.', 'wp-filebase');
     98                } else {
     99                    $errors[] = sprintf(__('Could not parse template: error (%s) in line %s.', 'wp-filebase'), $result['msg'], $result['line']);
     100                }
     101            }
     102
     103            if (!empty($tpl_cat) && (empty($options['template_cat_parsed']) || $tpl_cat != $options['template_cat'])) {
     104                wpfb_loadclass('TplLib');
     105                $tpl_cat = WPFB_TplLib::Parse($tpl_cat);
     106                $result = WPFB_TplLib::Check($tpl_cat);
     107
     108                if (!$result['error']) {
     109                    $options['template_cat_parsed'] = $tpl_cat;
     110                    $messages[] = __('Category template successfully parsed.', 'wp-filebase');
     111                } else {
     112                    $errors[] = sprintf(__('Could not parse template: error (%s) in line %s.', 'wp-filebase'), $result['msg'], $result['line']);
     113                }
     114            }
     115
     116            $fb_sub_pages = get_pages(array('child_of' => $options['file_browser_post_id']));
     117            if ($options['file_browser_post_id'] > 0 && count($fb_sub_pages)) {
     118                $messages[] = sprintf(__('Warning: The Filebrowser page <b>%s</b> has at least one subpage <b>%s</b>. This will cause unexpected behavior, since all requests to the subpages are redirected to the File Browser Page. Please choose a Page that does not have any subpages for File Browser.', 'wp-filebase'), get_the_title($post['file_browser_post_id']), get_the_title($fb_sub_pages[0]->ID));
     119            }
     120
     121            // save options
     122            foreach ($option_fields as $opt_tag => $opt_data) {
     123                $val = isset($post[$opt_tag]) ? $post[$opt_tag] : '';
     124                $options[$opt_tag] = ($val);
     125            }
     126
     127            // make sure a short tag exists, if not append one
     128            $select_opts = array('languages', 'platforms', 'licenses', 'requirements', 'custom_fields');
     129            foreach ($select_opts as $opt_tag) {
     130                if (empty($options[$opt_tag])) {
     131                    $options[$opt_tag] = '';
     132                    continue;
     133                }
     134                $lines = explode("\n", $options[$opt_tag]);
     135                $lines2 = array();
     136                for ($i = 0; $i < count($lines); $i++) {
     137                    $lines[$i] = str_replace('||', '|', trim($lines[$i], "|\r"));
     138                    if (empty($lines[$i]) || $lines[$i] == '|')
     139                        continue;
     140                    $pos = strpos($lines[$i], '|');
     141                    if ($pos <= 0)
     142                        $lines[$i] .= '|' . sanitize_key(substr($lines[$i], 0, min(8, strlen($lines[$i]))));
     143                    $lines2[] = $lines[$i];
     144                }
     145                $options[$opt_tag] = implode("\n", $lines2);
     146            }
     147
     148            $old_options = get_option(WPFB_OPT_NAME);
     149            update_option(WPFB_OPT_NAME, $options);
     150            WPFB_Core::$settings = (object) $options;
     151
     152            $messages = array_merge($messages, WPFB_Admin::SettingsUpdated($old_options, $options));
     153
     154            if (count($errors) == 0)
     155                $messages[] = __('Settings updated.', 'wp-filebase');
     156
     157            //refresh any description which can contain opt values
     158            $option_fields = WPFB_Admin::SettingsSchema();
     159        }
     160
     161        if (WPFB_Core::$settings->allow_srv_script_upload)
     162            $messages[] = __('WARNING: Script upload enabled!', 'wp-filebase');
     163
     164        $upload_path = WPFB_Core::$settings->upload_path;
     165        if (!empty($old_options) && path_is_absolute($upload_path) && !path_is_absolute($old_options['upload_path'])) {
     166            $rel_path = str_replace('\\', '/', $upload_path);
     167            $rel_path = substr($rel_path, strpos($rel_path, '/') + 1);
     168            $messages[] = sprintf(__('NOTICE: The upload path <code>%s</code> is rooted to the filesystem. You should remove the leading slash if you want to use a folder inside your Wordpress directory (i.e: <code>%s</code>)', 'wp-filebase'), $upload_path, $rel_path);
     169        }
     170
     171        $action_uri = admin_url('admin.php') . '?page=' . $_GET['page'] . '&amp;updated=true';
     172
     173        if (!empty($messages)) :
     174            $message = '';
     175            foreach ($messages as $msg)
     176                $message .= '<p>' . $msg . '</p>';
     177            ?>
     178            <div id="message" class="updated fade"><?php echo $message; ?></div>
     179            <?php
     180        endif;
     181
     182        if (!empty($errors)) :
     183            $error = '';
     184            foreach ($errors as $err)
     185                $error .= '<p>' . $err . '</p>';
     186            ?>
     187            <div id="message" class="error fade"><?php echo $error; ?></div>
     188        <?php endif; ?>
     189        <script type="text/javascript">
     190            /* Option tabs */
     191            jQuery(document).ready(function () {
     192                try {
     193                    jQuery('#wpfb-tabs').tabs();
     194                } catch (ex) {
     195                }
     196                /*if(typeof(CKEDITOR) != 'undefined') {
     197                 CKEDITOR.plugins.addExternal('wpfilebase', ajaxurl+'/../../wp-content/plugins/wp-filebase/extras/ckeditor/');
     198                 alert( ajaxurl+'/../../wp-content/plugins/wp-filebase/extras/ckeditor/');
     199                 }*/
     200            });
     201        </script>
     202
     203        <div class="wrap">
     204            <div id="icon-options-general" class="icon32"><br /></div>
     205            <h2><?php echo WPFB_PLUGIN_NAME;
     206        echo ' ';
     207        _e("Settings"/* def */); ?></h2>
     208
     209            <form method="post" action="<?php echo $action_uri; ?>" name="wpfilebase-options">
     210        <?php wp_nonce_field('wpfb-update-settings', 'wpfb-nonce'); ?>
     211                <p class="submit">
     212                    <input type="submit" name="submit" value="<?php _e('Save Changes'/* def */) ?>" class="button-primary" />
     213                </p>
     214        <?php
     215        $misc_tags = array('disable_id3', 'search_id3', 'thumbnail_path', 'use_path_tags', 'no_name_formatting');
     216        if (function_exists('wp_admin_bar_render'))
     217            $misc_tags[] = 'admin_bar';
     218
     219        $limits = array('bitrate_unregistered', 'bitrate_registered', 'traffic_day', 'traffic_month', 'traffic_exceeded_msg', 'file_offline_msg', 'daily_user_limits', 'daily_limit_subscriber', 'daily_limit_contributor', 'daily_limit_author', 'daily_limit_editor', 'daily_limit_exceeded_msg');
     220
     221
     222        $option_categories = array(
     223            __('Common', 'wp-filebase') => array('upload_path', 'search_integration' /* 'cat_drop_down' */),
     224            __('Display', 'wp-filebase') => array('file_date_format', 'thumbnail_size', 'auto_attach_files', 'attach_loop', 'attach_pos', 'filelist_sorting', 'filelist_sorting_dir', 'filelist_num', /* TODO: remove? 'parse_tags_rss', */ 'decimal_size_format', 'search_result_tpl', 'disable_css'),
     225            __('File Browser', 'wp-filebase') => array('file_browser_post_id', 'file_browser_cat_sort_by', 'file_browser_cat_sort_dir', 'file_browser_file_sort_by', 'file_browser_file_sort_dir', 'file_browser_fbc', 'late_script_loading',  'folder_icon',  'small_icon_size',
     226                'disable_footer_credits', 'footer_credits_style',
     227                                'file_browser_inline_add',
     228            ),
     229            __('Download', 'wp-filebase') => array( 'hide_links', 'disable_permalinks', 'download_base', 'force_download', 'range_download', 'http_nocache', 'ignore_admin_dls', 'accept_empty_referers', 'allowed_referers' /* ,'dl_destroy_session' */, 'use_fpassthru'),
     230            __('Form Presets', 'wp-filebase') => array('default_author', 'default_roles', 'default_cat', 'default_direct_linking', 'languages', 'platforms', 'licenses', 'requirements', 'custom_fields'),
     231            __('Limits', 'wp-filebase') => $limits,
     232            __('Security', 'wp-filebase') => array('allow_srv_script_upload', 'fext_blacklist', 'frontend_upload', 'hide_inaccessible', 'inaccessible_msg', 'inaccessible_redirect', 'cat_inaccessible_msg', 'login_redirect_src', 'protect_upload_path', 'private_files'),
     233            __('Templates and Scripts', 'wp-filebase') => array('template_file', 'template_cat', 'dlclick_js' ),
     234            __('Sync', 'wp-filebase') => array('cron_sync', 'base_auto_thumb', 'remove_missing_files', 'fake_md5' ),
     235            __('Misc') => $misc_tags,
     236        );
     237        ?>
     238                <div id="wpfb-tabs">
     239                    <ul class="wpfb-tab-menu">
     240                <?php
     241                foreach ($option_categories as $key => $val) {
     242                    echo '<li><a href="#' . sanitize_title($key) . '">' . esc_html($key) . '</a></li>';
     243                }
     244                ?>
     245                    </ul>
     246                        <?php
     247                        $page_option_list = '';
     248                        $n = 0;
     249                        foreach ($option_categories as $opt_cat => $opt_cat_fields) {
     250                            //echo "\n".'<h3>'.$opt_cat.'</h3>';   
     251                            echo "\n\n" . '<div id="' . sanitize_title($opt_cat) . '" class="wpfilebase-opttab"><h3>' . $opt_cat . '</h3><table class="form-table">';
     252                            foreach ($opt_cat_fields as $opt_tag) {
     253
     254                                $field_data = $option_fields[$opt_tag];
     255                                $opt_val = $options[$opt_tag];
     256                                echo "\n" . '<tr valign="top">' . "\n" . '<th scope="row">' . $field_data['title'] . '</th>' . "\n" . '<td>';
     257                                $style_class = '';
     258                                if (!empty($field_data['class']))
     259                                    $style_class .= ' class="' . $field_data['class'] . '"';
     260                                if (!empty($field_data['style']))
     261                                    $style_class .= ' style="' . $field_data['style'] . '"';
     262                                switch ($field_data['type']) {
     263                                    case 'text':
     264                                    case 'number':
     265                                    case 'checkbox':
     266                                        echo '<input name="' . $opt_tag . '" type="' . $field_data['type'] . '" id="' . $opt_tag . '"';
     267                                        echo ((!empty($field_data['class'])) ? ' class="' . $field_data['class'] . '"' : '');
     268                                        if ($field_data['type'] == 'checkbox') {
     269                                            echo ' value="1" ';
     270                                            checked('1', $opt_val);
     271                                        } elseif ($field_data['type'] == 'number')
     272                                            echo ' value="' . intval($opt_val) . '" size="5" style="text-align: right"';
     273                                        else {
     274                                            echo ' value="' . esc_attr($opt_val) . '"';
     275                                            if (isset($field_data['size']))
     276                                                echo ' size="' . (int) $field_data['size'] . '"';
     277                                        }
     278                                        echo $style_class . ' />';
     279                                        break;
     280
     281                                    case 'textarea':
     282                                        $code_edit = (strpos($opt_tag, 'template_') !== false || (isset($field_data['class']) && strpos($field_data['class'], 'code') !== false));
     283                                        $nowrap = !empty($field_data['nowrap']);
     284                                        echo '<textarea name="' . $opt_tag . '" id="' . $opt_tag . '"';
     285                                        if ($nowrap || $code_edit) {
     286                                            echo ' cols="100" wrap="off" style="width: 100%;' . ($code_edit ? 'font-size: 10px;' : '') . '"';
     287                                        } else
     288                                            echo ' cols="50"';
     289                                        echo ' rows="' . ($code_edit ? 20 : 5) . '"';
     290                                        echo $style_class;
     291                                        echo '>';
     292                                        echo esc_html($opt_val);
     293                                        echo '</textarea>';
     294                                        break;
     295                                    case 'select':
     296                                        echo '<select name="' . $opt_tag . '" id="' . $opt_tag . '">';
     297                                        foreach ($field_data['options'] as $opt_v => $opt_n)
     298                                            echo '<option value="' . esc_attr($opt_v) . '"' . (($opt_v == $opt_val) ? ' selected="selected" ' : '') . $style_class . '>' . ((!is_numeric($opt_v) && $opt_v !== $opt_n) ? (esc_html($opt_v) . ': ') : '') . esc_html($opt_n) . '</option>';
     299                                        echo '</select>';
     300                                        break;
     301
     302                                    case 'roles':
     303                                        WPFB_Admin::RolesCheckList($opt_tag, $opt_val, empty($field_data['not_everyone']));
     304                                        break;
     305
     306                                                                        case 'icon':
     307                                        wp_print_scripts('jquery-imagepicker');
     308                                        wp_print_styles('jquery-imagepicker');
     309
     310                                        echo '<select class="image-picker show-html" name="' . $opt_tag . '" id="' . $opt_tag . '">';
     311                                        ?>
     312                                    <?php
     313                                    foreach ($field_data['icons'] as $icon)
     314                                        echo '<option data-img-src="' . $icon['url'] . '" value="' . $icon['path'] . '" ' . (($icon['path'] === $opt_val) ? ' selected="selected" ' : '') . '>' . basename($icon['path']) . '</option>';
     315                                    ?>
     316                                    </select>
     317                                    <script type="text/javascript">
     318                                        jQuery(document).ready(function () {
     319                                            jQuery("#<?php echo $opt_tag; ?>").imagepicker();
     320                                        });
     321                                    </script>
     322                        <?php
     323                        break;
     324                   
     325                    case 'cat':
     326                        echo "<select name='$opt_tag' id='$opt_tag'>";
     327                        echo WPFB_Output::CatSelTree(array('selected' => $opt_val));
     328                        echo "</select>";
     329                        break;
     330                }
     331
     332                if (!empty($field_data['unit']))
     333                    echo ' ' . $field_data['unit'];
     334
     335                if (!empty($field_data['desc']))
     336                    echo "\n" . '<br />' . str_replace('%value%', is_array($opt_val) ? join(', ', $opt_val) : $opt_val, $field_data['desc']);
     337                echo "\n</td>\n</tr>";
     338                $page_option_list .= $opt_tag . ',';
     339            }
     340
     341            echo '</table></div>' . "\n";
     342        }
     343        ?>
     344                </div> <!--wpfilebase-opttabs-->
     345                <input type="hidden" name="action" value="update" />
     346                <input type="hidden" name="page_options" value="<?php echo $page_option_list; ?>" />
     347                <p class="submit">
     348                    <input type="submit" name="submit" value="<?php _e('Save Changes') ?>" class="button-primary" />
     349                    <input type="submit" name="reset" value="<?php _e('Restore Default Settings', 'wp-filebase') ?>" onclick="return confirm('<?php _e('All settings (except default file and category template) will be set to default values. Continue?', 'wp-filebase'); ?>')" class="button delete" style="float: right;" />
     350                </p>
     351            </form>
     352        </div>  <!-- wrap -->   
     353        <?php
     354    }
     355
    360356}
    361 }
  • wp-filebase/trunk/classes/AdminGuiTpls.php

    r1254671 r1303067  
    144144        url: '<?php echo WPFB_Core::$ajax_url ?>',
    145145        data: {
    146             action: "tpl-sample",
     146            wpfb_action: "tpl-sample",
    147147            tpl: tplc,
    148148            type: ty
     
    279279                <div id="tpl-preview_<?php echo $tpl_tag ?>">
    280280                    <?php if(!empty($_GET['iframe-preview'])) { ?>                 
    281                     <iframe src="<?php echo WPFB_Core::PluginUrl("tpl-preview.php?type=$type&tag=$tpl_tag"); ?>" style="width:100%;height:220px;"></iframe>
     281                    <iframe src="<?php echo admin_url("?wpfilebase-screen=tpl-preview&type=$type&tag=$tpl_tag"); ?>" style="width:100%;height:220px;"></iframe>
    282282                    <?php } else {
    283283                        $table_found = !$list && (strpos($tpl_src, '<table') !== false);
  • wp-filebase/trunk/classes/AdminLite.php

    r1298742 r1303067  
    103103        }
    104104    }
     105       
     106        if(isset($_GET['wpfilebase-screen'])) {
     107            $screen = $_GET['wpfilebase-screen'];
     108            if($screen == 'editor-plugin') {
     109                require_once(WPFB_PLUGIN_ROOT.'screens/editor-plugin.php');               
     110            }
     111           
     112            if($screen == 'tpl-preview') {
     113                require_once(WPFB_PLUGIN_ROOT.'screens/tpl-preview.php');
     114            }
     115           
     116            exit;
     117        }
    105118}
    106119
  • wp-filebase/trunk/classes/AdvUploader.php

    r1254671 r1303067  
    6363     /* delete already uploaded temp file */
    6464    if(jQuery('#file_flash_upload').val() != '0') {
    65         jQuery.ajax({type: 'POST', async: true, url:"<?php echo esc_attr( WPFB_Core::PluginUrl('wpfb-async-upload.php') ); ?>",
    66         data: {<?php echo $this->GetAjaxAuthData(true) ?> , "delupload": jQuery('#file_flash_upload').val()},
     65        jQuery.ajax({type: 'POST', async: true, url:"<?php echo esc_attr( WPFB_Core::$ajax_url_public ); ?>",
     66        data: {<?php echo $this->GetAjaxAuthData(true) ?> , "wpfb_action": "upload", "delupload": jQuery('#file_flash_upload').val()},
    6767        success: (function(data){})
    6868        });
  • wp-filebase/trunk/classes/BatchUploader.php

    r1254671 r1303067  
    171171{
    172172    var item = jQuery('#'+file.dom_id);
     173       
     174        if(!serverData || serverData == -1 || 'object' != typeof(serverData)) {
     175            jQuery('.error', item).show().html('Server response error! '+serverData);
     176            console.log(serverData);
     177            return;
     178        }
     179       
    173180    var url = serverData.file_cur_user_can_edit ? serverData.file_edit_url : serverData.file_download_url;
    174181    jQuery('.filename', item).html('<a href="'+url+'" target="_blank">'+serverData.file_display_name+'</a> <span class="ok"><?php _e('Upload OK!','wp-filebase') ?></span>');
  • wp-filebase/trunk/classes/Core.php

    r1254671 r1303067  
    22
    33class WPFB_Core {
    4    
    5 static $load_js = false;
    6 static $file_browser_search = false;
    7 static $file_browser_item = null;
    8 static $post_url_cache = array();
    9 static $ajax_url = '';
    10 
    11 
    12 /**
    13  * WP-Filebase Settings Object
    14  *
    15  * @since 3.0.14
    16  * @access public
    17  * @var WPFB_Options
    18  */
    19 static $settings;
    20 
    21 static function PluginUrl($url) {
    22     return is_multisite() ? add_query_arg('blog_id', get_current_blog_id(), WPFB_PLUGIN_URI.$url) : (WPFB_PLUGIN_URI.$url);
     4
     5    static $load_js = false;
     6    static $file_browser_search = false;
     7    static $file_browser_item = null;
     8    static $post_url_cache = array();
     9    static $ajax_url = '';
     10    static $ajax_url_public = '';
     11
     12    /**
     13     * WP-Filebase Settings Object
     14     *
     15     * @since 3.0.14
     16     * @access public
     17     * @var WPFB_Options
     18     */
     19    static $settings;
     20
     21    static function PluginUrl($url) {
     22        return is_multisite() ? add_query_arg('blog_id', get_current_blog_id(), WPFB_PLUGIN_URI . $url) : (WPFB_PLUGIN_URI . $url);
     23    }
     24
     25    static function InitClass() {
     26        self::$ajax_url = admin_url('admin-ajax.php?action=wpfilebase');
     27        self::$ajax_url_public = home_url('/?wpfilebase_ajax=1');
     28        if (defined('WPFB_NO_CORE_INIT'))
     29            return; // on activation
     30
     31        self::$settings = (object) get_option(WPFB_OPT_NAME);
     32
     33        // load lang
     34        $lang_dir = defined('WPFB_LANG_DIR') ? ('../../' . WPFB_LANG_DIR) : basename(WPFB_PLUGIN_ROOT) . '/languages';
     35        load_plugin_textdomain('wp-filebase', false, $lang_dir);
     36
     37        add_action('parse_query', array(__CLASS__, 'ParseQuery')); // search
     38        add_action('wp_enqueue_scripts', array(__CLASS__, 'EnqueueScripts'));
     39        add_action('wp_footer', array(__CLASS__, 'Footer'));
     40        add_action('generate_rewrite_rules', array(__CLASS__, 'GenRewriteRules'));
     41        add_action(WPFB . '_cron', array(__CLASS__, 'Cron'));
     42        add_action('wpfilebase_sync', array(__CLASS__, 'Sync')); // for Developers: New wp-filebase actions
     43
     44        add_action('wp_ajax_nopriv_wpfilebase', array(__CLASS__, 'AjaxPublic'));
     45        add_action('wp_ajax_wpfilebase', array(__CLASS__, 'AjaxAdmin'));
     46
     47        add_shortcode('wpfilebase', array(__CLASS__, 'ShortCode'));
     48
     49        // for attachments and file browser
     50        add_filter('the_content', array(__CLASS__, 'ContentFilter'), 10); // must be lower than 11 (before do_shortcode) and after wpautop (>9)
     51        add_filter('ext2type', array(__CLASS__, 'Ext2TypeFilter'));
     52
     53        add_filter('pre_set_site_transient_update_plugins', array(__CLASS__, 'PreSetPluginsTransientFilter'));
     54        add_filter('plugins_api', array(__CLASS__, 'PluginsApiFilter'), 10, 3);
     55
     56        // register treeview stuff
     57        wp_register_script('jquery-treeview', WPFB_PLUGIN_URI . 'extras/jquery/treeview/jquery.treeview.js', array('jquery'), WPFB_VERSION);
     58        wp_register_script('jquery-treeview-edit', WPFB_PLUGIN_URI . 'extras/jquery/treeview/jquery.treeview.edit.js', array('jquery-treeview'), WPFB_VERSION);
     59        wp_register_script('jquery-treeview-async', WPFB_PLUGIN_URI . 'extras/jquery/treeview/jquery.treeview.async.js', array('jquery-treeview-edit'), WPFB_VERSION);
     60        wp_register_style('jquery-treeview', WPFB_PLUGIN_URI . 'extras/jquery/treeview/jquery.treeview.css', array(), WPFB_VERSION);
     61
     62        // DataTables
     63        wp_register_script('jquery-dataTables', WPFB_PLUGIN_URI . 'extras/jquery/dataTables/js/jquery.dataTables.min.js', array('jquery'), WPFB_VERSION);
     64        wp_register_style('jquery-dataTables', WPFB_PLUGIN_URI . 'extras/jquery/dataTables/css/jquery.dataTables.css', array(), WPFB_VERSION);
     65        wp_register_script('jquery-dataTables-columnFilter', WPFB_PLUGIN_URI . 'extras/jquery/dataTables/js/jquery.dataTables.columnFilter.js', array('jquery-dataTables'), WPFB_VERSION);
     66
     67        wp_register_script(WPFB, WPFB_PLUGIN_URI . 'js/common.js', array('jquery'), WPFB_VERSION); // cond loading (see Footer)
     68
     69        if (empty(WPFB_Core::$settings->disable_css)) {
     70            $wpfb_css = get_option('wpfb_css');
     71            if ($wpfb_css) { // static file?
     72                wp_enqueue_style(WPFB, strstr($wpfb_css, '//'), array(), WPFB_VERSION, 'all');
     73            } else {
     74                $upload_path = path_is_absolute(WPFB_Core::$settings->upload_path) ? '' : WPFB_Core::$settings->upload_path;
     75                wp_enqueue_style(WPFB, WPFB_Core::PluginUrl("wp-filebase_css.php?rp=$upload_path"), array(), WPFB_VERSION, 'all');
     76            }
     77        }
     78
     79        $wpfb_admin_page = (is_admin() && !empty($_GET['page']) && strpos($_GET['page'], 'wpfilebase_') !== false) || defined('WPFB_EDITOR_PLUGIN');
     80        if ($wpfb_admin_page)
     81            wpfb_loadclass('Admin');
     82
     83        // live admin
     84        if (($wpfb_admin_page && @$_GET['page'] == 'wpfilebase_filebrowser') || ((WPFB_Core::CurUserCanCreateCat() || WPFB_Core::CurUserCanUpload()) && !is_admin())) {
     85            wp_enqueue_script(WPFB . '-live-admin', WPFB_PLUGIN_URI . 'js/live-admin.js', array('jquery'), WPFB_VERSION);
     86            if (self::GetOpt('admin_bar'))
     87                add_action('admin_bar_menu', array(__CLASS__, 'AdminBar'), 80);
     88            if (self::GetOpt('file_context_menu')) {
     89                wp_enqueue_script('jquery-contextmenu', WPFB_PLUGIN_URI . 'extras/jquery/contextmenu/jquery.contextmenu.js', array('jquery'));
     90                wp_enqueue_style('jquery-contextmenu', WPFB_PLUGIN_URI . 'extras/jquery/contextmenu/jquery.contextmenu.css', array(), WPFB_VERSION);
     91            }
     92            wp_enqueue_style('wpfb-live-admin', WPFB_PLUGIN_URI . 'css/live-admin.css', array(), WPFB_VERSION);
     93        }
     94
     95        // for admin
     96        if (current_user_can('edit_posts') || current_user_can('edit_pages'))
     97            self::MceAddBtns();
     98
     99        self::DownloadRedirect();
     100
     101        if ((WPFB_Core::$settings->frontend_upload || current_user_can('upload_files')) && (!empty($_GET['wpfb_upload_file']) || !empty($_GET['wpfb_add_cat'])))
     102            wpfb_call('Admin', empty($_GET['wpfb_upload_file']) ? 'ProcessWidgetAddCat' : 'ProcessWidgetUpload');
     103       
     104        if(isset($_GET['wpfilebase_ajax'])) {
     105            define( 'DOING_AJAX', true );
     106            wpfb_loadclass('Ajax');
     107            WPFB_Ajax::PublicRequest();
     108        }
     109    }
     110
     111    static function AjaxPublic() {
     112        wpfb_loadclass('Ajax');
     113        WPFB_Ajax::PublicRequest();
     114    }
     115
     116    static function AjaxAdmin() {
     117        wpfb_loadclass('Ajax');
     118        WPFB_Ajax::AdminRequest();
     119    }
     120
     121    static function InitDirectScriptAccess() {
     122        if (is_multisite() && !empty($_REQUEST['blog_id']) && get_current_blog_id() != $_REQUEST['blog_id']) {
     123            $blog_id = (int) $_REQUEST['blog_id'];
     124            if (!get_blog_details($blog_id, false))
     125                die('Blog does not exists!');
     126            switch_to_blog($blog_id);
     127        }
     128    }
     129
     130    static function GetOpt($name = null) {
     131        return empty($name) ? (array) WPFB_Core::$settings : (isset(WPFB_Core::$settings->$name) ? WPFB_Core::$settings->$name : null);
     132    }
     133
     134    static function AdminInit() {
     135        wpfb_loadclass('AdminLite');
     136        if (!empty($_GET['page']) && strpos($_GET['page'], 'wpfilebase_') !== false)
     137            wpfb_loadclass('Admin');
     138        WPFB_AdminLite::Init();
     139    }
     140
     141    static function AdminMenu() {
     142        wpfb_call('AdminLite', 'SetupMenu');
     143    }
     144
     145    static function AdminBar() {
     146        wpfb_call('AdminBar', 'AdminBar');
     147    }
     148
     149    static function Sync() {
     150        wpfb_call('Sync', 'Sync');
     151    }
     152
     153    static function GenRewriteRules() {
     154        wpfb_call('Misc', 'GenRewriteRules');
     155    }
     156
     157    static function GetPostId($query = null) {
     158        global $wp_query, $post;
     159
     160        if (!empty($post->ID))
     161            return $post->ID;
     162
     163        if (empty($query))
     164            $query = & $wp_query;
     165
     166        return ((!empty($query->post) && $query->post->ID > 0) ? $query->post->ID :
     167                        (!empty($query->queried_object_id) ? $query->queried_object_id :
     168                                (!empty($query->query['post_id']) ? $query->query['post_id'] :
     169                                        (!empty($query->query['page_id']) ? $query->query['page_id'] :
     170                                                0))));
     171    }
     172
     173    static function ParseQuery(&$query) {
     174        // conditional loading of the search hooks
     175        global $wp_query;
     176
     177        if (!empty($wp_query->query_vars['s']))
     178            wpfb_loadclass('Search');
     179
     180
     181        if (!empty($_GET['wpfb_s']) || !empty($_GET['s'])) {
     182            WPFB_Core::$file_browser_search = true;
     183            add_filter('the_excerpt', array(__CLASS__, 'SearchExcerptFilter'), 100); // must be lower than 11 (before do_shortcode) and after wpautop (>9)
     184        }
     185
     186        // check if current post is file browser and get currenlty selected file or category
     187        if (($id = self::GetPostId($query)) == WPFB_Core::$settings->file_browser_post_id) {
     188            wpfb_loadclass('File', 'Category');
     189            if (!empty($_GET['wpfb_file']))
     190                self::$file_browser_item = WPFB_File::GetFile($_GET['wpfb_file']);
     191            elseif (!empty($_GET['wpfb_cat']))
     192                self::$file_browser_item = WPFB_Category::GetCat($_GET['wpfb_cat']);
     193            else {
     194                $url = (is_ssl() ? 'https' : 'http') . '://' . $_SERVER["HTTP_HOST"] . stripslashes($_SERVER['REQUEST_URI']);
     195                if (($qs = strpos($url, '?')) !== false)
     196                    $url = substr($url, 0, $qs); // remove query string
     197                $path = trim(substr($url, strlen(WPFB_Core::GetPostUrl($id))), '/');
     198                if (!empty($path)) {
     199                    self::$file_browser_item = WPFB_Item::GetByPath(urldecode($path));
     200                    if (is_null(self::$file_browser_item))
     201                        self::$file_browser_item = WPFB_Item::GetByPath($path);
     202                }
     203            }
     204        }
     205    }
     206
     207    static function DownloadRedirect() {
     208        $file = null;
     209
     210        if (!empty($_GET['wpfb_dl'])) {
     211            wpfb_loadclass('File');
     212            $file = WPFB_File::GetFile($_GET['wpfb_dl']);
     213            @ob_end_clean(); // FIX: clean the OB so any output before the actual download is truncated (OB is started in wp-filebase.php)
     214        } else {
     215            if (!WPFB_Core::$settings->download_base || is_admin())
     216                return;
     217            $dl_url_path = parse_url(home_url(WPFB_Core::$settings->download_base . '/'), PHP_URL_PATH);
     218            $pos = strpos($_SERVER['REQUEST_URI'], $dl_url_path);
     219            if ($pos === 0) {
     220                $filepath = trim(substr(stripslashes($_SERVER['REQUEST_URI']), strlen($dl_url_path)), '/');
     221                if (($qs = strpos($filepath, '?')) !== false)
     222                    $filepath = substr($filepath, 0, $qs); // remove query string
     223                if (!empty($filepath)) {
     224                    wpfb_loadclass('File', 'Category');
     225                    $file = is_null($file = WPFB_File::GetByPath($filepath)) ? WPFB_File::GetByPath(urldecode($filepath)) : $file;
     226                }
     227            }
     228        }
     229
     230        if (!empty($file) && is_object($file) && !empty($file->is_file)) {
     231            $file->Download();
     232            exit;
     233        }
     234    }
     235
     236    static function Ext2TypeFilter($arr) {
     237        $arr['interactive'][] = 'exe';
     238        $arr['interactive'][] = 'msi';
     239        return $arr;
     240    }
     241
     242    static function SearchExcerptFilter($content) {
     243        global $id;
     244
     245        // replace file browser post content with search results
     246        if (WPFB_Core::$file_browser_search && $id == WPFB_Core::$settings->file_browser_post_id) {
     247            wpfb_loadclass('Search', 'File', 'Category');
     248            $content = '';
     249            WPFB_Search::FileSearchContent($content);
     250        }
     251
     252        return $content;
     253    }
     254
     255    static function ContentFilter($content) {
     256        global $id, $wpfb_fb, $post;
     257        if (!WPFB_Core::$settings->parse_tags_rss && is_feed())
     258            return $content;
     259
     260        if (is_object($post) && !post_password_required()) {
     261            // TODO: file resulst are generated twice, 2nd time in the_excerpt filter (SearchExcerptFilter)
     262            // some themes do not use excerpts in search resulsts!!
     263            // replace file browser post content with search results
     264            if (WPFB_Core::$file_browser_search && $id == WPFB_Core::$settings->file_browser_post_id) {
     265                wpfb_loadclass('Search', 'File', 'Category');
     266                $content = '';
     267                WPFB_Search::FileSearchContent($content);
     268            } else { // do not hanlde attachments when searching
     269                $single = is_single() || is_page();
     270
     271                // the did_action check prevents JS beeing printed into the post during a pre-render (e.g. WP SEO)
     272                if ($single && $post->ID == WPFB_Core::$settings->file_browser_post_id && did_action('wp_print_scripts')) {
     273                    $wpfb_fb = true;
     274                    wpfb_loadclass('Output', 'File', 'Category');
     275                    WPFB_Output::FileBrowser($content, 0, empty($_GET['wpfb_cat']) ? 0 : intval($_GET['wpfb_cat']));
     276                }
     277
     278                if (self::GetOpt('auto_attach_files') && ($single || self::GetOpt('attach_loop'))) {
     279                    wpfb_loadclass('Output');
     280                    if (WPFB_Core::$settings->attach_pos == 0)
     281                        $content = WPFB_Output::PostAttachments(true) . $content;
     282                    else
     283                        $content .= WPFB_Output::PostAttachments(true);
     284                }
     285            }
     286        }
     287
     288        return $content;
     289    }
     290
     291    static function ShortCode($atts, $content = null, $tag = null) {
     292        wpfb_loadclass('Output');
     293        return WPFB_Output::ProcessShortCode(shortcode_atts(array(
     294                    'tag' => 'list', // file, fileurl, attachments
     295                    'id' => -1,
     296                    'path' => null,
     297                    'tpl' => null,
     298                    'sort' => null,
     299                    'showcats' => false,
     300                    'sortcats' => null,
     301                    'num' => 0,
     302                    'pagenav' => 1,
     303                    'linktext' => null,
     304                                                    ), $atts), $content, $tag);
     305    }
     306
     307    static function Footer() {
     308        global $wpfb_fb; // filebrowser loaded?
     309        // TODO: use enque and no cond loading ?
     310        if (!empty(self::$load_js)) {
     311            self::PrintJS();
     312        }
     313
     314        if (!empty($wpfb_fb) && !WPFB_Core::$settings->disable_footer_credits) {
     315            echo '<div id="wpfb-credits" name="wpfb-credits" style="' . esc_attr(WPFB_Core::$settings->footer_credits_style) . '">';
     316            printf(__('<a href="%s" title="Wordpress Download Manager Plugin" style="color:inherit;font-size:inherit;">Downloads served by WP-Filebase</a>', 'wp-filebase'), 'https://wpfilebase.com/');
     317            echo '</div>';
     318        }
     319    }
     320
     321    static function MceAddBtns() {
     322        add_filter('mce_external_plugins', array('WPFB_Core', 'McePlugins'));
     323        add_filter('mce_buttons', array('WPFB_Core', 'MceButtons'));
     324    }
     325
     326    static function McePlugins($plugins) {
     327        wpfb_loadclass('AdminLite');
     328        return WPFB_AdminLite::McePlugins($plugins);
     329    }
     330
     331    static function MceButtons($buttons) {
     332        wpfb_loadclass('AdminLite');
     333        return WPFB_AdminLite::MceButtons($buttons);
     334    }
     335
     336    static function UpdateOption($name, $value = null) {
     337        WPFB_Core::$settings->$name = $value;
     338        update_option(WPFB_OPT_NAME, (array) WPFB_Core::$settings);
     339    }
     340
     341    static function UploadDir() {
     342        static $upload_path = '';
     343        return empty($upload_path) ? ($upload_path = path_join(ABSPATH, empty(WPFB_Core::$settings->upload_path) ? 'wp-content/uploads/filebase' : WPFB_Core::$settings->upload_path)) : $upload_path;
     344    }
     345
     346    static function GetPostUrl($id) {
     347        return isset(self::$post_url_cache[$id]) ? self::$post_url_cache[$id] : (self::$post_url_cache[$id] = get_permalink($id));
     348    }
     349
     350    static function GetSortSql($sort = null, $attach_order = false, $for_cat = false) {
     351        wpfb_loadclass('Output');
     352        $sql = $attach_order ? ("`" . ($for_cat ? 'cat_order' : 'file_attach_order') . "` ASC, ") : "";
     353        foreach (explode(',', $sort) as $s) {
     354            list($sf, $sd) = WPFB_Output::ParseSorting($s, $for_cat);
     355            $sql .= "`" . esc_sql($sf) . "` $sd, ";
     356        }
     357        return substr($sql, 0, -2);
     358    }
     359
     360    static function EnqueueScripts() {
     361        global $wp_query;
     362
     363        if (!WPFB_Core::$settings->late_script_loading && ((!empty($wp_query->queried_object_id) && $wp_query->queried_object_id == WPFB_Core::$settings->file_browser_post_id) ||
     364                !empty($wp_query->post) && $wp_query->post->ID == WPFB_Core::$settings->file_browser_post_id)) {
     365            wp_enqueue_script('jquery-treeview-async');
     366            wp_enqueue_style('jquery-treeview');
     367        }
     368    }
     369
     370    static function PrintJS() {
     371        static $printed = false;
     372        if ($printed)
     373            return;
     374        $printed = true;
     375
     376        wp_print_scripts(WPFB);
     377
     378        $context_menu = current_user_can('upload_files') && self::GetOpt('file_context_menu') && !defined('WPFB_EDITOR_PLUGIN') && !is_admin();
     379
     380        $conf = array(
     381            'ql' => !is_admin(), // querylinks with jQuery
     382            'hl' => (int) self::GetOpt('hide_links'), // hide links
     383            'pl' => (self::GetOpt('disable_permalinks') ? 0 : (int) !!get_option('permalink_structure')), // permlinks
     384            'hu' => trailingslashit(home_url()), // home url
     385            'db' => self::GetOpt('download_base'), // urlbase
     386            'fb' => self::GetPostUrl(self::GetOpt('file_browser_post_id')),
     387            'cm' => (int) $context_menu,
     388            'ajurl' => WPFB_Core::$ajax_url,
     389            'ajurlpub' => WPFB_Core::$ajax_url_public
     390        );
     391
     392        if ($context_menu) {
     393            $conf['fileEditUrl'] = admin_url("admin.php?page=wpfilebase_files&action=editfile&file_id=");
     394
     395            //wp_print_scripts('jquery-contextmenu');
     396            //wp_print_styles   ('jquery-contextmenu');
     397        }
     398
     399        echo "<script type=\"text/javascript\">\n//<![CDATA[\n", 'wpfbConf=', json_encode($conf), ';';
     400
     401        if ($context_menu) {
     402            echo
     403            "wpfbContextMenu=[
     404    {'", __('Edit'), "':{onclick:wpfb_menuEdit,icon:'" . WPFB_PLUGIN_URI . "extras/jquery/contextmenu/page_white_edit.png'}, },
     405    jQuery.contextMenu.separator,
     406    {'", __('Delete'), "':{onclick:wpfb_menuDel,icon:'" . WPFB_PLUGIN_URI . "extras/jquery/contextmenu/delete_icon.gif'}}
     407];\n";
     408        }
     409
     410        echo "function wpfb_ondl(file_id,file_url,file_path){ ", WPFB_Core::$settings->dlclick_js, " }";
     411        echo "\n//]]>\n</script>\n";
     412    }
     413
     414// OPTIMZE: not so deep function calls
     415// gets custom template list or single if tag specified
     416    static function GetFileTpls($tag = null) {
     417        if ($tag == 'default')
     418            return self::GetOpt('template_file');
     419        $tpls = get_option(WPFB_OPT_NAME . '_tpls_file');
     420        return empty($tag) ? $tpls : @$tpls[$tag];
     421    }
     422
     423    static function GetCatTpls($tag = null) {
     424        if ($tag == 'default')
     425            return self::GetOpt('template_cat');
     426        $tpls = get_option(WPFB_OPT_NAME . '_tpls_cat');
     427        return empty($tag) ? $tpls : @$tpls[$tag];
     428    }
     429
     430    static function GetTpls($type, $tag = null) {
     431        return ($type == 'cat') ? self::GetCatTpls($tag) : self::GetFileTpls($tag);
     432    }
     433
     434    static function SetFileTpls($tpls) {
     435        return is_array($tpls) ? update_option(WPFB_OPT_NAME . '_tpls_file', $tpls) : false;
     436    }
     437
     438    static function SetCatTpls($tpls) {
     439        return is_array($tpls) ? update_option(WPFB_OPT_NAME . '_tpls_cat', $tpls) : false;
     440    }
     441
     442    static function GetParsedTpl($type, $tag) {
     443        if (empty($tag))
     444            return null;
     445        if ($tag == 'default')
     446            return self::GetOpt("template_{$type}_parsed");
     447        $on = WPFB_OPT_NAME . '_ptpls_' . $type;
     448        $ptpls = get_option($on);
     449        if (empty($ptpls)) {
     450            $ptpls = wpfb_call('TplLib', 'Parse', self::GetTpls($type));
     451            update_option($on, $ptpls);
     452        }
     453        return empty($ptpls[$tag]) ? null : $ptpls[$tag];
     454    }
     455
     456    static function Cron() {
     457        if (self::$settings->cron_sync ) {
     458            wpfb_call('Sync', 'Sync');
     459            update_option(WPFB_OPT_NAME . '_cron_sync_time', empty($_SERVER["REQUEST_TIME"]) ? time() : $_SERVER["REQUEST_TIME"]);
     460        }
     461    }
     462
     463    static function GetMaxUlSize() {
     464        return wpfb_call('Misc', 'ParseIniFileSize', ini_get('upload_max_filesize'));
     465    }
     466
     467    public static function GetCustomFields($full_field_names = false, &$default_values = null) {
     468        $custom_fields = isset(WPFB_Core::$settings->custom_fields) ? explode("\n", WPFB_Core::$settings->custom_fields) : array();
     469        $arr = array();
     470        $default_values = array();
     471        if (empty($custom_fields[0]))
     472            return array();
     473        foreach ($custom_fields as $cf) {
     474            $cfa = explode("|", $cf);
     475            $arr[$k = $full_field_names ? ('file_custom_' . trim($cfa[1])) : trim($cfa[1])] = $cfa[0];
     476            $default_values[$k] = empty($cfa[2]) ? '' : $cfa[2];
     477        }
     478        return $arr;
     479    }
     480
     481    static function GetOldCustomCssPath($path = null) {
     482        $path = empty($path) ? self::UploadDir() : (ABSPATH . '/' . trim(str_replace('\\', '/', str_replace('..', '', $path)), '/'));
     483        return @is_dir($path) ? "$path/_wp-filebase.css" : null;
     484    }
     485
     486    static function CreateTplFunc($parsed_tpl) {
     487        return create_function('$f,$e=null', "return ($parsed_tpl);");
     488    }
     489
     490    static function PreSetPluginsTransientFilter($value) {
     491        if (!isset($value->response) || !is_array($value->response))
     492            return $value;
     493        $wpfb_dir = basename(WPFB_PLUGIN_ROOT);
     494        $lvi = wpfb_call('ExtensionLib', 'GetLatestVersionInfoExt');
     495        if (!empty($lvi))
     496            $value->response = array_merge($value->response, $lvi);
     497        return $value;
     498    }
     499
     500    static function PluginsApiFilter($value, $action = null, $args = null) {
     501        if (!is_object($args))
     502            $args = (object) $args;
     503        return ($action === 'plugin_information' && ( strncmp($args->slug, "wpfb-", 5) === 0)) ? wpfb_call('ExtensionLib', 'GetApiPluginInfo', $args->slug) : $value;
     504    }
     505
     506    static function CurUserCanCreateCat() {
     507        return current_user_can('manage_categories');
     508    }
     509
     510    static function CurUserCanUpload() {
     511        return (current_user_can('upload_files'));
     512    }
     513
    23514}
    24 
    25 static function InitClass()
    26 {   
    27     self::$ajax_url = WPFB_Core::PluginUrl('wpfb-ajax.php');   
    28     if(defined('WPFB_NO_CORE_INIT')) return;    // used with CSS proxy
    29    
    30     //Load settings
    31     self::$settings = (object)get_option(WPFB_OPT_NAME);
    32    
    33     // load lang
    34     $lang_dir = defined('WPFB_LANG_DIR') ? ('../../'.WPFB_LANG_DIR) : basename(WPFB_PLUGIN_ROOT).'/languages';
    35     load_plugin_textdomain('wp-filebase', false, $lang_dir);
    36 
    37     add_action('parse_query', array(__CLASS__, 'ParseQuery')); // search
    38     add_action('wp_enqueue_scripts', array(__CLASS__, 'EnqueueScripts'));
    39     add_action('wp_footer', array(__CLASS__, 'Footer'));   
    40     add_action('generate_rewrite_rules', array(__CLASS__, 'GenRewriteRules'));
    41     add_action(WPFB.'_cron', array(__CLASS__, 'Cron'));
    42     add_action('wpfilebase_sync', array(__CLASS__, 'Sync')); // for Developers: New wp-filebase actions
    43    
    44     add_shortcode('wpfilebase', array(__CLASS__, 'ShortCode'));
    45    
    46     // for attachments and file browser
    47     add_filter('the_content',   array(__CLASS__, 'ContentFilter'), 10); // must be lower than 11 (before do_shortcode) and after wpautop (>9)
    48     add_filter('ext2type', array(__CLASS__, 'Ext2TypeFilter'));
    49 
    50     add_filter('pre_set_site_transient_update_plugins', array(__CLASS__,'PreSetPluginsTransientFilter'));
    51     add_filter('plugins_api', array(__CLASS__,'PluginsApiFilter'), 10, 3);
    52    
    53    
    54     // register treeview stuff
    55     //wp_register_script('jquery-cookie', WPFB_PLUGIN_URI.'extras/jquery/jquery.cookie.js', array('jquery'));
    56     wp_register_script('jquery-treeview', WPFB_PLUGIN_URI.'extras/jquery/treeview/jquery.treeview.js', array('jquery'), WPFB_VERSION);
    57     wp_register_script('jquery-treeview-edit', WPFB_PLUGIN_URI.'extras/jquery/treeview/jquery.treeview.edit.js', array('jquery-treeview'), WPFB_VERSION);
    58     wp_register_script('jquery-treeview-async', WPFB_PLUGIN_URI.'extras/jquery/treeview/jquery.treeview.async.js', array('jquery-treeview-edit'), WPFB_VERSION);
    59     wp_register_style('jquery-treeview', WPFB_PLUGIN_URI.'extras/jquery/treeview/jquery.treeview.css', array(), WPFB_VERSION);
    60 
    61     // DataTables
    62     wp_register_script('jquery-dataTables', WPFB_PLUGIN_URI.'extras/jquery/dataTables/js/jquery.dataTables.min.js', array('jquery'), WPFB_VERSION);
    63     wp_register_style('jquery-dataTables', WPFB_PLUGIN_URI.'extras/jquery/dataTables/css/jquery.dataTables.css', array(), WPFB_VERSION);
    64    
    65     wp_register_script('jquery-dataTables-columnFilter', WPFB_PLUGIN_URI.'extras/jquery/dataTables/js/jquery.dataTables.columnFilter.js', array('jquery-dataTables'), WPFB_VERSION);
    66 
    67     wp_register_script(WPFB, WPFB_PLUGIN_URI.'js/common.js', array('jquery'), WPFB_VERSION); // cond loading (see Footer)
    68    
    69     if(empty(WPFB_Core::$settings->disable_css)) {
    70         $wpfb_css = get_option('wpfb_css');
    71         if($wpfb_css) { // static file?
    72             wp_enqueue_style(WPFB, strstr($wpfb_css,'//'), array(), WPFB_VERSION, 'all');
    73         } else {
    74             $upload_path = path_is_absolute(WPFB_Core::$settings->upload_path) ? '' : WPFB_Core::$settings->upload_path;
    75             wp_enqueue_style(WPFB, WPFB_Core::PluginUrl("wp-filebase_css.php?rp=$upload_path"), array(), WPFB_VERSION, 'all');
    76         }
    77     }
    78 
    79    
    80     $wpfb_admin_page = (is_admin() && !empty($_GET['page']) && strpos($_GET['page'], 'wpfilebase_') !== false) || defined('WPFB_EDITOR_PLUGIN');
    81     if($wpfb_admin_page)
    82         wpfb_loadclass('Admin');
    83    
    84     // live admin
    85     if(($wpfb_admin_page && @$_GET['page'] == 'wpfilebase_filebrowser') || ((WPFB_Core::CurUserCanCreateCat() || WPFB_Core::CurUserCanUpload()) && !is_admin())) {
    86         wp_enqueue_script(WPFB.'-live-admin', WPFB_PLUGIN_URI.'js/live-admin.js', array('jquery'), WPFB_VERSION);
    87         if(self::GetOpt('admin_bar'))
    88             add_action( 'admin_bar_menu', array(__CLASS__, 'AdminBar'), 80 );
    89         if(self::GetOpt('file_context_menu')) {
    90             wp_enqueue_script('jquery-contextmenu', WPFB_PLUGIN_URI.'extras/jquery/contextmenu/jquery.contextmenu.js', array('jquery'));
    91             wp_enqueue_style('jquery-contextmenu', WPFB_PLUGIN_URI.'extras/jquery/contextmenu/jquery.contextmenu.css', array(), WPFB_VERSION);
    92         }
    93         wp_enqueue_style('wpfb-live-admin', WPFB_PLUGIN_URI.'css/live-admin.css', array(), WPFB_VERSION);
    94     }
    95 
    96     // for admin
    97     if (current_user_can('edit_posts') || current_user_can('edit_pages'))
    98         self::MceAddBtns();
    99        
    100     self::DownloadRedirect();
    101    
    102     if( (WPFB_Core::$settings->frontend_upload || current_user_can('upload_files')) && (!empty($_GET['wpfb_upload_file']) || !empty($_GET['wpfb_add_cat'])))
    103         wpfb_call('Admin', empty($_GET['wpfb_upload_file'])?'ProcessWidgetAddCat':'ProcessWidgetUpload');
    104 }
    105 
    106 static function InitDirectScriptAccess()
    107 {
    108     if(is_multisite() && !empty($_REQUEST['blog_id']) && get_current_blog_id() != $_REQUEST['blog_id'] ) {
    109         $blog_id = (int)$_REQUEST['blog_id'];
    110         if(!get_blog_details($blog_id, false))
    111             die('Blog does not exists!');
    112         switch_to_blog( $blog_id);
    113     }   
    114 }
    115 
    116 static function GetOpt($name = null) {  return empty($name) ? (array)WPFB_Core::$settings : (isset(WPFB_Core::$settings->$name) ? WPFB_Core::$settings->$name : null); }
    117 
    118 static function AdminInit() {
    119     wpfb_loadclass('AdminLite');
    120     if(!empty($_GET['page']) && strpos($_GET['page'], 'wpfilebase_') !== false)
    121         wpfb_loadclass('Admin');
    122     WPFB_AdminLite::Init();
    123 }
    124 static function AdminMenu() {wpfb_call('AdminLite', 'SetupMenu');}
    125 static function AdminBar() { wpfb_call('AdminBar','AdminBar'); }
    126 
    127 static function Sync() { wpfb_call('Sync', 'Sync'); }
    128 static function GenRewriteRules() { wpfb_call('Misc','GenRewriteRules'); }
    129 
    130 static function GetPostId($query = null)
    131 {
    132     global $wp_query, $post;
    133    
    134     if(!empty($post->ID)) return $post->ID;
    135    
    136     if(empty($query)) $query =& $wp_query; 
    137    
    138     return ((!empty($query->post)&&$query->post->ID>0) ? $query->post->ID :
    139             (!empty($query->queried_object_id) ? $query->queried_object_id :
    140             (!empty($query->query['post_id']) ? $query->query['post_id'] :
    141             (!empty($query->query['page_id'])? $query->query['page_id'] :
    142             0))));
    143 }
    144 
    145 static function ParseQuery(&$query)
    146 {
    147     // conditional loading of the search hooks
    148     global $wp_query;
    149    
    150     if (!empty($wp_query->query_vars['s']))
    151             wpfb_loadclass('Search');
    152            
    153    
    154     if(!empty($_GET['wpfb_s']) || !empty($_GET['s'])) {
    155         WPFB_Core::$file_browser_search = true;     
    156         add_filter('the_excerpt',   array(__CLASS__, 'SearchExcerptFilter'), 100); // must be lower than 11 (before do_shortcode) and after wpautop (>9)
    157     }
    158    
    159     // check if current post is file browser
    160     if( ($id=self::GetPostId($query)) == WPFB_Core::$settings->file_browser_post_id)
    161     {
    162         wpfb_loadclass('File','Category');
    163         if(!empty($_GET['wpfb_file'])) self::$file_browser_item = WPFB_File::GetFile($_GET['wpfb_file']);
    164         elseif(!empty($_GET['wpfb_cat'])) self::$file_browser_item = WPFB_Category::GetCat($_GET['wpfb_cat']);
    165         else {
    166             $url = (is_ssl()?'https':'http').'://'.$_SERVER["HTTP_HOST"].stripslashes($_SERVER['REQUEST_URI']);
    167             if( ($qs=strpos($url,'?')) !== false ) $url = substr($url,0,$qs); // remove query string   
    168             $path = trim(substr($url, strlen(WPFB_Core::GetPostUrl($id))), '/');
    169             if(!empty($path)) {
    170                 self::$file_browser_item = WPFB_Item::GetByPath(urldecode($path));
    171                 if(is_null(self::$file_browser_item)) self::$file_browser_item = WPFB_Item::GetByPath($path);
    172             }
    173         }
    174     }   
    175 }
    176 
    177 
    178 
    179 static function DownloadRedirect()
    180 {
    181     $file = null;
    182    
    183     if(!empty($_GET['wpfb_dl'])) {
    184         wpfb_loadclass('File');
    185         $file = WPFB_File::GetFile($_GET['wpfb_dl']);
    186         @ob_end_clean(); // FIX: clean the OB so any output before the actual download is truncated (OB is started in wp-filebase.php)
    187     } else {
    188         if(!WPFB_Core::$settings->download_base || is_admin()) return;
    189         $dl_url_path = parse_url(home_url(WPFB_Core::$settings->download_base.'/'), PHP_URL_PATH);
    190         $pos = strpos($_SERVER['REQUEST_URI'], $dl_url_path);
    191         if($pos === 0) {
    192             $filepath = trim(substr(stripslashes($_SERVER['REQUEST_URI']), strlen($dl_url_path)), '/');
    193             if( ($qs=strpos($filepath,'?')) !== false ) $filepath = substr($filepath,0,$qs); // remove query string
    194             if(!empty($filepath)) {
    195                 wpfb_loadclass('File','Category');
    196                 $file = is_null($file=WPFB_File::GetByPath($filepath)) ? WPFB_File::GetByPath(urldecode($filepath)) : $file;
    197             }
    198         }
    199     }
    200    
    201     if(!empty($file) && is_object($file) && !empty($file->is_file)) {
    202         $file->Download();     
    203         exit;
    204     } /* else { // don't set coockies anymore
    205         // no download, a normal request: set site visited coockie to disable referer check
    206         if(empty($_COOKIE[WPFB_OPT_NAME])) {
    207             @setcookie(WPFB_OPT_NAME, '1');
    208             $_COOKIE[WPFB_OPT_NAME] = '1';
    209         }
    210     } */
    211 }
    212 
    213 static function Ext2TypeFilter($arr) {
    214     $arr['interactive'][] = 'exe';
    215     $arr['interactive'][] = 'msi';
    216     return $arr;
    217 }
    218 
    219 static function SearchExcerptFilter($content)
    220 {
    221     global $id;
    222    
    223     // replace file browser post content with search results
    224     if(WPFB_Core::$file_browser_search && $id == WPFB_Core::$settings->file_browser_post_id)
    225     {
    226         wpfb_loadclass('Search','File','Category');
    227         $content = '';
    228         WPFB_Search::FileSearchContent($content);
    229     }
    230    
    231     return $content;
    232 }
    233 
    234 static function ContentFilter($content)
    235 {
    236     global $id, $wpfb_fb, $post;
    237    
    238     if(!WPFB_Core::$settings->parse_tags_rss && is_feed())
    239         return $content;
    240    
    241     if(is_object($post) && !post_password_required())
    242     {
    243         // TODO: file resulst are generated twice, 2nd time in the_excerpt filter (SearchExcerptFilter)
    244         // some themes do not use excerpts in search resulsts!!
    245         // replace file browser post content with search results
    246         if(WPFB_Core::$file_browser_search && $id == WPFB_Core::$settings->file_browser_post_id)
    247         {
    248             wpfb_loadclass('Search','File','Category');
    249             $content = '';
    250             WPFB_Search::FileSearchContent($content);
    251         } else { // do not hanlde attachments when searching
    252             $single = is_single() || is_page();
    253            
    254             // the did_action check prevents JS beeing printed into the post during a pre-render (e.g. WP SEO)
    255             if($single && $post->ID == WPFB_Core::$settings->file_browser_post_id && did_action('wp_print_scripts')) {
    256                 $wpfb_fb = true;
    257                 wpfb_loadclass('Output', 'File', 'Category');
    258                 WPFB_Output::FileBrowser($content, 0, empty($_GET['wpfb_cat']) ? 0 : intval($_GET['wpfb_cat']));
    259             }
    260        
    261             if(self::GetOpt('auto_attach_files') && ($single || self::GetOpt('attach_loop'))) {
    262                 wpfb_loadclass('Output');           
    263                 if(WPFB_Core::$settings->attach_pos == 0)
    264                     $content = WPFB_Output::PostAttachments(true) . $content;
    265                 else
    266                     $content .= WPFB_Output::PostAttachments(true);
    267             }
    268         }
    269     }
    270 
    271     return $content;
    272 }
    273 
    274 
    275 static function ShortCode($atts, $content=null, $tag=null) {
    276     wpfb_loadclass('Output');
    277     return WPFB_Output::ProcessShortCode(shortcode_atts(array(
    278         'tag' => 'list', // file, fileurl, attachments
    279         'id' => -1,
    280         'path' => null,
    281         'tpl' => null,
    282         'sort' => null,
    283         'showcats' => false,
    284         'sortcats' => null,
    285         'num' => 0,
    286         'pagenav' => 1,
    287         'linktext' => null,
    288            
    289     ), $atts), $content, $tag);
    290 }
    291 
    292 
    293 static function Footer() {
    294     global $wpfb_fb; // filebrowser loaded?
    295    
    296     // TODO: use enque and no cond loading ?
    297     if(!empty(self::$load_js)) {
    298         self::PrintJS();
    299     }
    300    
    301     if(!empty($wpfb_fb) && !WPFB_Core::$settings->disable_footer_credits) {
    302         echo '<div id="wpfb-credits" name="wpfb-credits" style="'.esc_attr(WPFB_Core::$settings->footer_credits_style).'">';
    303         printf(__('<a href="%s" title="Wordpress Download Manager Plugin" style="color:inherit;font-size:inherit;">Downloads served by WP-Filebase</a>','wp-filebase'),'https://wpfilebase.com/');
    304         echo '</div>';
    305     }
    306 }
    307 
    308 
    309 
    310 static function MceAddBtns() {
    311     add_filter('mce_external_plugins', array('WPFB_Core', 'McePlugins'));
    312     add_filter('mce_buttons', array('WPFB_Core', 'MceButtons'));
    313 }
    314 static function McePlugins($plugins) { wpfb_loadclass('AdminLite'); return WPFB_AdminLite::McePlugins($plugins); }
    315 static function MceButtons($buttons) { wpfb_loadclass('AdminLite'); return WPFB_AdminLite::MceButtons($buttons); }
    316 
    317 static function UpdateOption($name, $value = null) {
    318     WPFB_Core::$settings->$name = $value;
    319     update_option(WPFB_OPT_NAME, (array)WPFB_Core::$settings);
    320 }
    321 
    322 static function UploadDir() {
    323     static $upload_path = '';
    324     return empty($upload_path) ? ($upload_path = path_join(ABSPATH, empty(WPFB_Core::$settings->upload_path) ? 'wp-content/uploads/filebase' : WPFB_Core::$settings->upload_path)) : $upload_path;
    325 }
    326 
    327 static function GetPostUrl($id) { return isset(self::$post_url_cache[$id]) ? self::$post_url_cache[$id] : (self::$post_url_cache[$id] = get_permalink($id)); }
    328 
    329 static function GetSortSql($sort=null, $attach_order=false, $for_cat=false)
    330 {
    331     wpfb_loadclass('Output');
    332     $sql =  $attach_order ? ("`".($for_cat ? 'cat_order' : 'file_attach_order')."` ASC, ") : "";
    333     foreach(explode(',', $sort) as $s) {
    334         list($sf, $sd) = WPFB_Output::ParseSorting($s, $for_cat);
    335         $sql .= "`".esc_sql($sf)."` $sd, ";
    336     }
    337     return substr($sql, 0,-2);
    338 }
    339 
    340 static function EnqueueScripts()
    341 {
    342     global $wp_query;
    343    
    344     if( !WPFB_Core::$settings->late_script_loading
    345             && ((!empty($wp_query->queried_object_id) && $wp_query->queried_object_id == WPFB_Core::$settings->file_browser_post_id) ||
    346             !empty($wp_query->post) && $wp_query->post->ID == WPFB_Core::$settings->file_browser_post_id)) {
    347         wp_enqueue_script('jquery-treeview-async');
    348         wp_enqueue_style('jquery-treeview');
    349     }
    350 }
    351 
    352 static function PrintJS() {
    353     static $printed = false;
    354     if($printed) return;
    355     $printed = true;
    356    
    357     wp_print_scripts(WPFB);
    358    
    359     $context_menu = current_user_can('upload_files') && self::GetOpt('file_context_menu') && !defined('WPFB_EDITOR_PLUGIN') && !is_admin();
    360    
    361     $conf = array(
    362         'ql'=>!is_admin(), // querylinks with jQuery
    363         'hl'=> (int)self::GetOpt('hide_links'), // hide links
    364         'pl'=>(self::GetOpt('disable_permalinks') ? 0 : (int)!!get_option('permalink_structure')), // permlinks
    365         'hu'=> trailingslashit(home_url()),// home url
    366         'db'=> self::GetOpt('download_base'),// urlbase
    367         'fb'=> self::GetPostUrl(self::GetOpt('file_browser_post_id')),
    368         'cm'=>(int)$context_menu,
    369         'ajurl'=>WPFB_Core::$ajax_url
    370     );
    371    
    372     if($context_menu) {
    373         $conf['fileEditUrl'] = admin_url("admin.php?page=wpfilebase_files&action=editfile&file_id=");
    374        
    375         //wp_print_scripts('jquery-contextmenu');
    376         //wp_print_styles   ('jquery-contextmenu');
    377     }
    378        
    379     echo "<script type=\"text/javascript\">\n//<![CDATA[\n",'wpfbConf=',json_encode($conf),';';
    380    
    381     if($context_menu) {
    382         echo
    383 "wpfbContextMenu=[
    384     {'",__('Edit'),"':{onclick:wpfb_menuEdit,icon:'".WPFB_PLUGIN_URI."extras/jquery/contextmenu/page_white_edit.png'}, },
    385     jQuery.contextMenu.separator,
    386     {'",__('Delete'),"':{onclick:wpfb_menuDel,icon:'".WPFB_PLUGIN_URI."extras/jquery/contextmenu/delete_icon.gif'}}
    387 ];\n";
    388        
    389     }
    390    
    391     echo "function wpfb_ondl(file_id,file_url,file_path){ ",WPFB_Core::$settings->dlclick_js," }"; 
    392     echo "\n//]]>\n</script>\n";
    393 }
    394 
    395 // OPTIMZE: not so deep function calls
    396 
    397 // gets custom template list or single if tag specified
    398 static function GetFileTpls($tag=null) {
    399     if($tag == 'default') return self::GetOpt('template_file');
    400     $tpls = get_option(WPFB_OPT_NAME.'_tpls_file');
    401     return empty($tag) ? $tpls : @$tpls[$tag];
    402 }
    403 
    404 static function GetCatTpls($tag=null) {
    405     if($tag == 'default') return self::GetOpt('template_cat');
    406     $tpls = get_option(WPFB_OPT_NAME.'_tpls_cat');
    407     return empty($tag) ? $tpls : @$tpls[$tag];
    408 }
    409 
    410 static function GetTpls($type, $tag=null) { return ($type == 'cat') ? self::GetCatTpls($tag) : self::GetFileTpls($tag);}
    411 
    412 static function SetFileTpls($tpls) { return is_array($tpls) ? update_option(WPFB_OPT_NAME.'_tpls_file', $tpls) : false; }
    413 static function SetCatTpls($tpls) { return is_array($tpls) ? update_option(WPFB_OPT_NAME.'_tpls_cat', $tpls) : false; }
    414 
    415 static function GetParsedTpl($type, $tag) {
    416     if(empty($tag)) return null;
    417     if($tag == 'default') return self::GetOpt("template_{$type}_parsed");
    418     $on = WPFB_OPT_NAME.'_ptpls_'.$type;
    419     $ptpls = get_option($on);
    420     if(empty($ptpls)) {
    421         $ptpls = wpfb_call('TplLib','Parse',self::GetTpls($type));
    422         update_option($on, $ptpls);
    423     }
    424     return empty($ptpls[$tag]) ? null : $ptpls[$tag];
    425 }
    426 
    427 
    428 
    429 static function Cron() {
    430     if(self::$settings->cron_sync ) {
    431         wpfb_call('Sync', 'Sync');
    432         update_option(WPFB_OPT_NAME.'_cron_sync_time', empty($_SERVER["REQUEST_TIME"]) ? time() : $_SERVER["REQUEST_TIME"]);
    433     }
    434 }
    435 
    436 static function GetMaxUlSize() {    return wpfb_call('Misc','ParseIniFileSize', ini_get('upload_max_filesize')); }
    437 
    438 public static function GetCustomFields($full_field_names=false, &$default_values=null) {
    439     $custom_fields = isset(WPFB_Core::$settings->custom_fields)?explode("\n",WPFB_Core::$settings->custom_fields):array();
    440     $arr = array();
    441     $default_values = array();
    442     if(empty($custom_fields[0])) return array();
    443     foreach($custom_fields as $cf) {
    444         $cfa = explode("|", $cf);
    445         $arr[$k = $full_field_names?('file_custom_'.trim($cfa[1])):trim($cfa[1])] = $cfa[0];
    446         $default_values[$k] = empty($cfa[2]) ? '' : $cfa[2];
    447     }
    448     return $arr;
    449 }
    450 
    451 
    452 static function GetOldCustomCssPath($path=null) {
    453     $path = empty($path) ? self::UploadDir() : (ABSPATH .'/'.trim(str_replace('\\','/',str_replace('..','', $path)),'/'));
    454     return @is_dir($path) ? "$path/_wp-filebase.css" : null;
    455 }
    456 
    457 static function CreateTplFunc($parsed_tpl) {    return create_function('$f,$e=null', "return ($parsed_tpl);"); }
    458 
    459 
    460 static function PreSetPluginsTransientFilter($value)
    461 {
    462     if(!isset($value->response) || !is_array($value->response))
    463         return $value;
    464     $wpfb_dir = basename(WPFB_PLUGIN_ROOT);
    465     $lvi = wpfb_call('ExtensionLib','GetLatestVersionInfoExt');
    466     if(!empty($lvi)) $value->response = array_merge($value->response, $lvi);
    467     return $value;
    468 }
    469 
    470 static function PluginsApiFilter($value, $action=null, $args=null)
    471 {
    472     if(!is_object($args)) $args = (object)$args;
    473     return ($action === 'plugin_information' && ( strncmp($args->slug, "wpfb-", 5) === 0))
    474               ? wpfb_call('ExtensionLib','GetApiPluginInfo', $args->slug)
    475               : $value;
    476 }
    477 
    478 
    479 static function CurUserCanCreateCat()
    480 {
    481     return  current_user_can('manage_categories');
    482 }
    483 
    484 static function CurUserCanUpload()
    485 {
    486     return (current_user_can('upload_files'));
    487 }
    488 
    489 }
  • wp-filebase/trunk/classes/Download.php

    r1254671 r1303067  
    463463    // clean up things that are not needed for download
    464464    @session_write_close(); // disable blocking of multiple downloads at the same time
    465     global $wpdb;
    466     if(!empty($wpdb->dbh) && is_resource($wpdb->dbh))
    467         @mysql_close($wpdb->dbh);
    468     else
    469         @mysql_close();
    470    
     465        if(function_exists('mysql_close')) {
     466            global $wpdb;
     467            if(!empty($wpdb->dbh) && is_resource($wpdb->dbh))
     468                    @mysql_close($wpdb->dbh);
     469            else
     470                    @mysql_close();
     471        }
     472
    471473    @ob_flush();
    472    @flush();
     474        @flush();
    473475   
    474476   
  • wp-filebase/trunk/classes/ExtensionLib.php

    r1298742 r1303067  
    55    private static function apiRequest($act, $post_data = null, $use_ssl = true) {
    66        global $wp_version;
    7         //print_r($post_data);
     7       
    88        $site = rawurlencode(base64_encode(get_option('siteurl')));
    99        $url = "http" . ($use_ssl ? "s://ssl-account.com" : ":/") . "/interface.fabi.me/wpfilebase-pro/$act.php";
    1010        $get_args = array('version' => WPFB_VERSION, 'pl_slug' => 'wp-filebase', 'pl_ver' => WPFB_VERSION, 'wp_ver' => $wp_version , 'site' => $site);
    1111
     12        // try to get from cache
     13        $cache_key =  'wpfb_apireq_'.md5($act.'||'.serialize($get_args).'||'.serialize($post_data).'||'.__FILE__);       
     14        $res = get_transient($cache_key);
     15        if ($res !== false) {
     16            return $res;
     17        }
     18       
     19        //trigger_error ( "WP-Filebase apiRequest (ssl=$use_ssl): $act ".json_encode($post_data), E_USER_NOTICE );
     20       
    1221        if (empty($post_data)) {
    1322            $res = wp_remote_get($url, $get_args);
     
    2332            return false;
    2433        }
    25         return empty($res['body']) ? false : json_decode($res['body']);
     34       
     35        $res = empty($res['body']) ? false : json_decode($res['body']);
     36       
     37        set_transient($cache_key, $res, 0  + 6 * HOUR_IN_SECONDS);
     38       
     39        return $res;
    2640    }
    2741
     
    4862    static function GetLatestVersionInfoExt() {
    4963        $ext_vers = json_encode(self::GetExtensionsVersionNumbers());
    50         $cache_key = 'wpfb_updcheckext_' . md5($ext_vers);
    51         $res = get_transient($cache_key);
    52         if ($res !== false)
    53             return $res;
    5464        $res = self::apiRequest('update-check-ext', array('extensions' => $ext_vers));
    55         $res = empty($res) ? array() : (array) $res;
    56         set_transient($cache_key, $res, 6 * HOUR_IN_SECONDS);
    57         return $res;
     65        return empty($res) ? array() : (array) $res;
    5866    }
    5967
    6068    static function QueryAvailableExtensions($bought_extensions_only = false) {
    61         $ext_vers = self::GetExtensionsVersionNumbers();
    62         $res = self::apiRequest('exts', array('bought' => $bought_extensions_only, 'extensions' => json_encode($ext_vers)));
    63         if (!$res)
    64             return false;
    65         $res = (object) $res;
    66         $res->info = (array) $res->info;
    67         foreach ($res->plugins as $i => $p) {
    68             $res->plugins[$i] = (object) $p;
    69             $res->plugins[$i]->ratings = (array) $res->plugins[$i]->ratings;
    70             $res->plugins[$i]->icons = (array) $res->plugins[$i]->icons;
     69        $ext_vers = json_encode(self::GetExtensionsVersionNumbers());
     70        $res = self::apiRequest('exts', array('bought' => $bought_extensions_only, 'extensions' => $ext_vers));
     71        if (!empty($res)) {
     72            $res = (object) $res;
     73            $res->info = (array) $res->info;
     74            foreach ($res->plugins as $i => $p) {
     75                $res->plugins[$i] = (object) $p;
     76                $res->plugins[$i]->ratings = (array) $res->plugins[$i]->ratings;
     77                $res->plugins[$i]->icons = (array) $res->plugins[$i]->icons;
     78            }
     79        } else {
     80            $res = null;
    7181        }
    7282        return $res;
  • wp-filebase/trunk/classes/File.php

    r1254671 r1303067  
    312312   
    313313   
     314
     315    function CurUserCanDelete($user = null)
     316    {
     317            return $this->CurUserCanEdit($user);
     318    }
     319
    314320    // only deletes file/thumbnail on FS, keeping DB entry
    315321    function Delete($keep_thumb=false)
  • wp-filebase/trunk/classes/Item.php

    r1254671 r1303067  
    588588                               
    589589                if($this->is_file) {
    590                     if(!@rename($old_path, c))
     590                    if(!@rename($old_path, $new_path))
    591591                        return array( 'error' => sprintf('Unable to move file %s!', $old_path));
    592592                    @chmod($new_path, octdec(WPFB_PERM_FILE));
  • wp-filebase/trunk/classes/ListTpl.php

    r1254671 r1303067  
    230230        $is_datatable = strpos($footer, ").dataTable(")!==false;
    231231       
    232         // TODO: no page_limit when dataTable?
     232        // TODO: no page_limit when dataTable? 
    233233        // hide pagenav when using datatable
    234234        $this->current_list->hide_pagenav = $this->current_list->hide_pagenav || $is_datatable;
  • wp-filebase/trunk/classes/Output.php

    r1254671 r1303067  
    239239        $files_before_cats = $browser && WPFB_Core::$settings->file_browser_fbc;   
    240240       
    241         $inline_add_cat = /*($cat && $cat->CurUserCanAddFiles()) ||*/  WPFB_Core::CurUserCanCreateCat() && (!isset($args['inline_add']) || $args['inline_add']);
     241        $inline_add_cat = (is_admin() || WPFB_Core::$settings->file_browser_inline_add) && /*($cat && $cat->CurUserCanAddFiles()) ||*/  WPFB_Core::CurUserCanCreateCat() && (!isset($args['inline_add']) || $args['inline_add']);
    242242   
    243243        $where = " cat_parent = $parent_id ";
     
    478478
    479479    $ajax_data =  array(
    480          'action'=>'tree',
     480         'wpfb_action'=>'tree',
    481481         'type'=>'browser',
    482482         'base' => intval($base)
     
    488488<script type="text/javascript">
    489489//<![CDATA[
    490 function wpfb_initfb<?php echo $jss ?>() {  jQuery("#<?php echo $id ?>").treeview(wpfb_fbsets<?php echo $jss ?>={url: "<?php echo WPFB_Core::$ajax_url ?>",
     490function wpfb_initfb<?php echo $jss ?>() {  jQuery("#<?php echo $id ?>").treeview(wpfb_fbsets<?php echo $jss ?>={url: "<?php echo WPFB_Core::$ajax_url_public ?>",
    491491ajax:{data:<?php echo json_encode($ajax_data); ?>,type:"post",error:function(x,status,error){if(error) alert(error);},complete:function(x,status){if(typeof(wpfb_setupLinks)=='function')wpfb_setupLinks();}},
    492492animated: "medium"}).data("settings",wpfb_fbsets<?php echo $jss ?>);
     
    614614                } ?>
    615615                <small><?php printf(str_replace('%d%s','%s',__('Maximum upload file size: %d%s.'/*def*/)), WPFB_Output::FormatFilesize(WPFB_Core::GetMaxUlSize())) ?></small>
    616                
    617616                <?php if(empty($auto_submit)) { ?><div style="float: right; text-align:right;"><input type="submit" class="button-primary" name="submit-btn" value="<?php _e('Add New','wp-filebase'); ?>" /></div>
    618617                <?php } ?>
    619618            </div>
     619
    620620        </form>
    621621    </div>
  • wp-filebase/trunk/classes/PLUpload.php

    r1254671 r1303067  
    5858    'multiple_queues' => false,
    5959    'max_file_size' => $max_upload_size.'b',
    60     'url' => WPFB_Core::PluginUrl('wpfb-async-upload.php'),
     60    'url' => add_query_arg('wpfb_action', 'upload', WPFB_Core::$ajax_url_public),
    6161    'flash_swf_url' => includes_url('js/plupload/plupload.flash.swf'),
    6262    'silverlight_xap_url' => includes_url('js/plupload/plupload.silverlight.xap'),
  • wp-filebase/trunk/classes/PLUploader.php

    r1254671 r1303067  
    100100    'multiple_queues' => $this->multi,
    101101    'max_file_size' => $max_upload_size.'b',
    102     'url' => WPFB_Core::PluginUrl('wpfb-async-upload.php'),
     102    'url' => add_query_arg('wpfb_action', 'upload', WPFB_Core::$ajax_url_public),
    103103    'flash_swf_url' => includes_url('js/plupload/plupload.flash.swf'),
    104104    'silverlight_xap_url' => includes_url('js/plupload/plupload.silverlight.xap'),
  • wp-filebase/trunk/classes/SWFUpload.php

    r1254671 r1303067  
    5252            button_image_url: '<?php echo $upload_image_path; ?>',
    5353            button_placeholder_id: "flash-browse-button",
    54             upload_url : "<?php echo esc_attr( WPFB_Core::PluginUrl('wpfb-async-upload.php') ); ?>",
     54            upload_url : "<?php echo esc_attr( add_query_arg('wpfb_action', 'upload', WPFB_Core::$ajax_url_public) ); ?>",
    5555            flash_url : "<?php echo includes_url('js/swfupload/swfupload.swf'); ?>",
    5656            file_post_name: "async-upload",
     
    8787//]]>
    8888</script>
    89 
    90 
    9189<?php do_action('pre-flash-upload-ui'); ?>
    9290    <div>
  • wp-filebase/trunk/classes/Settings.php

    r1254671 r1303067  
    9898
    9999         
     100           
     101        'file_browser_inline_add' => array('default' => true, 'title' => __('Inline Add','wp-filebase'), 'type' => 'checkbox', 'desc' => __('In each category display actions to add a file or category.','wp-filebase')),
    100102   
    101103            'folder_icon' => array('default' => '/plugins/wp-filebase/images/folder-icons/folder_orange48.png', 'title' => __('Folder Icon','wp-filebase'), 'type' => 'icon', 'icons' => $folder_icons, 'desc' => sprintf(__('Choose the default category icon and file browser icon. You can put custom icons in <code>%s</code>.','wp-filebase'),'wp-content/images/foldericons')),
     
    121123   
    122124    'allow_srv_script_upload'   => array('default' => false, 'title' => __('Allow script upload','wp-filebase'), 'type' => 'checkbox', 'desc' => __('If you enable this, scripts like PHP or CGI can be uploaded. <b>WARNING:</b> Enabling script uploads is a <b>security risk</b>!','wp-filebase')),
    123     'protect_upload_path'   => array('default' => true, 'title' => __('Protect upload path','wp-filebase'), 'type' => 'checkbox', 'desc' => __('This prevents direct access to files in the upload directory.','wp-filebase')),
     125    'protect_upload_path'           => array('default' => true, 'title' => __('Protect upload path','wp-filebase'), 'type' => 'checkbox', 'desc' => __('This prevents direct access to files in the upload directory.','wp-filebase'). ' '.__('Only applies on Apache webservers! For NGINX you have to edit its config file manually.','wp-filebase')),
    124126
    125127         
     
    176178"*Freeware|free\nShareware|share\nGNU General Public License|gpl|http://www.gnu.org/copyleft/gpl.html\nCC Attribution-NonCommercial-ShareAlike|ccbyncsa|http://creativecommons.org/licenses/by-nc-sa/3.0/", 'title' => __('Licenses','wp-filebase'), 'type' => 'textarea', 'desc' => &$multiple_entries_desc, 'nowrap' => true),
    177179    'requirements'          => array('default' =>
    178 "PDF Reader|pdfread|http://www.foxitsoftware.com/pdf/reader/addons.php
     180"PDF Reader|pdfread|https://www.foxitsoftware.com/products/pdf-reader/
    179181Java|java|http://www.java.com/download/
    180 Flash|flash|http://get.adobe.com/flashplayer/
    181182Open Office|ooffice|http://www.openoffice.org/download/index.html
    182 .NET Framework 3.5|.net35|http://www.microsoft.com/downloads/details.aspx?FamilyID=333325fd-ae52-4e35-b531-508d977d32a6",
     183",
    183184    'title' => __('Requirements','wp-filebase'), 'type' => 'textarea', 'desc' => $multiple_entries_desc . ' ' . __('You can optionally add |<i>URL</i> to each line to link to the required software/file.','wp-filebase'), 'nowrap' => true),
    184185   
  • wp-filebase/trunk/classes/TreeviewAdmin.php

    r1254671 r1303067  
    1 <?php class WPFB_TreeviewAdmin {   
    2     public static function ReturnHTML($id, $drag_drop=false, $tpl_tag=null, $args=array()) {
    3         ob_start(); self::RenderHTML($id, $drag_drop, $tpl_tag, $args); return ob_get_clean();
    4     }
    5     public static function RenderHTML($id, $drag_drop=false, $tpl_tag=null, $args=array())
    6     {       
    7         $jss = md5($id);
    8         ?>
    9 <script type="text/javascript">
    10 //<![CDATA[
    11 var wpfb_fbDOMModTimeout<?php echo $jss ?> = -1;
    12 
    13 <?php if($drag_drop) { ?>
    14 function wpfb_dtContains(dt,t) {
    15     if('undefined' !== typeof dt.types.indexOf) return dt.types.indexOf(t) !== -1;
    16     if('undefined' !== typeof dt.types.contains) return dt.types.contains(t);
    17     for(var s in dt.types) {
    18         if(s === t) return true;
    19     }
    20     return false;
     1<?php
     2
     3class WPFB_TreeviewAdmin {
     4
     5    public static function ReturnHTML($id, $drag_drop = false, $tpl_tag = null, $args = array()) {
     6        ob_start();
     7        self::RenderHTML($id, $drag_drop, $tpl_tag, $args);
     8        return ob_get_clean();
     9    }
     10
     11    public static function RenderHTML($id, $drag_drop = false, $tpl_tag = null, $args = array()) {
     12        $jss = md5($id);
     13        ?>
     14        <script type="text/javascript">
     15        //<![CDATA[
     16            var wpfb_fbDOMModTimeout<?php echo $jss ?> = -1;
     17
     18        <?php if ($drag_drop) { ?>
     19                function wpfb_dtContains(dt, t) {
     20                    if ('undefined' !== typeof dt.types.indexOf)
     21                        return dt.types.indexOf(t) !== -1;
     22                    if ('undefined' !== typeof dt.types.contains)
     23                        return dt.types.contains(t);
     24                    for (var s in dt.types) {
     25                        if (s === t)
     26                            return true;
     27                    }
     28                    return false;
     29                }
     30        <?php } ?>
     31
     32            wpfb_tvaUseDataText = false;
     33
     34            function wpfb_fbDOMModHandle<?php echo $jss ?>() {
     35                wpfb_fbDOMModTimeout<?php echo $jss ?> = -1;
     36
     37        <?php if ($drag_drop) { ?>
     38                    jQuery("#<?php echo $id ?> li:not([draggable]):not([id$='-0'])")
     39                            .attr('draggable', 'true')
     40                            .bind('dragstart', function (e) {
     41                                var li = jQuery(e.currentTarget), t = 'file', id = wpfb_fileBrowserTargetId(e, t) || ((t = 'cat') && wpfb_fileBrowserTargetId(e, t));
     42                                if (id > 0) {
     43                                    var dt = e.originalEvent.dataTransfer;
     44                                    dt.effectAllowed = (t === 'cat') ? 'move' : 'linkMove';
     45                                    dt.clearData();
     46                                    try {
     47                                        dt.setData("application/x-wpfilebase-item", t + "-" + id);
     48                                        dt.setData("application/x-wpfilebase-" + t + "-" + id, '' + id);
     49                                    } catch (e) { // on IE, only text/URL data format is allowed
     50                                        dt.setData("Text", "application/x-wpfilebase-item=" + t + "-" + id);
     51                                        wpfb_tvaUseDataText = true;
     52                                    }
     53                                    try {
     54                                        dt.setDragImage(li.find('img')[0], 10, 10);
     55                                    } catch (e) {
     56                                    }
     57                                }
     58                            }).bind('dragover', function (e) {
     59                        var id = wpfb_fileBrowserTargetId(e, 'cat'), dt = e.originalEvent.dataTransfer;
     60                        var hasFiles = wpfb_dtContains(dt, "Files");
     61                        var hasWpfbItem = wpfb_dtContains(dt, "application/x-wpfilebase-item") || (wpfb_tvaUseDataText && wpfb_dtContains(dt, "Text"));
     62                        if (!hasFiles && !hasWpfbItem)
     63                            return true;
     64
     65                        var ok = hasFiles || (id > 0 && !wpfb_dtContains(dt, "application/x-wpfilebase-cat-" + id));
     66                        var idp = wpfb_getFileBrowserIDP('<?php echo $id ?>');
     67                        var cat_id = wpfb_fileBrowserTargetId(e, 'cat'), cur_id = wpfb_fbDragCat<?php echo $jss ?>;
     68                        if (cur_id !== cat_id && cat_id > 0) {
     69                            jQuery('#' + idp + 'cat-' + cur_id).css({backgroundColor: ''});
     70                            if (ok)
     71                                jQuery('#' + idp + 'cat-' + id).css({backgroundColor: 'yellow'});
     72                            wpfb_fbDragCat<?php echo $jss ?> = ok ? cat_id : 0;
     73                        }
     74
     75                        if (hasFiles)
     76                            return true;
     77
     78                        if (hasWpfbItem)
     79                            e.stopPropagation();
     80
     81                        if (hasWpfbItem && ok) { // make dropk OK effect
     82                            e.preventDefault();
     83                            e.originalEvent.dataTransfer.dropEffect = 'move';
     84                        }
     85                    }).bind('dragleave', function (e) {
     86                        jQuery(e.currentTarget).css({backgroundColor: ''});
     87                        wpfb_fbDragCat<?php echo $jss ?> = 0;
     88                    }).bind('drop', function (e) {
     89                        var li = jQuery(e.currentTarget), id = wpfb_fileBrowserTargetId(e, 'cat'), dt = e.originalEvent.dataTransfer;
     90                        if (!wpfb_dtContains(dt, "application/x-wpfilebase-item") && !(wpfb_tvaUseDataText && wpfb_dtContains(dt, "Text")))
     91                            return true;
     92
     93                        e.stopPropagation();
     94
     95                        var idp = wpfb_getFileBrowserIDP('<?php echo $id ?>');
     96
     97                        var tid = wpfb_tvaUseDataText ? dt.getData("Text").substr("application/x-wpfilebase-item=".length).split('-') : dt.getData("application/x-wpfilebase-item").split('-');
     98                        if (!tid || tid.length !== 2)
     99                            return false;
     100
     101                        jQuery('#' + idp + 'cat-' + id).css({backgroundColor: '', cursor: 'wait'});
     102                        wpfb_fbDragCat<?php echo $jss ?> = 0;
     103
     104                        jQuery.ajax({url: wpfbConf.ajurl, type: "POST", dataType: "json",
     105                            data: {wpfb_action: "change-category", new_cat_id: id, id: tid[1], type: tid[0]},
     106                            success: (function (data) {
     107                                if (!data.error) {
     108                                    var dLi = jQuery('#' + idp + tid.join('-')); // the dragged
     109                                    var tUl = jQuery('#' + idp + 'cat-' + id).children('ul').first();
     110                                    if (li.hasClass('expandable')) {
     111                                        dLi.remove();
     112                                        jQuery('.hitarea', li).click();
     113                                    } else if (tUl.length) {
     114                                        dLi.appendTo(tUl);
     115                                    } else {
     116                                        dLi.remove();
     117                                    }
     118            <?php if (!empty($args['onCategoryChanged'])) echo $args['onCategoryChanged'] . '(tid, id);'; ?>
     119                                } else {
     120                                    alert(data.error);
     121                                }
     122                            }),
     123                            complete: (function () {
     124                                jQuery('#' + idp + 'cat-' + id).css({cursor: ''});
     125                            })
     126                        });
     127                    });
     128        <?php } /* drag_drop */ ?>
     129                jQuery("#<?php echo $id ?> a.add-file:not(.file-input)").each(function (i, el) {
     130                    var fileInput = new moxie.file.FileInput({
     131                        multiple: true,
     132                        //container: '<?php echo $id ?>',
     133                        browse_button: el
     134                    });
     135
     136                    jQuery(el).addClass('file-input');
     137
     138                    fileInput.onchange = function (event) {
     139                        var up = jQuery("#<?php echo $id ?>").data('uploader');
     140                        var cat_id = wpfb_fileBrowserTargetId(jQuery(el).parent(), 'cat');
     141                        up.settings.multipart_params["btn_cat_id"] = cat_id;
     142                        up.addFile(fileInput.files);
     143                    };
     144                    fileInput.init();
     145                });
     146            }
     147
     148            jQuery(document).ready(function () {
     149                wpfb_fbDragCat<?php echo $jss ?> = 0;
     150                jQuery("#<?php echo $id ?>")
     151                        .bind("DOMSubtreeModified", function (e) {
     152                            if (wpfb_fbDOMModTimeout<?php echo $jss ?> >= 0)
     153                                window.clearTimeout(wpfb_fbDOMModTimeout<?php echo $jss ?>);
     154                            wpfb_fbDOMModTimeout<?php echo $jss ?> = window.setTimeout(wpfb_fbDOMModHandle<?php echo $jss ?>, 100);
     155                        })
     156        <?php if ($drag_drop) { ?>
     157                    .bind('dragleave', function (e) {
     158                        var idp = wpfb_getFileBrowserIDP('<?php echo $id ?>');
     159                        jQuery('#' + idp + 'cat-' + wpfb_fbDragCat<?php echo $jss ?>).css({backgroundColor: ''});
     160                        wpfb_fbDragCat<?php echo $jss ?> = 0;
     161                    })
     162                            .before('<' + 'div class="wpfb-drag-drop-hint">+ DRAG &amp; DROP enabled<' + '/div>');
     163        <?php } /* drag_drop */ ?>
     164                ;
     165
     166                wpfb_fbDOMModHandle<?php echo $jss ?>();
     167            });
     168
     169            var callbacks<?php echo $jss ?> = {
     170                filesQueued: function (up, files) {
     171                    var cat_id = wpfb_fbDragCat<?php echo $jss ?>;
     172                    if (up.settings.multipart_params["btn_cat_id"]) {
     173                        cat_id = up.settings.multipart_params["btn_cat_id"];
     174                        up.settings.multipart_params["btn_cat_id"] = null;
     175                    }
     176
     177                    up.settings.multipart_params["cat_id"] = cat_id; // actually presets is used (see below)!
     178                    up.settings.multipart_params["tpl_tag"] = '<?php echo $tpl_tag; ?>';
     179
     180        <?php if (!empty($args['uploadParamsFilter'])) echo 'up.settings.multipart_params = ' . $args['uploadParamsFilter'] . '(up.settings.multipart_params, files);'; ?>
     181
     182                    cat_id = up.settings.multipart_params["cat_id"];
     183                    up.settings.multipart_params["presets"] = (up.settings.multipart_params["presets"] ? '&' : '') + "file_category=" + cat_id;
     184
     185                    var idp = wpfb_getFileBrowserIDP('<?php echo $id ?>');
     186                    var li = jQuery('#' + idp + 'cat-' + cat_id);
     187                    if (li.hasClass('expandable'))
     188                        jQuery('.hitarea', li).click();
     189
     190                    jQuery('#' + idp + 'cat-' + cat_id).css({backgroundColor: ''});
     191                    wpfb_fbDragCat<?php echo $jss ?> = 0;
     192                },
     193                fileQueued: function (up, file) {
     194                    var idp = wpfb_getFileBrowserIDP('<?php echo $id ?>');
     195                    var cat_id = up.settings.multipart_params["cat_id"];
     196                    var el = (cat_id === 0) ? jQuery('#<?php echo $id ?>') : jQuery('#' + idp + 'cat-' + cat_id).children('ul').first();
     197                    if (el.length)
     198                        el.after(
     199                                '<div id="' + file.dom_id + '" class="wpfb-treeview-upload">' +
     200                                '<' + 'img src="<?php echo site_url(WPINC . '/images/crystal/default.png'); ?>" alt="Loading..." style="height:1.2em;margin-right:0.3em;" /' + '>' +
     201                                '<' + 'span class="filename">' + file.name + '<' + '/span><' + 'span class="error"><' + '/span> ' +
     202                                '<' + 'div class="loading" style="background-image:url(<?php echo admin_url('images/loading.gif'); ?>);width:1.2em;height:1.2em;background-size:contain;display:inline-block;vertical-align:sub;"><' + '/div>' +
     203                                '<' + 'span class="percent">0%<' + '/span>' +
     204                                '<' + '/div>');
     205
     206        <?php if (!empty($args['onFileQueued'])) echo $args['onFileQueued'] . '(file, up.settings.multipart_params);'; ?>
     207                },
     208                success: function (file, serverData) {
     209                    var item = jQuery('#' + file.dom_id);
     210                    if (serverData.tpl) {
     211                        item.html(serverData.tpl);
     212                        var idp = wpfb_getFileBrowserIDP('<?php echo $id ?>');
     213                        item.attr('id', idp + 'file-' + serverData.file_id);
     214                        item.append('<' + 'span class="ok"><?php _e('Upload OK!', 'wp-filebase') ?><' + '/span>');
     215                    } else {
     216                        var url = serverData.file_cur_user_can_edit ? serverData.file_edit_url : serverData.file_download_url;
     217                        jQuery('.filename', item).html('<' + 'a href="' + url + '" target="_blank">' + serverData.file_display_name + '<' + '/a>');
     218                        jQuery('img', item).attr('src', serverData.file_thumbnail_url);
     219                        jQuery('.loading,.percent', item).hide();
     220                    }
     221
     222        <?php if (!empty($args['onSuccess'])) echo $args['onSuccess'] . '(file,serverData);'; ?>
     223                }
     224            };
     225        //]]>
     226        </script>
     227        <?php
     228        wpfb_loadclass('PLUploader');
     229        $uploader = new WPFB_PLUploader();
     230        $cb_prefix = 'callbacks' . $jss . '.';
     231        $uploader->js_files_queued = $cb_prefix . 'filesQueued';
     232        $uploader->js_file_queued = $cb_prefix . 'fileQueued';
     233        $uploader->js_upload_success = $cb_prefix . 'success';
     234        $uploader->post_params['file_add_now'] = true;
     235        $uploader->Init($id);
     236    }
     237
    21238}
    22 <?php } ?>
    23 
    24 wpfb_tvaUseDataText = false;
    25 
    26 function wpfb_fbDOMModHandle<?php echo $jss ?>() {
    27     wpfb_fbDOMModTimeout<?php echo $jss ?> = -1;
    28    
    29 <?php if($drag_drop) { ?>
    30     jQuery("#<?php echo $id ?> li:not([draggable]):not([id$='-0'])")
    31         .attr('draggable','true')
    32         .bind('dragstart', function(e) {
    33             var li = jQuery(e.currentTarget), t = 'file', id = wpfb_fileBrowserTargetId(e,t)||((t='cat')&&wpfb_fileBrowserTargetId(e,t));
    34             if(id > 0) {
    35                 var dt = e.originalEvent.dataTransfer;
    36                 dt.effectAllowed = (t==='cat')?'move':'linkMove';
    37                 dt.clearData();
    38                 try {
    39                     dt.setData("application/x-wpfilebase-item", t+"-"+id);
    40                     dt.setData("application/x-wpfilebase-"+t+"-"+id, ''+id);
    41                 } catch(e) { // on IE, only text/URL data format is allowed
    42                     dt.setData("Text", "application/x-wpfilebase-item="+t+"-"+id);
    43                     wpfb_tvaUseDataText = true;
    44                 }
    45                 try { dt.setDragImage(li.find('img')[0],10,10); }
    46                 catch(e) {}
    47             }
    48         }).bind('dragover', function(e){
    49             var id = wpfb_fileBrowserTargetId(e,'cat'), dt = e.originalEvent.dataTransfer;
    50             var hasFiles = wpfb_dtContains(dt,"Files");
    51             var hasWpfbItem = wpfb_dtContains(dt,"application/x-wpfilebase-item") || (wpfb_tvaUseDataText && wpfb_dtContains(dt,"Text"));
    52             if(!hasFiles && !hasWpfbItem)
    53                 return true;
    54            
    55             var ok = hasFiles || (id > 0 && !wpfb_dtContains(dt,"application/x-wpfilebase-cat-"+id));
    56             var idp = wpfb_getFileBrowserIDP('<?php echo $id ?>');
    57             var cat_id = wpfb_fileBrowserTargetId(e,'cat'), cur_id = wpfb_fbDragCat<?php echo $jss ?>;
    58             if(cur_id !== cat_id && cat_id > 0) {           
    59                 jQuery('#'+idp+'cat-'+cur_id).css({backgroundColor: ''});
    60                 if(ok) jQuery('#'+idp+'cat-'+id).css({backgroundColor: 'yellow'});
    61                 wpfb_fbDragCat<?php echo $jss ?> = ok?cat_id:0;
    62             }
    63            
    64             if(hasFiles)
    65                 return true;
    66            
    67             if(hasWpfbItem)
    68                 e.stopPropagation();
    69            
    70             if(hasWpfbItem && ok) { // make dropk OK effect
    71                 e.preventDefault();
    72                 e.originalEvent.dataTransfer.dropEffect = 'move';
    73             }
    74         }).bind('dragleave', function(e){
    75             jQuery(e.currentTarget).css({backgroundColor: ''});
    76             wpfb_fbDragCat<?php echo $jss ?> = 0;           
    77         }).bind('drop', function(e){       
    78             var li = jQuery(e.currentTarget), id = wpfb_fileBrowserTargetId(e,'cat'), dt = e.originalEvent.dataTransfer;
    79             if(!wpfb_dtContains(dt,"application/x-wpfilebase-item") && !(wpfb_tvaUseDataText && wpfb_dtContains(dt,"Text")))
    80                 return true;
    81            
    82             e.stopPropagation();
    83            
    84             var idp = wpfb_getFileBrowserIDP('<?php echo $id ?>');
    85            
    86             var tid = wpfb_tvaUseDataText ? dt.getData("Text").substr("application/x-wpfilebase-item=".length).split('-') : dt.getData("application/x-wpfilebase-item").split('-');     
    87             if(!tid || tid.length !== 2)
    88                 return false;
    89            
    90             jQuery('#'+idp+'cat-'+id).css({backgroundColor: '', cursor:'wait'});
    91             wpfb_fbDragCat<?php echo $jss ?> = 0;
    92            
    93             jQuery.ajax({url: wpfbConf.ajurl, type: "POST", dataType: "json",
    94                 data: {action:"change-category",new_cat_id:id,id:tid[1],type:tid[0]},               
    95                 success: (function(data){
    96                     if(!data.error) {
    97                         var dLi = jQuery('#'+idp+tid.join('-')); // the dragged
    98                         var tUl = jQuery('#'+idp+'cat-'+id).children('ul').first();
    99                         if(li.hasClass('expandable')) {
    100                             dLi.remove();
    101                             jQuery('.hitarea',li).click();
    102                         } else if(tUl.length) {
    103                             dLi.appendTo(tUl);
    104                         } else {
    105                             dLi.remove();
    106                         }
    107                         <?php if(!empty($args['onCategoryChanged'])) echo $args['onCategoryChanged'].'(tid, id);'; ?>
    108                     } else {
    109                         alert(data.error);
    110                     }
    111                 }),
    112                 complete: (function() { jQuery('#'+idp+'cat-'+id).css({cursor:''}); })
    113             });         
    114         });
    115 <?php } /* drag_drop */ ?>
    116     jQuery("#<?php echo $id ?> a.add-file:not(.file-input)").each(function(i,el) { 
    117         var fileInput = new moxie.file.FileInput({
    118             multiple: true,
    119             //container: '<?php echo $id ?>',
    120             browse_button: el
    121         });
    122        
    123         jQuery(el).addClass('file-input');
    124        
    125         fileInput.onchange = function( event ) {
    126             var up = jQuery("#<?php echo $id ?>").data('uploader');
    127             var cat_id = wpfb_fileBrowserTargetId(jQuery(el).parent(),'cat');
    128             up.settings.multipart_params["btn_cat_id"] = cat_id;
    129             up.addFile( fileInput.files );
    130         };
    131         fileInput.init();
    132     });
    133 }
    134 
    135 jQuery(document).ready(function(){ 
    136     wpfb_fbDragCat<?php echo $jss ?> = 0;
    137     jQuery("#<?php echo $id ?>")
    138         .bind("DOMSubtreeModified", function(e) {
    139             if(wpfb_fbDOMModTimeout<?php echo $jss ?> >= 0)
    140                 window.clearTimeout(wpfb_fbDOMModTimeout<?php echo $jss ?>)
    141             wpfb_fbDOMModTimeout<?php echo $jss ?> = window.setTimeout(wpfb_fbDOMModHandle<?php echo $jss ?>,100);     
    142         })
    143 <?php if($drag_drop) { ?>
    144         .bind('dragleave', function(e){
    145             var idp = wpfb_getFileBrowserIDP('<?php echo $id ?>');
    146             jQuery('#'+idp+'cat-'+wpfb_fbDragCat<?php echo $jss ?>).css({backgroundColor: ''});
    147             wpfb_fbDragCat<?php echo $jss ?> = 0;
    148         })
    149         .before('<div class="wpfb-drag-drop-hint">+ DRAG &amp; DROP enabled</div>')     
    150 <?php } /* drag_drop */ ?>
    151     ;
    152        
    153         wpfb_fbDOMModHandle<?php echo $jss ?>();
    154 });
    155 
    156 var callbacks<?php echo $jss ?> = {
    157     filesQueued: function(up, files)    {
    158         var cat_id = wpfb_fbDragCat<?php echo $jss ?>;     
    159         if(up.settings.multipart_params["btn_cat_id"]) {
    160             cat_id = up.settings.multipart_params["btn_cat_id"];
    161             up.settings.multipart_params["btn_cat_id"] = null;
    162         }
    163        
    164         up.settings.multipart_params["cat_id"] = cat_id; // actually presets is used (see below)!
    165         up.settings.multipart_params["tpl_tag"] = '<?php echo $tpl_tag; ?>';
    166        
    167         <?php if(!empty($args['uploadParamsFilter'])) echo 'up.settings.multipart_params = '.$args['uploadParamsFilter'].'(up.settings.multipart_params, files);'; ?>
    168        
    169         cat_id = up.settings.multipart_params["cat_id"];
    170         up.settings.multipart_params["presets"] = (up.settings.multipart_params["presets"] ? '&' : '') + "file_category="+cat_id;
    171        
    172         var idp = wpfb_getFileBrowserIDP('<?php echo $id ?>');
    173         var li = jQuery('#'+idp+'cat-'+cat_id);
    174         if(li.hasClass('expandable'))
    175             jQuery('.hitarea',li).click();
    176        
    177         jQuery('#'+idp+'cat-'+cat_id).css({backgroundColor: ''});
    178         wpfb_fbDragCat<?php echo $jss ?> = 0;
    179     },
    180     fileQueued: function(up, file) {
    181         var idp = wpfb_getFileBrowserIDP('<?php echo $id ?>');
    182         var cat_id = up.settings.multipart_params["cat_id"];
    183         var el = (cat_id===0) ? jQuery('#<?php echo $id ?>') : jQuery('#'+idp+'cat-'+cat_id).children('ul').first();
    184         if(el.length) el.after(
    185             '<div id="'+file.dom_id+'" class="wpfb-treeview-upload">'+
    186                 '<img src="<?php echo site_url(WPINC . '/images/crystal/default.png'); ?>" alt="Loading..." style="height:1.2em;margin-right:0.3em;"/>'+
    187                 '<span class="filename">'+file.name+'</span><span class="error"></span> '+
    188                 '<div class="loading" style="background-image:url(<?php echo admin_url('images/loading.gif');?>);width:1.2em;height:1.2em;background-size:contain;display:inline-block;vertical-align:sub;"></div>'+
    189                 '<span class="percent">0%</span>'+
    190             '</div>');
    191  
    192         <?php if(!empty($args['onFileQueued'])) echo $args['onFileQueued'].'(file, up.settings.multipart_params);'; ?>
    193     },
    194     success: function(file, serverData) {
    195         var item = jQuery('#'+file.dom_id);
    196         if(serverData.tpl) {
    197             item.html(serverData.tpl);
    198             var idp = wpfb_getFileBrowserIDP('<?php echo $id ?>');
    199             item.attr('id', idp+'file-'+serverData.file_id);
    200         } else {
    201             var url = serverData.file_cur_user_can_edit ? serverData.file_edit_url : serverData.file_download_url;
    202             jQuery('.filename', item).html('<a href="'+url+'" target="_blank">'+serverData.file_display_name+'</a>');
    203             jQuery('img', item).attr('src', serverData.file_thumbnail_url);
    204             jQuery('.loading,.percent',item).hide();
    205         }
    206        
    207         <?php if(!empty($args['onSuccess'])) echo $args['onSuccess'].'(file,serverData);'; ?>
    208     }
    209 };
    210 //]]>
    211 </script>
    212 <?php       
    213         wpfb_loadclass('PLUploader');
    214         $uploader = new WPFB_PLUploader(); 
    215         $cb_prefix = 'callbacks'.$jss.'.';
    216         $uploader->js_files_queued = $cb_prefix.'filesQueued';
    217         $uploader->js_file_queued = $cb_prefix.'fileQueued';
    218         $uploader->js_upload_success =  $cb_prefix.'success';           
    219         $uploader->post_params['file_add_now'] = true;         
    220         $uploader->Init($id);
    221     }
    222 }
  • wp-filebase/trunk/css/live-admin.css

    r1254671 r1303067  
    7575    margin-left: 15px;
    7676}
     77
     78.wpfb-treeview-upload span.ok {
     79    background: green;
     80    font-size: 0.6em;
     81    display: inline-block;
     82    margin-left: 0.5em;
     83    vertical-align: text-top;
     84    border-radius: 1em;
     85    padding: 0.1em 0.6em;
     86    color: white;
     87}
  • wp-filebase/trunk/extras/ckeditor/plugin.js

    r365225 r1303067  
    44For licensing, see LICENSE.html or http://ckeditor.com/license
    55*/
     6
    67
    78CKEDITOR.plugins.add( 'wpfilebase',
     
    3132                                        label : 'WP-Filebase',
    3233                                        style : 'width:680px; height:400px;',
    33                                         html : '<iframe src="'+me.path+'../../editor_plugin.php?post_id='+postId+'" frameborder="0" name="iframeWPFilebase" id="iframeWPFilebase" allowtransparency="1" style="width:100%;height:400px;margin:0;padding:0;"></iframe>'
     34                                        html : '<iframe src="'+ajaxurl.replace("admin-ajax.php","?wpfilebase-screen=editor-plugin")+'&post_id='+postId+'" frameborder="0" name="iframeWPFilebase" id="iframeWPFilebase" allowtransparency="1" style="width:100%;height:400px;margin:0;padding:0;"></iframe>'
    3435                                    }
    3536                                ]
  • wp-filebase/trunk/extras/phpthumb.functions.php

    r155458 r1303067  
    11<?php
    22//////////////////////////////////////////////////////////////
    3 ///  phpThumb() by James Heinrich <info@silisoftware.com>   //
    4 //        available at http://phpthumb.sourceforge.net     ///
     3//   phpThumb() by James Heinrich <info@silisoftware.com>   //
     4//        available at http://phpthumb.sourceforge.net      //
     5//         and/or https://github.com/JamesHeinrich/phpThumb //
    56//////////////////////////////////////////////////////////////
    67///                                                         //
     
    1112class phpthumb_functions {
    1213
    13     function user_function_exists($functionname) {
     14    static function user_function_exists($functionname) {
    1415        if (function_exists('get_defined_functions')) {
    1516            static $get_defined_functions = array();
     
    2324
    2425
    25     function builtin_function_exists($functionname) {
     26    static function builtin_function_exists($functionname) {
    2627        if (function_exists('get_defined_functions')) {
    2728            static $get_defined_functions = array();
     
    3536
    3637
    37     function version_compare_replacement_sub($version1, $version2, $operator='') {
     38    static function version_compare_replacement_sub($version1, $version2, $operator='') {
    3839        // If you specify the third optional operator argument, you can test for a particular relationship.
    3940        // The possible operators are: <, lt, <=, le, >, gt, >=, ge, ==, =, eq, !=, <>, ne respectively.
    4041        // Using this argument, the function will return 1 if the relationship is the one specified by the operator, 0 otherwise.
    4142
    42         // If a part contains special version strings these are handled in the following order: dev < (alpha = a) < (beta = b) < RC < pl
     43        // If a part contains special version strings these are handled in the following order:
     44        // (any string not found in this list) < (dev) < (alpha = a) < (beta = b) < (RC = rc) < (#) < (pl = p)
    4345        static $versiontype_lookup = array();
    4446        if (empty($versiontype_lookup)) {
     
    4951            $versiontype_lookup['beta']  = 10003;
    5052            $versiontype_lookup['RC']    = 10004;
    51             $versiontype_lookup['pl']    = 10005;
    52         }
    53         if (isset($versiontype_lookup[$version1])) {
    54             $version1 = $versiontype_lookup[$version1];
    55         }
    56         if (isset($versiontype_lookup[$version2])) {
    57             $version2 = $versiontype_lookup[$version2];
    58         }
     53            $versiontype_lookup['rc']    = 10004;
     54            $versiontype_lookup['#']     = 10005;
     55            $versiontype_lookup['pl']    = 10006;
     56            $versiontype_lookup['p']     = 10006;
     57        }
     58        $version1 = (isset($versiontype_lookup[$version1]) ? $versiontype_lookup[$version1] : $version1);
     59        $version2 = (isset($versiontype_lookup[$version2]) ? $versiontype_lookup[$version2] : $version2);
    5960
    6061        switch ($operator) {
     
    9596
    9697
    97     function version_compare_replacement($version1, $version2, $operator='') {
     98    static function version_compare_replacement($version1, $version2, $operator='') {
    9899        if (function_exists('version_compare')) {
    99100            // built into PHP v4.1.0+
     
    107108        // and also inserts dots . before and after any non number so that for example '4.3.2RC1' becomes '4.3.2.RC.1'.
    108109        // Then it splits the results like if you were using explode('.',$ver). Then it compares the parts starting from left to right.
    109         $version1 = eregi_replace('([0-9]+)([A-Z]+)([0-9]+)', '\\1.\\2.\\3', $version1);
    110         $version2 = eregi_replace('([0-9]+)([A-Z]+)([0-9]+)', '\\1.\\2.\\3', $version2);
     110        $version1 = preg_replace('#([0-9]+)([A-Z]+)([0-9]+)#i', "$1.$2.$3", $version1);
     111        $version2 = preg_replace('#([0-9]+)([A-Z]+)([0-9]+)#i', "$1.$2.$3", $version2);
    111112
    112113        $parts1 = explode('.', $version1);
     
    122123    }
    123124
    124 
    125     function phpinfo_array() {
     125    static function escapeshellarg_replacement($arg) {
     126        if (function_exists('escapeshellarg') && !phpthumb_functions::FunctionIsDisabled('escapeshellarg')) {
     127            return escapeshellarg($arg);
     128        }
     129        return '\''.str_replace('\'', '\\\'', $arg).'\'';
     130    }
     131
     132    static function phpinfo_array() {
    126133        static $phpinfo_array = array();
    127134        if (empty($phpinfo_array)) {
     
    136143
    137144
    138     function exif_info() {
     145    static function exif_info() {
    139146        static $exif_info = array();
    140147        if (empty($exif_info)) {
     
    162169
    163170
    164     function ImageTypeToMIMEtype($imagetype) {
     171    static function ImageTypeToMIMEtype($imagetype) {
    165172        if (function_exists('image_type_to_mime_type') && ($imagetype >= 1) && ($imagetype <= 16)) {
    166173            // PHP v4.3.0+
     
    197204
    198205
    199     function TranslateWHbyAngle($width, $height, $angle) {
     206    static function TranslateWHbyAngle($width, $height, $angle) {
    200207        if (($angle % 180) == 0) {
    201208            return array($width, $height);
     
    206213    }
    207214
    208     function HexCharDisplay($string) {
     215    static function HexCharDisplay($string) {
    209216        $len = strlen($string);
    210217        $output = '';
     
    216223
    217224
    218     function IsHexColor($HexColorString) {
    219         return eregi('^[0-9A-F]{6}$', $HexColorString);
    220     }
    221 
    222 
    223     function ImageColorAllocateAlphaSafe(&$gdimg_hexcolorallocate, $R, $G, $B, $alpha=false) {
     225    static function IsHexColor($HexColorString) {
     226        return preg_match('#^[0-9A-F]{6}$#i', $HexColorString);
     227    }
     228
     229
     230    static function ImageColorAllocateAlphaSafe(&$gdimg_hexcolorallocate, $R, $G, $B, $alpha=false) {
    224231        if (phpthumb_functions::version_compare_replacement(phpversion(), '4.3.2', '>=') && ($alpha !== false)) {
    225232            return ImageColorAllocateAlpha($gdimg_hexcolorallocate, $R, $G, $B, intval($alpha));
     
    229236    }
    230237
    231     function ImageHexColorAllocate(&$gdimg_hexcolorallocate, $HexColorString, $dieOnInvalid=false, $alpha=false) {
     238    static function ImageHexColorAllocate(&$gdimg_hexcolorallocate, $HexColorString, $dieOnInvalid=false, $alpha=false) {
    232239        if (!is_resource($gdimg_hexcolorallocate)) {
    233240            die('$gdimg_hexcolorallocate is not a GD resource in ImageHexColorAllocate()');
     
    246253
    247254
    248     function HexColorXOR($hexcolor) {
     255    static function HexColorXOR($hexcolor) {
    249256        return strtoupper(str_pad(dechex(~hexdec($hexcolor) & 0xFFFFFF), 6, '0', STR_PAD_LEFT));
    250257    }
    251258
    252259
    253     function GetPixelColor(&$img, $x, $y) {
     260    static function GetPixelColor(&$img, $x, $y) {
    254261        if (!is_resource($img)) {
    255262            return false;
     
    259266
    260267
    261     function PixelColorDifferencePercent($currentPixel, $targetPixel) {
     268    static function PixelColorDifferencePercent($currentPixel, $targetPixel) {
    262269        $diff = 0;
    263270        foreach ($targetPixel as $channel => $currentvalue) {
     
    267274    }
    268275
    269     function GrayscaleValue($r, $g, $b) {
     276    static function GrayscaleValue($r, $g, $b) {
    270277        return round(($r * 0.30) + ($g * 0.59) + ($b * 0.11));
    271278    }
    272279
    273280
    274     function GrayscalePixel($OriginalPixel) {
     281    static function GrayscalePixel($OriginalPixel) {
    275282        $gray = phpthumb_functions::GrayscaleValue($OriginalPixel['red'], $OriginalPixel['green'], $OriginalPixel['blue']);
    276283        return array('red'=>$gray, 'green'=>$gray, 'blue'=>$gray);
     
    278285
    279286
    280     function GrayscalePixelRGB($rgb) {
     287    static function GrayscalePixelRGB($rgb) {
    281288        $r = ($rgb >> 16) & 0xFF;
    282289        $g = ($rgb >>  8) & 0xFF;
     
    286293
    287294
    288     function ScaleToFitInBox($width, $height, $maxwidth=null, $maxheight=null, $allow_enlarge=true, $allow_reduce=true) {
     295    static function ScaleToFitInBox($width, $height, $maxwidth=null, $maxheight=null, $allow_enlarge=true, $allow_reduce=true) {
    289296        $maxwidth  = (is_null($maxwidth)  ? $width  : $maxwidth);
    290297        $maxheight = (is_null($maxheight) ? $height : $maxheight);
     
    307314    }
    308315
    309     function ImageCopyResampleBicubic($dst_img, $src_img, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h) {
     316    static function ImageCopyResampleBicubic($dst_img, $src_img, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h) {
    310317        // ron at korving dot demon dot nl
    311318        // http://www.php.net/imagecopyresampled
     
    359366
    360367
    361     function ImageCreateFunction($x_size, $y_size) {
     368    static function ImageCreateFunction($x_size, $y_size) {
    362369        $ImageCreateFunction = 'ImageCreate';
    363370        if (phpthumb_functions::gd_version() >= 2.0) {
     
    374381
    375382
    376     function ImageCopyRespectAlpha(&$dst_im, &$src_im, $dst_x, $dst_y, $src_x, $src_y, $src_w, $src_h, $opacity_pct=100) {
     383    static function ImageCopyRespectAlpha(&$dst_im, &$src_im, $dst_x, $dst_y, $src_x, $src_y, $src_w, $src_h, $opacity_pct=100) {
    377384        $opacipct = $opacity_pct / 100;
    378385        for ($x = $src_x; $x < $src_w; $x++) {
     
    398405
    399406
    400     function ProportionalResize($old_width, $old_height, $new_width=false, $new_height=false) {
     407    static function ProportionalResize($old_width, $old_height, $new_width=false, $new_height=false) {
    401408        $old_aspect_ratio = $old_width / $old_height;
    402409        if (($new_width === false) && ($new_height === false)) {
     
    421428
    422429
    423     function FunctionIsDisabled($function) {
     430    static function FunctionIsDisabled($function) {
    424431        static $DisabledFunctions = null;
    425432        if (is_null($DisabledFunctions)) {
     
    441448
    442449
    443     function SafeExec($command) {
     450    static function SafeExec($command) {
    444451        static $AllowedExecFunctions = array();
    445452        if (empty($AllowedExecFunctions)) {
     
    482489
    483490
    484     function ApacheLookupURIarray($filename) {
     491    static function ApacheLookupURIarray($filename) {
    485492        // apache_lookup_uri() only works when PHP is installed as an Apache module.
    486493        if (php_sapi_name() == 'apache') {
     494            //$property_exists_exists = function_exists('property_exists');
    487495            $keys = array('status', 'the_request', 'status_line', 'method', 'content_type', 'handler', 'uri', 'filename', 'path_info', 'args', 'boundary', 'no_cache', 'no_local_copy', 'allowed', 'send_bodyct', 'bytes_sent', 'byterange', 'clength', 'unparsed_uri', 'mtime', 'request_time');
    488496            if ($apacheLookupURIobject = @apache_lookup_uri($filename)) {
     
    498506
    499507
    500     function gd_is_bundled() {
     508    static function gd_is_bundled() {
    501509        static $isbundled = null;
    502510        if (is_null($isbundled)) {
     
    508516
    509517
    510     function gd_version($fullstring=false) {
     518    static function gd_version($fullstring=false) {
    511519        static $cache_gd_version = array();
    512520        if (empty($cache_gd_version)) {
    513521            $gd_info = gd_info();
    514             if (eregi('bundled \((.+)\)$', $gd_info['GD Version'], $matches)) {
     522            if (preg_match('#bundled \((.+)\)$#i', $gd_info['GD Version'], $matches)) {
    515523                $cache_gd_version[1] = $gd_info['GD Version'];  // e.g. "bundled (2.0.15 compatible)"
    516524                $cache_gd_version[0] = (float) $matches[1];     // e.g. "2.0" (not "bundled (2.0.15 compatible)")
     
    524532
    525533
    526     function filesize_remote($remotefile, $timeout=10) {
     534    static function filesize_remote($remotefile, $timeout=10) {
    527535        $size = false;
    528536        $url = phpthumb_functions::ParseURLbetter($remotefile);
     
    534542            while (!feof($fp)) {
    535543                $headerline = fgets($fp, 4096);
    536                 if (eregi('^Content-Length: (.*)', $headerline, $matches)) {
     544                if (preg_match('#^Content-Length: (.*)#i', $headerline, $matches)) {
    537545                    $size = intval($matches[1]);
    538546                    break;
     
    545553
    546554
    547     function filedate_remote($remotefile, $timeout=10) {
     555    static function filedate_remote($remotefile, $timeout=10) {
    548556        $date = false;
    549557        $url = phpthumb_functions::ParseURLbetter($remotefile);
     
    555563            while (!feof($fp)) {
    556564                $headerline = fgets($fp, 4096);
    557                 if (eregi('^Last-Modified: (.*)', $headerline, $matches)) {
     565                if (preg_match('#^Last-Modified: (.*)#i', $headerline, $matches)) {
    558566                    $date = strtotime($matches[1]) - date('Z');
    559567                    break;
     
    566574
    567575
    568     function md5_file_safe($filename) {
     576    static function md5_file_safe($filename) {
    569577        // md5_file() doesn't exist in PHP < 4.2.0
    570578        if (function_exists('md5_file')) {
     
    584592
    585593
    586     function nonempty_min() {
     594    static function nonempty_min() {
    587595        $arg_list = func_get_args();
    588596        $acceptable = array();
     
    596604
    597605
    598     function LittleEndian2String($number, $minbytes=1) {
     606    static function LittleEndian2String($number, $minbytes=1) {
    599607        $intstring = '';
    600608        while ($number > 0) {
     
    605613    }
    606614
    607     function OneOfThese() {
     615    static function OneOfThese() {
    608616        // return the first useful (non-empty/non-zero/non-false) value from those passed
    609617        $arg_list = func_get_args();
     
    616624    }
    617625
    618     function CaseInsensitiveInArray($needle, $haystack) {
     626    static function CaseInsensitiveInArray($needle, $haystack) {
    619627        $needle = strtolower($needle);
    620628        foreach ($haystack as $key => $value) {
     
    628636    }
    629637
    630     function URLreadFsock($host, $file, &$errstr, $successonly=true, $port=80, $timeout=10) {
     638    static function URLreadFsock($host, $file, &$errstr, $successonly=true, $port=80, $timeout=10) {
    631639        if (!function_exists('fsockopen') || phpthumb_functions::FunctionIsDisabled('fsockopen')) {
    632640            $errstr = 'fsockopen() unavailable';
    633641            return false;
    634642        }
    635         if ($fp = @fsockopen($host, 80, $errno, $errstr, $timeout)) {
     643        //if ($fp = @fsockopen($host, $port, $errno, $errstr, $timeout)) {
     644        if ($fp = @fsockopen((($port == 443) ? 'ssl://' : '').$host, $port, $errno, $errstr, $timeout)) { // https://github.com/JamesHeinrich/phpThumb/issues/39
    636645            $out  = 'GET '.$file.' HTTP/1.0'."\r\n";
    637646            $out .= 'Host: '.$host."\r\n";
     
    650659                    $Data_body .= $line;
    651660                }
    652                 if (eregi('^HTTP/[\\.0-9]+ ([0-9]+) (.+)$', rtrim($line), $matches)) {
     661                if (preg_match('#^HTTP/[\\.0-9]+ ([0-9]+) (.+)$#i', rtrim($line), $matches)) {
    653662                    list($dummy, $errno, $errstr) = $matches;
    654663                    $errno = intval($errno);
    655                 } elseif (eregi('^Location: (.*)$', rtrim($line), $matches)) {
     664                } elseif (preg_match('#^Location: (.*)$#i', rtrim($line), $matches)) {
    656665                    $header_newlocation = $matches[1];
    657666                }
     
    679688    }
    680689
    681     function CleanUpURLencoding($url, $queryseperator='&') {
    682         if (!eregi('^http', $url)) {
     690    static function CleanUpURLencoding($url, $queryseperator='&') {
     691        if (!preg_match('#^http#i', $url)) {
    683692            return $url;
    684693        }
     
    696705        }
    697706
    698         $queries = explode($queryseperator, @$parse_url['query']);
     707        $queries = explode($queryseperator, (isset($parse_url['query']) ? $parse_url['query'] : ''));
    699708        $CleanQueries = array();
    700709        foreach ($queries as $key => $query) {
     
    711720        $cleaned_url .= (@$parse_url['username'] ? $parse_url['host'].(@$parse_url['password'] ? ':'.$parse_url['password'] : '').'@' : '');
    712721        $cleaned_url .= $parse_url['host'];
     722        $cleaned_url .= ((!empty($parse_url['port']) && ($parse_url['port'] != 80)) ? ':'.$parse_url['port'] : '');
    713723        $cleaned_url .= '/'.implode('/', $CleanPathElements);
    714724        $cleaned_url .= (@$CleanQueries ? '?'.implode($queryseperator, $CleanQueries) : '');
     
    716726    }
    717727
    718     function ParseURLbetter($url) {
     728    static function ParseURLbetter($url) {
    719729        $parsedURL = @parse_url($url);
    720730        if (!@$parsedURL['port']) {
     
    734744    }
    735745
    736     function SafeURLread($url, &$error, $timeout=10, $followredirects=true) {
     746    static function SafeURLread($url, &$error, $timeout=10, $followredirects=true) {
    737747        $error = '';
    738748
     
    743753            $tryagain = false;
    744754            $rawData = phpthumb_functions::URLreadFsock(@$parsed_url['host'], @$parsed_url['path'].'?'.@$parsed_url['query'], $errstr, true, (@$parsed_url['port'] ? @$parsed_url['port'] : 80), $timeout);
    745             if (eregi('302 [a-z ]+; Location\\: (http.*)', $errstr, $matches)) {
     755            if (preg_match('#302 [a-z ]+; Location\\: (http.*)#i', $errstr, $matches)) {
    746756                $matches[1] = trim(@$matches[1]);
    747757                if (!@$alreadyLookedAtURLs[$matches[1]]) {
     
    817827    }
    818828
    819     function EnsureDirectoryExists($dirname) {
     829    static function EnsureDirectoryExists($dirname) {
    820830        $directory_elements = explode(DIRECTORY_SEPARATOR, $dirname);
    821831        $startoffset = (!$directory_elements[0] ? 2 : 1);  // unix with leading "/" then start with 2nd element; Windows with leading "c:\" then start with 1st element
    822         $open_basedirs = split('[;:]', ini_get('open_basedir'));
     832        $open_basedirs = preg_split('#[;:]#', ini_get('open_basedir'));
    823833        foreach ($open_basedirs as $key => $open_basedir) {
    824             if (ereg('^'.preg_quote($open_basedir), $dirname) && (strlen($dirname) > strlen($open_basedir))) {
     834            if (preg_match('#^'.preg_quote($open_basedir).'#', $dirname) && (strlen($dirname) > strlen($open_basedir))) {
    825835                $startoffset = count(explode(DIRECTORY_SEPARATOR, $open_basedir));
    826836                break;
     
    850860
    851861
    852     function GetAllFilesInSubfolders($dirname) {
     862    static function GetAllFilesInSubfolders($dirname) {
    853863        $AllFiles = array();
    854864        $dirname = rtrim(realpath($dirname), '/\\');
     
    883893
    884894
    885     function SanitizeFilename($filename) {
    886         $filename = ereg_replace('[^'.preg_quote(' !#$%^()+,-.;<>=@[]_{}').'a-zA-Z0-9]', '_', $filename);
     895    static function SanitizeFilename($filename) {
     896        $filename = preg_replace('/[^'.preg_quote(' !#$%^()+,-.;<>=@[]_{}').'a-zA-Z0-9]/', '_', $filename);
    887897        if (phpthumb_functions::version_compare_replacement(phpversion(), '4.1.0', '>=')) {
    888898            $filename = trim($filename, '.');
    889899        }
    890900        return $filename;
     901    }
     902
     903    static function PasswordStrength($password) {
     904        $strength = 0;
     905        $strength += strlen(preg_replace('#[^a-z]#',       '', $password)) * 0.5; // lowercase characters are weak
     906        $strength += strlen(preg_replace('#[^A-Z]#',       '', $password)) * 0.8; // uppercase characters are somewhat better
     907        $strength += strlen(preg_replace('#[^0-9]#',       '', $password)) * 1.0; // numbers are somewhat better
     908        $strength += strlen(preg_replace('#[a-zA-Z0-9]#',  '', $password)) * 2.0; // other non-alphanumeric characters are best
     909        return $strength;
    891910    }
    892911
     
    9951014    // included in PHP v4.3.0+
    9961015    function file_get_contents($filename) {
    997         if (eregi('^(f|ht)tp\://', $filename)) {
     1016        if (preg_match('#^(f|ht)tp\://#i', $filename)) {
    9981017            return SafeURLread($filename, $error);
    9991018        }
  • wp-filebase/trunk/js/admin.js

    r1081173 r1303067  
     1function WPFB_PopupCenter(url, title, w, h) {
     2    // Fixes dual-screen position                         Most browsers      Firefox
     3    var dualScreenLeft = window.screenLeft != undefined ? window.screenLeft : screen.left;
     4    var dualScreenTop = window.screenTop != undefined ? window.screenTop : screen.top;
     5
     6    width = window.innerWidth ? window.innerWidth : document.documentElement.clientWidth ? document.documentElement.clientWidth : screen.width;
     7    height = window.innerHeight ? window.innerHeight : document.documentElement.clientHeight ? document.documentElement.clientHeight : screen.height;
     8
     9    var left = ((width / 2) - (w / 2)) + dualScreenLeft;
     10    var top = ((height / 2) - (h / 2)) + dualScreenTop;
     11    var newWindow = window.open(url, title, 'scrollbars=yes, menubar=no,location=no,resizable=no,status=no,toolbar=no, width=' + w + ', height=' + h + ', top=' + top + ', left=' + left);
     12
     13    // Puts focus on the newWindow
     14    if (window.focus) {
     15        newWindow.focus();
     16    }
     17   
     18    return newWindow;
     19}
     20
    121function WPFB_PostBrowser(inputId, titleId)
    222{
    323    var postId = document.getElementById(inputId).value;
    424    var pluginUrl = (typeof(wpfbConf.ajurl) == 'undefined') ? "../wp-content/plugins/wp-filebase/" : (wpfbConf.ajurl+"/../");
    5     var browserWindow = window.open(pluginUrl+"wpfb-postbrowser.php?post=" + postId + "&inp_id=" + inputId + "&tit_id=" + titleId, "PostBrowser", "width=300,height=400,menubar=no,location=no,resizable=no,status=no,toolbar=no,scrollbars=yes");
     25    var browserWindow = WPFB_PopupCenter(wpfbConf.ajurl+"&wpfb_action=postbrowser-main&post=" + postId + "&inp_id=" + inputId + "&tit_id=" + titleId, "PostBrowser", 300, 400);
    626    browserWindow.focus();
    727}
     
    93113                inp.prop('disabled', true).addClass('loading');
    94114                jQuery.ajax({url: wpfbConf.ajurl, type:"POST",dataType:'json',
    95                     data:{action:'new-cat', cat_name:cat_name, cat_parent:pid},
     115                    data:{wpfb_action:'new-cat', cat_name:cat_name, cat_parent:pid},
    96116                    success: (function(data){
    97117                        if(data.error) {
  • wp-filebase/trunk/js/common.js

    r1081173 r1303067  
    2020    try{// to get url by ajax request
    2121        // wpfbfid
    22         fi = jQuery.parseJSON(jQuery.ajax({url:wpfbConf.ajurl,data:{action:"fileinfo",url:uesc},async:false}).responseText);
     22        fi = jQuery.parseJSON(jQuery.ajax({url:wpfbConf.ajurl,data:{wpfb_action:"fileinfo",url:uesc},async:false}).responseText);
    2323        if(typeof(fi) == 'object' && fi.id > 0) {
    2424            wpfbFileInfos.push(fi);
     
    123123    theForm.find('*[name^="file_"]').prop('disabled',true).change(function(){
    124124        var formData = theForm.serialize().replace(/file_user_roles%5B%5D=.+?&/gi,''); // fix: remove user roles, serialization does not work properly!
    125         jQuery.ajax({url: wpfbConf.ajurl, type:"POST", data:{action:'set-user-setting',name:settingName,value: formData }});
     125        jQuery.ajax({url: wpfbConf.ajurl, type:"POST", data:{wpfb_action:'set-user-setting',name:settingName,value: formData }});
    126126    });
    127     jQuery.ajax({url: wpfbConf.ajurl, data:{action:'get-user-setting',name:settingName}, dataType:'json', success: (function(data){
     127    jQuery.ajax({url: wpfbConf.ajurl, data:{wpfb_action:'get-user-setting',name:settingName}, dataType:'json', success: (function(data){
    128128            theForm.find('*[name^="file_"]').prop('disabled', false);
    129129        if(data) theForm.deserialize(data);
  • wp-filebase/trunk/js/editor-plugin.js

    r1254671 r1303067  
    204204
    205205function getFilePath(id) {
    206     var fi = jQuery.parseJSON(jQuery.ajax({url:wpfbConf.ajurl, data: {action:"fileinfo","id":id} ,async:false}).responseText);
     206    var fi = jQuery.parseJSON(jQuery.ajax({url:wpfbConf.ajurl, data: {wpfb_action:"fileinfo","id":id} ,async:false}).responseText);
    207207    return (fi != null && fi.path != '') ? fi.path : '';   
    208208}
    209209
    210210function getCatPath(id) {
    211     var ci = jQuery.parseJSON(jQuery.ajax({url:wpfbConf.ajurl, data:{action:"catinfo","id":id},async:false}).responseText);
     211    var ci = jQuery.parseJSON(jQuery.ajax({url:wpfbConf.ajurl, data:{wpfb_action:"catinfo","id":id},async:false}).responseText);
    212212    return (ci != null && ci.path != '') ? ci.path : '';   
    213213};
     
    215215function getTreeViewModel(data) {
    216216    if(typeof data != 'object') data = {};
    217     data.action = "tree";
     217    data.wpfb_action = "tree";
    218218    return {url: wpfbAjax,
    219219        ajax:{data:data,type:"post"},
  • wp-filebase/trunk/js/live-admin.js

    r1113324 r1303067  
    2525            type: 'POST',
    2626            url: wpfbConf.ajurl,
    27             data: {action:'delete',file_id:fid},
     27            data: {wpfb_action:'delete',file_id:fid},
    2828            async: false,
    2929            success: (function(data){
     
    4646}
    4747
    48 function wpfb_manageAttachments(url,postId)
    49 {
    50     var browserWindow = window.open("../wp-content/plugins/wp-filebase/wpfb-postbrowser.php?post=" + postId + "&inp_id=" + inputId + "&tit_id=" + titleId, "PostBrowser", "width=300,height=400,menubar=no,location=no,resizable=no,status=no,toolbar=no");
    51     browserWindow.focus();
    52 }
    53 
    5448function wpfb_toggleContextMenu() {
    5549    wpfbConf.cm = !wpfbConf.cm;
    56     jQuery.ajax({url: wpfbConf.ajurl, data:'action=toggle-context-menu', async: false});
     50    jQuery.ajax({url: wpfbConf.ajurl, data:{wpfb_action: 'toggle-context-menu'}, async: false});
    5751    return true;
    5852}
     
    8478                var tv =  el.parents('.treeview').first(); var set = tv.data("settings");
    8579                jQuery.ajax({url: wpfbConf.ajurl, type:"POST",dataType:'json',
    86                     data:{action:'new-cat', cat_name:cat_name, cat_parent:pid, args:set.ajax.data, is_admin:(typeof(adminpage) !== 'undefined')?1:0},
     80                    data:{wpfb_action:'new-cat', cat_name:cat_name, cat_parent:pid, args:set.ajax.data, is_admin:(typeof(adminpage) !== 'undefined')?1:0},
    8781                    success: (function(data){
    8882                        if(data.error) {
  • wp-filebase/trunk/lib/wpfb_form_file.php

    r1254671 r1303067  
    136136        jQuery.ajax({
    137137            url: wpfbConf.ajurl,
    138             data: {action:"ftag_proposal","tag":lt},
     138            data: {wpfb_action:"tag_autocomplete","tag":lt}, // TODO test!
    139139            dataType: "json",
    140140            success: (function(data){
     
    217217                        <label for="file_upload"><?php _e('Choose File','wp-filebase') ?></label>
    218218                        <input type="file" name="file_upload" id="file_upload" /><br />
    219                         <?php printf(str_replace('%d%s','%s',__('Maximum upload file size: %d%s'/*def*/)), WPFB_Output::FormatFilesize(WPFB_Core::GetMaxUlSize())) ?> <b>&nbsp;&nbsp;<a href="#" onclick="alert(this.title); return false;" title="<?php printf(__('Ask your webhoster to increase this limit, it is set in %s.','wp-filebase'), 'php.ini'); ?>">?</a></b>
     219                        <?php printf(__('Maximum upload file size: %s.'/*def*/), WPFB_Output::FormatFilesize(WPFB_Core::GetMaxUlSize())) ?> <b>&nbsp;&nbsp;<a href="#" onclick="alert(this.title); return false;" title="<?php printf(__('Ask your webhoster to increase this limit, it is set in %s.','wp-filebase'), 'php.ini'); ?>">?</a></b>
    220220                        <p class="upload-html-bypass hide-if-no-js"><?php _e('You are using the Browser uploader.');
    221                         printf( __('Try the <a href="%s">Flash uploader</a> instead.'), esc_url(add_query_arg('flash', 1)) );
     221                        printf( __('Try the <a href="%s">Drag&amp;Drop uploader</a> instead.', 'wp-filebase'), esc_url(add_query_arg('flash', 1)) );
    222222                        ?>
    223223                    </div>
  • wp-filebase/trunk/readme.txt

    r1298742 r1303067  
    55Requires at least: 3.1
    66Tested up to: 4.3.1
    7 Stable tag: 3.1.03
     7Stable tag: 3.1.04
    88
    99Adds a powerful download manager including file categories, downloads counter, widgets, sorted file lists and more to your WordPress blog.
     
    121121== Changelog ==
    122122
     123= 3.1.04 =
     124* FileBrowser: new option `Inline Add` to toggle the display of Add File/Category links
     125* Async Uploader: Added error message on invalid server response after upload
     126* Prevent direct script access for Editor Plugin, Post Browser and AJAX
     127* PHP 7 compatibility: `mysql_close` only called if exists
     128
    123129= 3.1.03 =
    124130* Added Extension Update API caching
     
    132138* Made treeview drag&drop IE compatible
    133139* Added delete buttons to backend file browser
    134 * Show icons in file/category selector tree (TEST)
     140* Show icons in file/category selector tree
    135141* Better sync progress reporting
    136142* Improved sync performance, reduced server load during sync
    137 * Rescan process can be resumed (TEST?)
    138 * Rescan Tool now rescans remote files (TEST)
    139143* Removed FLV player, replaced with HTML5 video player
    140144* Added compatibility for latest CF7
     
    143147* File browser: only show add category if user has permission
    144148* Run a File Sync to fix category file counter bug (categories no opening in file browser)
    145 * Inherit category upload permissions (TEST)
     149* Inherit category upload permissions
    146150* Deleting a category removes the folder
    147151* New list template header/footer var: `%search_term%`
  • wp-filebase/trunk/tinymce/editor_plugin.js

    r876786 r1303067  
    99                    try { postId = tinymce.DOM.get("post_ID").value; } catch(ex) {}
    1010                    ed.windowManager.open(                         
    11                         {file: (url+'/../editor_plugin.php?post_id='+postId+'&content='+escape(tinyMCE.activeEditor.selection.getContent())), title:'WP-Filebase', width: 810, height: 400, inline: 1},
     11                        {file: (ajaxurl.replace("admin-ajax.php","?wpfilebase-screen=editor-plugin")+'&post_id='+postId+'&content='+escape(tinyMCE.activeEditor.selection.getContent())), title:'WP-Filebase', width: 810, height: 400, inline: 1},
    1212                        {plugin_url: url}
    1313                    );
  • wp-filebase/trunk/wp-filebase.php

    r1298742 r1303067  
    44Plugin URI:  https://wpfilebase.com/
    55Description: Adds a powerful downloads manager supporting file categories, download counter, widgets, sorted file lists and more to your WordPress blog.
    6 Version:     3.1.03
     6Version:     3.1.04
    77Author:      Fabian Schlieper
    88Author URI:  http://fabi.me/
     
    1616{
    1717    define('WPFB', 'wpfb');
    18     define('WPFB_VERSION', '3.1.03');
     18    define('WPFB_VERSION', '3.1.04');
    1919    define('WPFB_PLUGIN_ROOT', str_replace('\\','/',dirname(__FILE__)).'/');
    2020    if(!defined('ABSPATH')) {
     
    108108
    109109// database settings
     110
     111 /**
     112  * WPDB
     113  * @global wpdb $wpdb
     114  */
    110115global $wpdb;
     116
    111117if(isset($wpdb))
    112118{
     
    124130    register_deactivation_hook(__FILE__, 'wpfilebase_deactivate');
    125131}
     132
     133
  • wp-filebase/trunk/wpfb-load.php

    r1113324 r1303067  
    7272
    7373
    74 function wpfb_ajax_die($msg,$title='',$args='') {
    75     @ob_end_clean();
    76     echo '<div class="error-div">
    77     <strong>' . $msg . '</strong></div>';
    78     exit;   
    79 }
    8074
    81 
    82 if(defined('DOING_AJAX') && DOING_AJAX) {
    83     add_filter('wp_die_ajax_handler', create_function('$v','return "wpfb_ajax_die";'));
    84 }
Note: See TracChangeset for help on using the changeset viewer.