HEX
Server: Microsoft-IIS/8.5
System: Windows NT YDAWBH120 6.3 build 9600 (Windows Server 2012 R2 Standard Edition) AMD64
User: tentjecom_web (0)
PHP: 7.4.14
Disabled: NONE
Upload Files
File: D:/HostingSpaces/yoda-ict/uttoeternietoe.com/wwwroot/wp-content/plugins/totalsmug/totalsmug.php
<?php
/*
Plugin Name: TotalSmug
Plugin URI: http://www.yoda-ict.nl/totalsmug
Description: Smugmug galley / upload plugin based on smugmug API.
Version: 1.0
Author: Frans Rampen
Author URI: http://www.yoda-ict.nl
*/
require_once 'vendor/autoload.php';
require("parsedomain.php");

@define('TOTALSMUG_QUERY_VAR', 'tsm');
@define('TOTALSMUG_ACTION_QUERY_VAR', 'tsm-action');
@define('TOTALSMUG_FILEPATH', '/totalsmug/totalsmug.php');
@define('TOTALSMUG_COMMENT', "\n\n<!-- TotalSmug Plugin: http://www.yoda-ict.nl/totalsmug -->\n\n");
@define('TOTALSMUG_VERSION', '1.0.0');
@define('TOTALSMUG_PHOTOSWIPE_CSS','.cf:before, .cf:after {
  content: " ";
  display: table;
}
.cf:after {
  clear: both;
}
.cf {
  *zoom: 1;
}
figure {
  margin: 0;
  padding: 10px;
}
figure a {
  display: block;
  box-shadow: 0 0 0 0 !important;
}
.picture {
  padding: 36px 0;
}
.picture:first-child {
  padding-top: 0;
}
figcaption {
  display: none;
}
@media screen and (min-width: 630px) {
  header {
    text-align: none;
  }
  header h1,
  header a {
    font-size: 12px;
  }
  header h1 {
    float: left;
  }
  header a {
    float: right;
  }
  .demo-content {
    padding: 10px;
  }
  .picture {
    padding: 0;
    border-bottom: 0;
  }
  .one figure {
    float: left;
    width: 100%;
  }
  .two figure {
    float: left;
    width: 50%;
  }
  .three figure {
    float: left;
    width: 33.33333333%;
  }
  .four figure {
    float: left;
    width: 25%;
  }
  .five figure {
    float: left;
    width: 20%;
  }
  .six figure {
    float: left;
    width: 16.66666666%;
  }
  .seven figure {
    float: left;
    width: 14.28571428%;
  }
  .eight figure {
    float: left;
    width: 12.5%;
  }
  .nine figure {
    float: left;
    width: 11.11111111%;
  }
  .ten figure {
    float: left;
    width: 10%;
  }
}');
@define('TOTALSMUG_PHOTOSWIPE','<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="pswp__bg"></div>
    <div class="pswp__scroll-wrap">
 
        <div class="pswp__container">
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
        </div>
 
        <div class="pswp__ui pswp__ui--hidden">
            <div class="pswp__top-bar">
                <div class="pswp__counter"></div>
                <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>
                <button class="pswp__button pswp__button--share" title="Share"></button>
                <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>
                <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>
                <div class="pswp__preloader">
                    <div class="pswp__preloader__icn">
                      <div class="pswp__preloader__cut">
                        <div class="pswp__preloader__donut"></div>
                      </div>
                    </div>
                </div>
            </div>
            <div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
                <div class="pswp__share-tooltip"></div> 
            </div>
            <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
            </button>
            <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
            </button>
            <div class="pswp__caption">
                <div class="pswp__caption__center"></div>
            </div>
        </div>
    </div>
</div>');

if ( !empty($_REQUEST[TOTALSMUG_ACTION_QUERY_VAR]) ) {
	switch ( $_REQUEST[TOTALSMUG_ACTION_QUERY_VAR] ) {
		case 'css':
			header("Content-type: text/css");
			echo TOTALSMUG_PHOTOSWIPE_CSS;
			die();
			break;
		default:
			die();
			break;
	}
}

if ( !class_exists('TotalSmug') ) { 

	class TotalSmug 
	{
		var $totalsmug_domain = 'yoda-ict.nl';
		var $totalsmug_is_setup = 0;
		var $settings;
		var $client;
        var $options;
		var $defaults = array(
								'key' => ''
								,'secret' => ''
								,'oauth_token' => ''
                                ,'oauth_token_secret' => ''
								,'category' => ''
								,'albumid' => ''
								,'thumbsize' => 'Th'		// Default thumbnail size
								,'size' => 'M'				// Default photo size
                                ,'columns' => '4'            // Default number of columns
								,'captions' => 'true'		// Display Captions
								,'original' => 'false'  // Display link to orginal image
								,'version' => TOTALSMUG_VERSION
								,'installed' => true
							);
        
		function TotalSmug()
		{
			# Description:	Constructor for TotalSmug class. Adds all the necessary
			#				hooks and filters into WordPress.
			#
			
			if ( $this->totalsmug_is_setup )
                return;
            
			load_plugin_textdomain($this->totalsmug_domain, PLUGINDIR.'/'.dirname(plugin_basename(__FILE__)), dirname(plugin_basename(__FILE__)));
            
			$this->totalsmug_load_settings();
			
			add_action('wp_head', array(&$this, 'totalsmug_wp_head'));
			add_action('admin_menu', array(&$this, 'totalsmug_admin_menu'));
			add_action('admin_menu', array(&$this, 'totalsmug_admin_panel'));
			add_action('wp_ajax_add_album_dd', array(&$this, 'totalsmug_add_album_dropdown'));
			add_action('wp_ajax_reset_album_rss', array(&$this, 'totalsmug_reset_album_rss'));
            add_action('wp_footer', array(&$this, 'totalsmug_wp_foot'));
			
			add_filter('post_rewrite_rules', array(&$this, 'totalsmug_post_rewrite_rules'), 50);
			add_filter('page_rewrite_rules', array(&$this, 'totalsmug_page_rewrite_rules'), 50);
			
			add_filter('query_vars', array(&$this, 'totalsmug_query_vars'));
			add_filter('admin_print_scripts', array(&$this, 'totalsmug_admin_print_scripts'));
			
			add_shortcode('totalsmug', array(&$this, 'totalsmug_shortcode'));
		}
        
		function totalsmug_load_settings()
		{
			# Description:	Load the default settings to display in the TotalSmug editing pane.

            // Add the default settings if this is the first time TotalSmug is being loaded
			
			$version = get_option('totalsmug_version');
			
			if ( !get_option('totalsmug_installed') || version_compare($version, TOTALSMUG_VERSION, 'lt') ) {
				foreach($this->defaults as $k => $v) add_option('totalsmug_' . $k, $v);
				update_option('totalsmug_version', TOTALSMUG_VERSION);
			}
			
			$this->settings = array	(
										'key' => get_option('totalsmug_key')
										,'secret' => get_option('totalsmug_secret')
										,'oauth_token' => get_option('totalsmug_token')
                                        ,'oauth_token_secret' => get_option('totalsmug_token_secret')
										,'category' => get_option('totalsmug_category')
										,'albumid' => ''
										,'thumbsize' => get_option('totalsmug_thumbsize')
										,'size' => get_option('totalsmug_size')
                                        ,'columns' => get_option('totalsmug_columns') 
										,'captions' => get_option('totalsmug_captions')
										,'original' => get_option('totalsmug_original')
									);
			
		}
		
		function totalsmug_install_db() {
            global $wpdb;

            $table_name = $wpdb->prefix ."smug_gallery";
            if($wpdb->get_var("show tables like '$table_name'") != $table_name) {
                $sql = "CREATE TABLE " . $table_name . " (
        albumid VARCHAR(20) NOT NULL,
        rssxml longtext NOT NULL,
        UNIQUE KEY id (albumid)
        );";

                require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
                dbDelta($sql);
            }
        }

        
		function totalsmug_wp_foot()
		{
			# Description:	Adds photoswipe placeholder and script references.
			#
			
			$wp = get_bloginfo('wpurl');
			$plugindir = $wp . '/' . PLUGINDIR . '/';
            $ps_holder = TOTALSMUG_PHOTOSWIPE;
			
			echo <<<EOF
    {$ps_holder}
    <script type="text/javascript" src="{$plugindir}totalsmug/photoswipe/photoswipe.min.js"></script> 
    <script type="text/javascript" src="{$plugindir}totalsmug/photoswipe/photoswipe-ui-default.min.js"></script>
    <script type="text/javascript" src="{$plugindir}totalsmug/photoswipe/script-min.js"></script>\n
EOF;
		}

        function totalsmug_wp_head()
		{
			# Description:	Adds stylesheet link references.
			#
			
			$wp = get_bloginfo('wpurl');
			$plugindir = $wp . '/' . PLUGINDIR . '/';
            $url = $plugindir . plugin_basename(__FILE__);
            $query_var = TOTALSMUG_ACTION_QUERY_VAR;
			
			echo <<<EOF
    <link rel="stylesheet" href="{$plugindir}totalsmug/photoswipe/photoswipe.css"/>
    <link rel="stylesheet" href="{$plugindir}totalsmug/photoswipe/default-skin/default-skin.css"/> 
    <link rel="stylesheet" type="text/css" href="{$url}?{$query_var}=css" />\n
EOF;
            echo '<script type="text/javascript">
//<![CDATA[
function OpenImagePopup(imagename) {
  window.open("'.$plugindir.'totalsmug/popup.htm?" + imagename,"popup","width=640,height=480,directories=no,location=no,menubar=no,scrollbars=no,status=no,toolbar=no,resizable=no,top=0,left=0");
}//]]>
</script>';
		}
        
		function totalsmug_shortcode($atts, $content = null)
		{
			# Description:	Processes the shortcode text for TotalSmug
			#
			# Parameters:	atts - array of attribute names/value pairs
			#				content - the text between the shortcode tags (optional)
			
			global $post,$wpdb;
			
			$attrs = shortcode_atts($this->settings, $atts);

			array_walk($attrs, array(&$this, 'fixTrueFalseAndEncoding'));
			extract($attrs);
			if ( !empty($albumid) ) {

                $table_name = $wpdb->prefix ."smug_gallery";
                $rssxml = $wpdb->get_var("select rssxml from $table_name where albumid='$albumid'");
                if (empty($rssxml)) {
                    $rssxml = $this->construct_smug_rss($albumid,$thumbsize,$size);
                    $id = $wpdb->get_var("select albumid from $table_name where albumid='$albumid'");
                    if (empty($id) ) {
                        $wpdb->insert( $table_name, array( 'albumid' => $albumid, 'rssxml' => $rssxml ), array( '%s', '%s' ) );
                    }
                    else {
                        $wpdb->update( $table_name, array('rssxml' => $rssxml ), array('albumid' => $albumid), array( '%s' ), array( '%s' ) );
                    }
                }
                if ( !function_exists('fetch_rss') ) {
					include_once (ABSPATH . WPINC . '/class-simplepie.php');
				}
                $rss = new SimplePie();
                $rss->set_raw_data($rssxml);
                $rss->init();
                $items = $rss->get_items();

                // Generate the HTML code
                $rows = "";
                switch ($columns)
                {   
                    case "10":
                        $rows = "ten";
                        break;
                    case "9":
                        $rows = "nine";
                        break;
                    case "8":
                        $rows = "eight";
                        break;
                    case "7":
                        $rows = "seven";
                        break;
                    case "6":
                        $rows = "six";
                        break;
                    case "5":
                        $rows = "five";
                        break;
                    case "4":
                        $rows = "four";
                        break;
                    case "3":
                        $rows = "three";
                        break;
                    case "2":
                        $rows = "two";
                        break;
                    case "1":
                        $rows = "one";
                        break;
                }
                $output = apply_filters('totalsmug_style', TOTALSMUG_COMMENT . "<div class=\"picture ".$rows." cf\" itemscope itemtype=\"http://schema.org/ImageGallery\"\>\n");
                $index = 0;
                foreach($items as $item) {
                    
                    $photo_url = $item->data['child']['']['link'][0]['data'];
                    $width = $item->data['child']['']['link'][0]['attribs']['']['width'];
                    $height = $item->data['child']['']['link'][0]['attribs']['']['height'];
                    
                    $thumb_url = $item->data['child']['']['guid'][0]['data'];
                    $twidth = $item->data['child']['']['guid'][0]['attribs']['']['width'];
                    $theight = $item->data['child']['']['guid'][0]['attribs']['']['height'];

                    $item_title = ($captions == 'true') ? htmlspecialchars(strip_tags($item->data['child']['']['description'][0]['data'])) : '';
                    if (strlen ($item_title) > 0)
                    {
                        $item_title += '<br/>';
                    }
                    $item_original = ($original == 'true') ? '<center><a href="javascript:OpenImagePopup(\''.$item->data['child']['']['comments'][0]['data'].'\');">View orginal image</a></center>' : '';

                    $output .= '<figure itemprop="associatedMedia" itemscope itemtype="http://schema.org/ImageObject">';
                    $output .= '<a href="'.$photo_url.'" itemprop="contentUrl" data-size="'.$width.'x'.$height.'" data-index="'.$index.'">';
                    $output .= '<img src="'.$thumb_url.'" height="'.$theight.'" width="'.$twidth.'" itemprop="thumbnail" alt="">';
                    $output .= '</a><figcaption>'.$item_title.$item_original.'</figcaption></figure>';
                    $index++;
                }
			}
			return $output.'</div>';
		}
		
		function totalsmug_admin_menu()
		{
			# Description:	Adds the TotalSmug forms to the Post/Page editing screens
			#
			
			add_meta_box('totalsmug', 'TotalSmug', array(&$this, 'totalsmug_insert_form'), 'post', 'normal');
			add_meta_box('totalsmug', 'TotalSmug', array(&$this, 'totalsmug_insert_form'), 'page', 'normal');
		}
        
		function totalsmug_insert_form()
		{
			# Description:	Inserts the TotalSmug form in the Post/Page edit screen
			global $f;
?>
			<table class="form-table">
				<tr valign="top">
					<th scope="row">
						<label for="TotalSmug_Album"><?php _e('Smugmug Album:') ?></label>
					</th>
					<td>
            <select name="TotalSmug[albumid]" id="TotalSmug_album">
            <?php
            $albums = $this->totalsmug_get_albums(get_option("totalsmug_categoryid"));
            foreach($albums as $a) {
                echo "<option value=\"".$a->NodeID."\">".$a->Name."</option>";
            } ?>
            </select><br/><a href="#" id="album_add_link">Add new Album</a>
					</td>
				</tr>
				<tr><th colspan="2"><div id="TotalSmug_Add_Album" style="float:left;margin-left:80px;">
                <div id="add_album_error"></div>
                <table cellspacing="0" cellpadding="0">
                  <tr><td class="left"><?php _e('Album&nbsp;Name:') ?></td><td class="left"><input type="text" size="30" name="album_name" id="album_name" /></td></tr>
                  <tr><td colspan="2" class="submit"><input type="button" onclick="return totalSmugAdmin.addNewAlbum(this.form.TotalSmug_album,this.form.album_name);" value="<?php _e('Add new Album') ?>" /></td></tr>
                </table>
            </div></th>
        </tr>
				<tr valign="top">
					<th scope="row">
						<label for="TotalSmug_thumbsize"><?php _e('Thumbnail size:') ?></label>
					</th>
					<td>
                        <select name="TotalSmug[thumbsize]" id="TotalSmug_thumbsize">
                            <option value="Ti" <?php if ( get_option('totalsmug_thumbsize') == 'Ti' ) echo ' selected="selected"'; ?>><?php _e('Tiny (100x100)'); ?></option>
                            <option value="Th" <?php if ( get_option('totalsmug_thumbsize') == 'Th' ) echo ' selected="selected"'; ?>><?php _e('Regular (150x150)'); ?></option>
                            <option value="S" <?php if ( get_option('totalsmug_thumbsize') == 'S' ) echo ' selected="selected"'; ?>><?php _e('Small (200x200)'); ?></option>
                            <option value="M" <?php if ( get_option('totalsmug_thumbsize') == 'M' ) echo ' selected="selected"'; ?>><?php _e('Medium (250x250)'); ?></option>
                        </select>
					</td>
				</tr>
				<tr valign="top">
					<th scope="row">
						<label for="TotalSmug_size"><?php _e('Photo size:') ?></label>
					</th>
					<td>
						<select name="TotalSmug[size]" id="TotalSmug_size">
                            <option value="S" <?php if ( get_option('totalsmug_size') == 'S' ) echo ' selected="selected"'; ?>><?php _e('Small (400x300)'); ?></option>
                            <option value="M" <?php if ( get_option('totalsmug_size') == 'M' ) echo ' selected="selected"'; ?>><?php _e('Medium (600x450)'); ?></option>
                            <option value="L" <?php if ( get_option('totalsmug_size') == 'L' ) echo ' selected="selected"'; ?>><?php _e('Large (800x600)'); ?></option>
                            <option value="X1" <?php if ( get_option('totalsmug_size') == 'X1' ) echo ' selected="selected"'; ?>><?php _e('X-Large 1 (1024x768)'); ?></option>
                            <option value="X2" <?php if ( get_option('totalsmug_size') == 'X2' ) echo ' selected="selected"'; ?>><?php _e('X-Large 2 (1280x1024)'); ?></option>
                            <option value="X3" <?php if ( get_option('totalsmug_size') == 'X3' ) echo ' selected="selected"'; ?>><?php _e('X-Large 3 (1600x1200)'); ?></option>
						</select>
					</td>
				</tr>
                <tr valign="top">
                    <th scope="row">
                        <label for="TotalSmug_columns"><?php _e('Number of columns:') ?></label>
                    </th>
                    <td>
                        <select name="TotalSmug[columns]" id="TotalSmug_columns">
                            <option value="1" <?php if ( get_option('totalsmug_columns') == '1' ) echo ' selected="selected"'; ?>><?php _e('1'); ?></option>
                            <option value="2" <?php if ( get_option('totalsmug_columns') == '2' ) echo ' selected="selected"'; ?>><?php _e('2'); ?></option>
                            <option value="3" <?php if ( get_option('totalsmug_columns') == '3' ) echo ' selected="selected"'; ?>><?php _e('3'); ?></option>
                            <option value="4" <?php if ( get_option('totalsmug_columns') == '4' ) echo ' selected="selected"'; ?>><?php _e('4'); ?></option>
                            <option value="5" <?php if ( get_option('totalsmug_columns') == '5' ) echo ' selected="selected"'; ?>><?php _e('5'); ?></option>
                            <option value="6" <?php if ( get_option('totalsmug_columns') == '6' ) echo ' selected="selected"'; ?>><?php _e('6'); ?></option>
                            <option value="7" <?php if ( get_option('totalsmug_columns') == '7' ) echo ' selected="selected"'; ?>><?php _e('7'); ?></option>
                            <option value="8" <?php if ( get_option('totalsmug_columns') == '8' ) echo ' selected="selected"'; ?>><?php _e('8'); ?></option>
                            <option value="9" <?php if ( get_option('totalsmug_columns') == '9' ) echo ' selected="selected"'; ?>><?php _e('9'); ?></option>
                            <option value="10" <?php if ( get_option('totalsmug_columns') == '10' ) echo ' selected="selected"'; ?>><?php _e('10'); ?></option>
                        </select>
                    </td>
                </tr>
				<tr valign="top">
					<th scope="row">
						<?php _e('Options:') ?>
					</th>
					<td>
						<input type="hidden" name="TotalSmug[captions]" id="TotalSmug_captions_" value="false" />
						<input type="checkbox" name="TotalSmug[captions]" id="TotalSmug_captions" value="true"<?php if ( get_option('totalsmug_captions') == 'true' ) echo ' checked="checked"'; ?> />
						<label for="TotalSmug_captions"><?php _e('Display captions'); ?></label>
						<br />
						<input type="hidden" name="TotalSmug[original]" id="TotalSmug_original_" value="false" />
						<input type="checkbox" name="TotalSmug[original]" id="TotalSmug_original" value="true"<?php if ( get_option('totalsmug_original') == 'true' ) echo ' checked="checked"'; ?> />
						<label for="TotalSmug_original"><?php _e('Show link to original image'); ?></label>
						<br />
					</td>
				</tr>
				<tr>
					<th colspan="2" class="submit">
						<input type="button" onclick="return totalSmugAdmin.sendToEditor(this.form);" value="<?php _e('Send to Editor &raquo;') ?>" />
					</th>
				</tr>
			</table>
		<?php 
		}
        
        
		function totalsmug_admin_panel()
		{
            # Description:	Registers the admin panel to WordPress
            
			if (function_exists('add_options_page')) {
				add_options_page('TotalSmug', 'TotalSmug', 'manage_options', basename(__FILE__), array(&$this, 'totalsmug_panel'));
			}
		}
        
		function totalsmug_panel()
		{ 
            global $client;
            # Description:	The administrative panel for the TotalSmug plugin
            if ( isset ($_REQUEST['oauth_token']) && isset ($_REQUEST['oauth_verifier'])) 
            {
                $this->get_smugmug();
                // Step 3: Use the Request token obtained in step 1 to get an access token
                $oauth_verifier = $_GET['oauth_verifier'];  // This comes back with the callback request.
                $token = $client->getAccessToken($oauth_verifier);  // The results of this call is what your application needs to store.
                update_option('totalsmug_token', $token[oauth_token]);
                update_option('totalsmug_token_secret', $token[oauth_token_secret]);
                $conf_status = $this->totalsmug_verify_conf( null, null, $category );
                update_option('totalsmug_categoryid', $conf_status);
                $ms[] = 'new_conf_valid';
            }
            if ( isset($_POST['submit']) ) {
                if ( function_exists('current_user_can') && !current_user_can('manage_options') )
                    die(__('Cheatin&#8217; uh?'));

                $key = $_POST['totalsmug_key'];
                $secret = $_POST['totalsmug_secret'];
                $category = $_POST['totalsmug_category'];
                $thumbsize = $_POST['totalsmug_thumbsize'];
                $size = $_POST['totalsmug_size'];
                $columns = $_POST['totalsmug_columns'];
                $captions = $_POST['totalsmug_captions'];
                $original = $_POST['totalsmug_original'];
                update_option('totalsmug_token_secret', 'authorize');
                if ( empty($key) ) {
                    $conf_status = 'empty';
                    $ms[] = 'new_key_empty';
                    delete_option('totalsmug_key');
                } 
                if ( empty($secret) ) {
                    $conf_status = 'empty';
                    $ms[] = 'new_secret_empty';
                    delete_option('totalsmug_secret');
                }
                if ( empty($category) ) {
                    $category = get_domain_name($_SERVER["SERVER_NAME"]);
                }
                
                if (!empty($key) && !empty($secret)) {
                    $conf_status = $this->totalsmug_verify_conf( $key, $secret, $category );
                }

                if ( $conf_status != 'invalid' ) {
                    update_option('totalsmug_key', $key);
                    update_option('totalsmug_secret', $secret);
                    update_option('totalsmug_category', $category);
                    update_option('totalsmug_thumbsize', $thumbsize);
                    update_option('totalsmug_size', $size);
                    update_option('totalsmug_columns', $columns);
                    update_option('totalsmug_captions', $captions);
                    update_option('totalsmug_original', $original);
                    $ms[] = 'new_conf_valid_need_auth';
                } else {
                    $ms[] = 'new_conf_failed';
                }

                if ( $conf_status == 'invalid' ) {
                    $key = get_option('totalsmug_key');
                    $secret = get_option('totalsmug_secret');
                    $category = get_option('totalsmug_category');

                    if ( empty($key) || empty($secret)) {
                        $conf_status = 'empty';
                    } else {
                        $conf_status = $this->totalsmug_verify_conf( $key, $secret, $category );
                    }
                    if ( $conf_status != 'invalid' ) {
                        $ms[] = 'conf_valid';
                        update_option('totalsmug_categoryid', $conf_status);
                    } else if ( $conf_status == 'invalid' ) {
                        delete_option('totalsmug_key', $key);
                        delete_option('totalsmug_secret', $secret);
                        $ms[] = 'conf_failed';
                    }
                }
            }
            $messages = array(
                'new_key_empty' => array('color' => 'aa0', 'text' => __('Your key has been cleared.')),
                'new_secret_empty' => array('color' => 'aa0', 'text' => __('Your secret has been cleared.')),
                'new_conf_valid' => array('color' => '2d2', 'text' => __('Your configuration has been verified. Happy Smugging!')),
                'new_conf_valid_need_auth' => array('color' => '2d2', 'text' => __($conf_status)),
                'new_conf_failed' => array('color' => 'd22', 'text' => __('The configuration you entered could not be validated. Please check for errors.')),
                'conf_valid' => array('color' => '2d2', 'text' => __('The stored configuration is valid.')),
                'conf_failed' => array('color' => 'aa0', 'text' => __('The configuration below was previously validated but an error occurred. Please check your input.')));
            
            if ( !empty($_POST ) && $conf_status == 'valid') : ?>
    <div id="message" class="updated fade"><p><strong><?php _e('Options saved.') ?></strong></p></div>
  <?php endif; ?>
			<div class=wrap>
				<form action="" method="post" id="totalsmug_panel">
					<h2>TotalSmug</h2>
					<p>
					<?php _e('Integrate your <a href="http://www.smugmug.com/">SmugMug</a> galleries into your WordPress posts and pages.'); ?>
					</p>
					<h3><?php _e('SmugMug API Settings'); ?></h3>
					<table class="form-table">
						<tr valign="top">
							<th scope="row">
								<label for="totalsmug_key"><?php _e('SmugMug API Key:') ?></label>
							</th>
							<td>
								<input type="text" size="40" name="totalsmug_key" value="<?php echo get_option('totalsmug_key'); ?>" id="totalsmug_key" />
							</td>
						</tr>
						<tr valign="top">
							<th scope="row">
								<label for="totalsmug_secret"><?php _e('SmugMug Secret:') ?></label>
							</th>
							<td>
								<input type="text" size="40" name="totalsmug_secret" value="<?php echo get_option('totalsmug_secret'); ?>" id="totalsmug_secret" />
							</td>
						</tr>
						<tr valign="top">
							<th scope="row">
								<label for="totalsmug_category"><?php _e('SmugMug Category:') ?></label>
							</th>
							<td>
								<input type="text" size="40" name="totalsmug_category" value="<?php echo get_option('totalsmug_category'); ?>" id="totalsmug_category" />
							</td>
						</tr>
                        <tr valign="top">
                            <th scope="row">
                                <label><?php _e('SmugMug Validation:') ?></label>
                            </th>
                            <td>
                                <label><strong><?php if (strlen(get_option('totalsmug_token_secret')) <= 9) { echo 'not '; } ?>validated</strong></label>
                            </td>
                        </tr>
						<?php if (!empty($ms)) {
                                  foreach ( $ms as $m ) : ?>
              <tr valign="top"><th scope="row" colspan="2"><p style="padding: .5em; background-color: #<?php echo $messages[$m]['color']; ?>; color: #fff; font-weight: bold;"><?php echo $messages[$m]['text']; ?></p></th></tr>
            <?php endforeach;
                              } ?>
					</table>
					<h3><?php _e('Default Gallery Settings'); ?></h3>
					<p>
					<?php _e('Customize the default settings shown in the TotalSmug panel in the Write Post or Write Page SubPanel.'); ?>
					</p>
					<table class="form-table">
						<tr valign="top">
							<th scope="row">
								<label for="totalsmug_thumbsize"><?php _e('Thumbnail size:') ?></label>
							</th>
                            <td>
                                <select name="totalsmug_thumbsize" id="totalsmug_thumbsize">
                                    <option value="Ti" <?php if ( get_option('totalsmug_thumbsize') == 'Ti' ) echo ' selected="selected"'; ?>><?php _e('Tiny (100x100)'); ?></option>
                                    <option value="Th" <?php if ( get_option('totalsmug_thumbsize') == 'Th' ) echo ' selected="selected"'; ?>><?php _e('Regular (150x150)'); ?></option>
                                    <option value="S" <?php if ( get_option('totalsmug_thumbsize') == 'S' ) echo ' selected="selected"'; ?>><?php _e('Small (200x200)'); ?></option>
                                    <option value="M" <?php if ( get_option('totalsmug_thumbsize') == 'M' ) echo ' selected="selected"'; ?>><?php _e('Medium (250x250)'); ?></option>
                                </select>
                            </td>
						</tr>
						<tr valign="top">
							<th scope="row">
								<label for="totalsmug_size"><?php _e('Photo size:') ?></label>
							</th>
							<td>
								<select name="totalsmug_size" id="totalsmug_size">
									<option value="S"<?php if ( get_option('totalsmug_size') == 'S' ) echo ' selected="selected"'; ?>><?php _e('Small (400x300)'); ?></option>
									<option value="M"<?php if ( get_option('totalsmug_size') == 'M' ) echo ' selected="selected"'; ?>><?php _e('Medium (600x450)'); ?></option>
									<option value="L"<?php if ( get_option('totalsmug_size') == 'L' ) echo ' selected="selected"'; ?>><?php _e('Large (800x600)'); ?></option>
									<option value="X1"<?php if ( get_option('totalsmug_size') == 'X1' ) echo ' selected="selected"'; ?>><?php _e('X-Large 1 (1024x768)'); ?></option>
									<option value="X2"<?php if ( get_option('totalsmug_size') == 'X2' ) echo ' selected="selected"'; ?>><?php _e('X-Large 2 (1280x1024)'); ?></option>
									<option value="X3"<?php if ( get_option('totalsmug_size') == 'X3' ) echo ' selected="selected"'; ?>><?php _e('X-Large 3 (1600x1200)'); ?></option>
								</select>
							</td>
						</tr>
                        <tr valign="top">
                            <th scope="row">
                                <label for="TotalSmug_columns"><?php _e('Number of columns:') ?></label>
                            </th>
                            <td>
                                <select name="totalsmug_columns" id="totalsmug_columns">
                                    <option value="1" <?php if ( get_option('totalsmug_columns') == '1' ) echo ' selected="selected"'; ?>><?php _e('1'); ?></option>
                                    <option value="2" <?php if ( get_option('totalsmug_columns') == '2' ) echo ' selected="selected"'; ?>><?php _e('2'); ?></option>
                                    <option value="3" <?php if ( get_option('totalsmug_columns') == '3' ) echo ' selected="selected"'; ?>><?php _e('3'); ?></option>
                                    <option value="4" <?php if ( get_option('totalsmug_columns') == '4' ) echo ' selected="selected"'; ?>><?php _e('4'); ?></option>
                                    <option value="5" <?php if ( get_option('totalsmug_columns') == '5' ) echo ' selected="selected"'; ?>><?php _e('5'); ?></option>
                                    <option value="6" <?php if ( get_option('totalsmug_columns') == '6' ) echo ' selected="selected"'; ?>><?php _e('6'); ?></option>
                                    <option value="7" <?php if ( get_option('totalsmug_columns') == '7' ) echo ' selected="selected"'; ?>><?php _e('7'); ?></option>
                                    <option value="8" <?php if ( get_option('totalsmug_columns') == '8' ) echo ' selected="selected"'; ?>><?php _e('8'); ?></option>
                                    <option value="9" <?php if ( get_option('totalsmug_columns') == '9' ) echo ' selected="selected"'; ?>><?php _e('9'); ?></option>
                                    <option value="10" <?php if ( get_option('totalsmug_columns') == '10' ) echo ' selected="selected"'; ?>><?php _e('10'); ?></option>
                                </select>
                            </td>
                        </tr>
						<tr valign="top">
							<th scope="row">
								<?php _e('Options:') ?>
							</th>
							<td>
								<input type="checkbox" name="totalsmug_captions" id="totalsmug_captions" value="true"<?php if ( get_option('totalsmug_captions') == 'true' ) echo ' checked="checked"'; ?> />
								<label for="TotalSmug_captions"><?php _e('Display captions'); ?></label>
								<br />
                                <input type="checkbox" name="totalsmug_original" id="totalsmug_original" value="true"<?php if ( get_option('totalsmug_original') == 'true' ) echo ' checked="checked"'; ?> />
                                <label for="TotalSmug_original"><?php _e('Show link to original image'); ?></label>
                                <br />
							</td>
						</tr>
					</table>
					<p class="submit">
					<input type="submit" class="button-primary" name="submit" value="<?php _e('Save Changes');?>" />
					</p>
				</form>
			</div>
		<?php
		}

		function totalsmug_admin_print_scripts()
		{
			# Description:	Adds the necessary scripts to the editing page head
            
			if( $GLOBALS['editing']) {
				$wp = get_bloginfo('wpurl');		
				wp_enqueue_script('totalSmugAdmin', $wp . '/' . PLUGINDIR . '/'  . dirname(plugin_basename(__FILE__)) . '/totalsmug.js.php', array('jquery'), '1.0.0');
			}
		}
		
		function totalsmug_post_rewrite_rules($rewrite)
		{
			# Description:	Creates the new rewrite rules for post permalinks
			
			global $wp_rewrite;
            
			$totalsmug_token = '%' . TOTALSMUG_QUERY_VAR . '%';
			$wp_rewrite->add_rewrite_tag($totalsmug_token, '(.+)', TOTALSMUG_QUERY_VAR . '=');		
			$totalsmug_structure = $wp_rewrite->permalink_structure . TOTALSMUG_QUERY_VAR . "/$totalsmug_token";
			$totalsmug_rewrite = $wp_rewrite->generate_rewrite_rules($totalsmug_structure);
            
			return ( $rewrite + $totalsmug_rewrite );
		}
		
		function totalsmug_page_rewrite_rules($rewrite)
		{
			# Description:	Creates the new rewrite rules for page permalinks
			
			global $wp_rewrite;
            
			$totalsmug_token = '%' . TOTALSMUG_QUERY_VAR . '%';
			$wp_rewrite->add_rewrite_tag($totalsmug_token, '(.+)', TOTALSMUG_QUERY_VAR . '=');
			$totalsmug_structure = $wp_rewrite->page_structure . '/' . TOTALSMUG_QUERY_VAR . "/$totalsmug_token";
			$totalsmug_rewrite = $wp_rewrite->generate_rewrite_rules($totalsmug_structure);
			return ( $totalsmug_rewrite + $rewrite );
		}
        
		function totalsmug_query_vars($vars)
		{
			$vars[] = TOTALSMUG_QUERY_VAR;
			return $vars;
		}
        
		function totalsmug_flush_rewrite_rules() 
		{
			global $wp_rewrite;
            
			$wp_rewrite->flush_rules();
		}
		
		function fixTrueFalseAndEncoding(&$value, $key) {
			$value = urldecode($value);
            
			if ($value == 'false') {
				$value = false;
			} elseif ($value == 'true') {
				$value = true;
			}
		}
		
		function decode_entities($text, $quote_style = ENT_COMPAT)
		{
			# Description:	Handles UTF-8 decoding in PHP4
			
			if ( function_exists('html_entity_decode') ) {
				$text = html_entity_decode($text, $quote_style, 'ISO-8859-1');
			} else { 
				$trans_tbl = get_html_translation_table(HTML_ENTITIES, $quote_style);
				$trans_tbl = array_flip($trans_tbl);
				$text = strtr($text, $trans_tbl);
			}
			$text = preg_replace('~&#x([0-9a-f]+);~ei', 'chr(hexdec("\\1"))', $text); 
			$text = preg_replace('~&#([0-9]+);~e', 'chr("\\1")', $text);
			
			return $text;
		}
		
        function totalsmug_verify_conf( $key, $secret, $cat ) {
            global $client;
            try {
                $token = get_option('totalsmug_token_secret');
                if (($token == '') || ($token == 'authorize')) {

                    // Step 1: Get a request token using an optional callback URL back to ourselves
                    $callback = 'http://'.$_SERVER['SERVER_NAME'].':'.$_SERVER['SERVER_PORT'].$_SERVER['SCRIPT_NAME'].'?'.$_SERVER['QUERY_STRING'];
                    $this->get_smugmug($key, $secret);
                    $request_token = $client->getRequestToken($callback);
                    update_option('totalsmug_token', $request_token[oauth_token]);
                    update_option('totalsmug_token_secret', $request_token[oauth_token_secret]);
                    $perms = [
                        'Access' => 'Full',
                        'Permissions' => 'Modify',
                    ];
                    return 'Your key and secret have been verified. Klik <a href='.$client->getAuthorizeURL($perms).'>here</a> to authenticate';
                } else {
                    $this->get_smugmug();
                    $usernode = $client->get('!authuser')->User->Uris->Node;
                    $folders = $client->get("{$usernode}!children")->Node;
                    foreach($folders as $node)
                    {
                        if ($node->Name == get_option("totalsmug_category"))
                        {
                            $cid = end(explode('/',$node->Uri));
                            break;
                        }
                    }
                    return $cid;
                }
            }
            catch (Exception $e) {
                echo "<div id=\"message\" class=\"updated fade\"><p><strong>{$e->getMessage()} (Error Code: {$e->getCode()})</strong></p></div>";
                return "invalid";
            }
        }
        
        function totalsmug_get_albums($category_id) {
            global $client;
            try {
                $this->get_smugmug();
                $albums = $client->get("node/{$category_id}!children", array('count' => 1000, 'SortDirection' => 'Ascending' , 'SortMethod' => 'Name'))->Node;
                $arr = array();
                foreach ($albums as $al) {
                    $arr[] = $al;
                }
                return $arr;
            }
            catch (Exception $e) {
                echo "<div id=\"message\" class=\"updated fade\"><p><strong>{$e->getMessage()} (Error Code: {$e->getCode()})</strong></p></div>";
                return "invalid";
            }
        }
        
        function totalsmug_add_album_dropdown() {
            global $client;
            $name = $_POST['name'];
            $category_id = get_option('totalsmug_categoryid');
            try {
                if (!empty($name)) {
                    $this->get_smugmug();
                    $album = $client->post("node/{$category_id}!children", array('Type' => 'Album', 'Name' => $name, 'UrlName' => preg_replace('/\s+/', '-', $name), 'Privacy' => 'Unlisted', 'SortMethod' => 'DateAdded'));
                }
                $albums = $this->totalsmug_get_albums($category_id);
                foreach($albums as $a) {
                    echo '<option value="'.$a->NodeID.'"';
                    if ( $a->Name == $name ) echo ' selected="selected"';
                    echo '>'.$a->Name.'</option>';
                }
            }
            catch (Exception $e) {
                echo "<div id=\"message\" class=\"updated fade\"><p><strong>{$e->getMessage()} (Error Code: {$e->getCode()})</strong></p></div>";
            }
            die;
        }
        
        function totalsmug_reset_album_rss() {
            global $wpdb;
            $albumid = $_POST['name'];
            #echo "Album: ". $albumid;
            if (!empty($albumid)) {
                $table_name = $wpdb->prefix ."smug_gallery";
                $wpdb->update( $table_name, array('rssxml' => '' ), array('albumid' => $albumid), array( '%s' ), array( '%s' ) );
            }
            die;
        }
        
        function construct_smug_rss($albumid,$thumb,$link) {
            global $client;
            $this->get_smugmug();
            $linksize = '';
            $thumbsize = '';
            $customsize = '';
            $width = 0;
            $height = 0;
            $pwidth = 0;
            $pheight = 0;
            $twidth = 0;
            $theight = 0;
            switch ($link) {
                case "S":
                    $linksize = 'SmallImageUrl';
                    $pwidth = 400;
                    $pheight = 300;
                    break;
                case "M":
                    $linksize = 'MediumImageUrl';
                    $pwidth = 600;
                    $pheight = 450;
                    break;
                case "L":
                    $linksize = 'LargeImageUrl';
                    $pwidth = 800;
                    $pheight = 600;
                    break;
                case "X1":
                    $linksize = 'XLargeImageUrl';
                    $pwidth = 1024;
                    $pheight = 768;
                    break;
                case "X2":
                    $linksize = 'X2LargeImageUrl';
                    $pwidth = 1280;
                    $pheight = 1024;
                    break;
                case "X3":
                    $linksize = 'LargestImageUrl';
                    $pwidth = 1600;
                    $pheight = 1200;
                    break;
            }
            switch ($thumb) {
                case "Th":
                    $thumbsize = 'ThumbImageUrl';
                    $twidth = 150;
                    $theight = 150;
                    break;
                case "Ti":
                    $thumbsize = 'TinyImageUrl';
                    $twidth = 100;
                    $theight = 100;
                    break;
                case "S":
                    $thumbsize = 'SmallImageUrl';
                    $customsize = "200x200!";
                    $twidth = 200;
                    $theight = 200;
                    break;
                case "M":
                    $thumbsize = 'SmallImageUrl';
                    $customsize = "250x250!";
                    $twidth = 250;
                    $theight = 250;
                    break;
            }
            try {
                $album = $client->get("node/{$albumid}")->Node;
                $album = $client->get($album->Uris->Album)->Album;
                $rssxml = '<?xml version="1.0" encoding="ISO-8859-1" ?>
                   <rss version="2.0">
                    <channel>
                      <title>'. $album->Title .'</title>
                      <description>'. $album->Description.'</description>
                      <lastBuildDate>'. $album->LastUpdated .'</lastBuildDate>
                    ';
                $images = $client->get($album->Uris->AlbumImages, array('count' => $album->ImageCount));
                foreach ($images->AlbumImage as $image) {
                    $imagesizes = $client->get($image->Uris->ImageSizes)->ImageSizes;
                    $title = (empty($image->Title)) ? $image->FileName : $image->Title;
                    $caption = (empty($image->Caption)) ? '' : $image->Caption;
                    $thumb = $imagesizes->$thumbsize;
                    if (!empty($customsize))
                    {   
                        $thumb = str_replace("/S/", "/".$customsize."/", $thumb);
                        $thumb = str_replace("-S.", "-".$customsize.".", $thumb);  
                    }
                    if ($image->OriginalHeight > $image->OriginalWidth)
                    {
                        if ($image->OriginalHeight < $pwidth)
                        {
                            $link = $imagesizes->OriginalImageUrl;
                            $height = $image->OriginalWidth;
                            $width = $image->OriginalHeight;
                        }
                        else
                        {
                            $link = $imagesizes->$linksize;
                            $height = $pwidth;
                            $width = $height/($image->OriginalHeight/$image->OriginalWidth);
                        }
                    }
                    else
                    {
                        if ($image->OriginalWidth < $pwidth)
                        {
                            $link = $imagesizes->OriginalImageUrl;
                            $width = $image->OriginalWidth;
                            $height = $image->OriginalHeight;
                        }
                        else
                        {
                            $link = $imagesizes->$linksize;
                            $width = $pwidth;
                            $height = $width/($image->OriginalWidth/$image->OriginalHeight);
                        }
                    }
                    $originalurl = $imagesizes->OriginalImageUrl;
                    $rssxml .= '<item>
                        <title>'. $title .'</title>
                        <link width="'.$width.'" height="'.$height.'">'. $link .'</link>
                        <description><![CDATA['. $caption .']]></description>
                        <comments>'.$originalurl.'</comments>
                        <guid isPermaLink="false" width="'.$twidth.'" height="'.$theight.'">'. $thumb .'</guid>
                      </item>
                   ';
                }
                $rssxml .= '</channel>   
               </rss>';
                return $rssxml;
            }
            catch (Exception $e) {
                echo "<div id=\"message\" class=\"updated fade\"><p><strong>{$e->getMessage()} (Error Code: {$e->getCode()})</strong></p></div>";
                return '';
            }
        }

        function get_smugmug() {
            global $client;
            if (func_num_args() == 0) {
                $key = get_option('totalsmug_key');
                $secret = get_option('totalsmug_secret');
                $token = get_option('totalsmug_token');
                $token_secret = get_option('totalsmug_token_secret');
            }
            else
            {
                $arg_list = func_get_args();
                $key = $arg_list[0];
                $secret = $arg_list[1];
                $token = '';
                $token_secret = '';
            }
            if (!isset($client)) {
                $options = [
              'AppName' => 'TotalSmug/1.0 (http://www.yoda-ict.nl/TotalSmug)',
              '_verbosity' => 1, # Reduce verbosity to reduce the amount of data in the response and to make using it easier.
              'OAuthSecret' => $secret,
                    ];
                $client = new phpSmug\Client($key, $options);
                if (strlen($token_secret) > 9)
                {
                    $client->setToken($token, $token_secret);
                }
            }
        }
    }
}
global $totalsmug;

if ( class_exists('TotalSmug') ) {
	$totalsmug = new TotalSmug();

		// Register for activation
  register_activation_hook(__FILE__, array(&$totalsmug, 'totalsmug_install_db'));
	register_activation_hook(__FILE__, array(&$totalsmug, 'totalsmug_flush_rewrite_rules'));
}

?>