/**
  * Get cached request results
  *
  * @param $server_url
  * @param $action
  * @param $args
  * @return bool
  */
 public function getCachedApiRequest($server_url, $action, $args)
 {
     $cache_action = $this->checkAction($action);
     if (!$cache_action) {
         $msg = sprintf("Cacher action: %s, cache_action: %s", $action, $cache_action ? 'YES' : 'NO');
         WPRC_Functions::log($msg, 'api', 'api.log');
         return false;
     }
     $foo = $this->model->getCachedRequest($server_url, $action, $args);
     $msg = sprintf("Cacher model get: %s", $foo == false ? 'NO' : 'YES');
     WPRC_Functions::log($msg, 'api', 'api.log');
     return $foo;
 }
 public static function wprc_theme_update_row($theme_key, $theme)
 {
     $current = get_site_transient('update_themes');
     if (!isset($current->response[$theme_key])) {
         return false;
     }
     $r = (array) $current->response[$theme_key];
     $themes_allowedtags = array('a' => array('href' => array(), 'title' => array()), 'abbr' => array('title' => array()), 'acronym' => array('title' => array()), 'code' => array(), 'em' => array(), 'strong' => array());
     $theme_name = wp_kses($theme['Name'], $themes_allowedtags);
     if (isset($r['repository_id'])) {
         $details_url = self_admin_url("theme-install.php?tab=theme-information&repository_id=" . $r['repository_id'] . "&theme={$theme_key}&TB_iframe=true&width=640&height=484");
     } else {
         $details_url = self_admin_url("theme-install.php?tab=theme-information&theme={$theme_key}&TB_iframe=true&width=640&height=484");
     }
     $wp_list_table = _get_list_table('WP_MS_Themes_List_Table');
     echo '<tr class="plugin-update-tr"><td colspan="' . $wp_list_table->get_column_count() . '" class="plugin-update colspanchange"><div class="update-message">';
     if (!current_user_can('update_themes')) {
         printf(__('There is a new version of %1$s available. <a href="%2$s" class="thickbox" title="%3$s">View version %4$s details</a>.', 'installer'), $theme['Name'], esc_url($details_url), esc_attr($theme['Name']), $r->new_version);
     } else {
         if (empty($r['package'])) {
             printf(__('There is a new version of %1$s available. <a href="%2$s" class="thickbox" title="%3$s">View version %4$s details</a>. <em>Automatic update is unavailable for this theme.</em>', 'installer'), $theme['Name'], esc_url($details_url), esc_attr($theme['Name']), $r['new_version']);
         } else {
             printf(__('There is a new version of %1$s available. <a href="%2$s" class="thickbox" title="%3$s">View version %4$s details</a> or <a href="%5$s">update now</a>.', 'installer'), $theme['Name'], esc_url($details_url), esc_attr($theme['Name']), $r['new_version'], wp_nonce_url(self_admin_url('update.php?action=upgrade-theme&theme=') . $theme_key, 'upgrade-theme_' . $theme_key));
         }
     }
     //if ( empty( $r['package'] ) )
     //{
     /*if (isset($r['message']) && !empty($r['message']))
     		{
     			echo '<br /> '.wp_kses( $r->message, $themes_allowedtags );
     		}*/
     if (isset($r['message']) && !empty($r['message'])) {
         $message = WPRC_Functions::formatMessage((object) $r['message']);
         if (isset($r['message_type']) && $r['message_type'] == 'notify') {
             WPRC_AdminNotifier::addMessage('wprc-theme-info-' . $theme_key, $message);
         } else {
             echo $message;
         }
     } else {
         if (isset($r['repository_id']) && isset($r['purchase']) && !empty($r['purchase']) && isset($r['price']) && !empty($r['price'])) {
             echo '<br /> ';
             $purl = WPRC_Functions::sanitizeURL($r['purchase']);
             $return_url = rawurlencode(admin_url('theme-install.php?tab=theme-information&repository_id=' . $r['repository_id'] . '&theme=' . $theme_key));
             $salt = rawurlencode($r['repository_salt']);
             if (strpos($purl, '?')) {
                 $url_glue = '&';
             } else {
                 $url_glue = '?';
             }
             $purl .= $url_glue . 'return_to=' . $return_url . '&rsalt=' . $salt;
             echo '<a href="' . $purl . '&TB_iframe=true&width=640&height=484' . '" class="thickbox" title="' . sprintf(__('Upgrade %s', 'installer'), '(' . $r['currency']->symbol . $r['price'] . ' ' . $r['currency']->name . ')') . '">' . sprintf(__('Upgrade %s', 'installer'), '(' . $r['currency']->symbol . $r['price'] . ' ' . $r['currency']->name . ')') . '</a>';
         }
     }
     //}
     do_action("in_theme_update_message-{$theme_key}", $theme, $r);
     echo '</div></td></tr>';
 }
 /**
  * Send request to any file
  * 
  * @param string method
  * @param string url to send
  * @param mixed arguments to send
  */
 public function sendRequest($method, $url, $args, $timeout = 15)
 {
     WPRC_Loader::includeWordpressHttp();
     if (isset($args['request'])) {
         $body_array = array('action' => $args['action'], 'request' => serialize($args['request']));
     } else {
         $body_array = array('action' => $args['action']);
     }
     // log
     $debug_msg = sprintf('SERVER REQUEST, method: %s, timeout: %d, uri: %s, args: %s', $method, $timeout, $url, print_r($args, true));
     WPRC_Functions::log($debug_msg, 'server', 'server.log');
     switch ($method) {
         case 'post':
             $request = wp_remote_post($url, array('timeout' => $timeout, 'body' => $body_array));
             // log
             $debug_msg = sprintf('SERVER REQUEST, response: %s', print_r($request, true));
             WPRC_Functions::log($debug_msg, 'server', 'server.log');
             if (is_wp_error($request) || 200 != wp_remote_retrieve_response_code($request)) {
                 // log
                 if (is_wp_error($request)) {
                     $debug_msg = sprintf('SERVER REQUEST, response error: %s', print_r($request->get_error_message(), true));
                 } else {
                     $debug_msg = sprintf('SERVER REQUEST, response error code: %s', print_r(wp_remote_retrieve_response_code($request), true));
                 }
                 WPRC_Functions::log($debug_msg, 'server', 'server.log');
                 // connection failed
                 return false;
             }
             $res = @unserialize(wp_remote_retrieve_body($request));
             if (false === $res) {
                 $res = new WP_Error('repository_connector_error', __('An unknown error occurred.', 'installer'), wp_remote_retrieve_body($request));
                 // log
                 $debug_msg = sprintf('SERVER REQUEST, response unknown error: %s', print_r(wp_remote_retrieve_body($request), true));
                 WPRC_Functions::log($debug_msg, 'server', 'server.log');
             }
             break;
     }
     return $res;
 }
 public function updateExtensionMap($get, $post)
 {
     if (isset($get['update_extension_map'])) {
         $msg = sprintf('Extension maps update entered');
         WPRC_Functions::log($msg, 'controller', 'controller.log');
         // clear cache
         delete_transient('wprc_update_extensions_maps');
         $result = WPRC_Installer::wprc_update_extensions_maps();
         echo json_encode(array('result' => $result));
         $msg = sprintf('Extension maps update complete');
         WPRC_Functions::log($msg, 'controller', 'controller.log');
         exit;
     }
     exit;
 }
    private function wprc_display_theme($theme, $actions = null, $show_details = true)
    {
        global $themes_allowedtags;
        if (empty($theme)) {
            return;
        }
        $name = wp_kses($theme->name, $themes_allowedtags);
        $desc = wp_kses($theme->description, $themes_allowedtags);
        //if ( strlen($desc) > 30 )
        //	$desc =  substr($desc, 0, 15) . '<span class="dots">...</span><span>' . substr($desc, -15) . '</span>';
        $preview_link = $theme->preview_url . '?TB_iframe=true&amp;width=600&amp;height=400';
        $status = $this->_get_theme_status($theme);
        if (!is_array($actions)) {
            $actions = array();
            if ($status == 'latest_installed' || $status == 'newer_installed' || !isset($theme->purchase_link) || empty($theme->purchase_link)) {
                switch ($status) {
                    default:
                    case 'install':
                        $actions[] = '<a href="' . self_admin_url('theme-install.php?tab=theme-information&amp;theme=' . $theme->slug . '&amp;TB_iframe=true&amp;tbWidth=640&amp;tbHeight=484') . '" class="thickbox thickbox-preview onclick" title="' . esc_attr(sprintf(__('Install &#8220;%s&#8221;', 'installer'), $name)) . '">' . __('Install', 'installer') . '</a>';
                        break;
                    case 'update_available':
                        $actions[] = '<a href="' . self_admin_url('theme-install.php?tab=theme-information&amp;theme=' . $theme->slug . '&amp;TB_iframe=true&amp;tbWidth=640&amp;tbHeight=484') . '" class="thickbox thickbox-preview onclick" title="' . esc_attr(sprintf(__('Update to version %s', 'installer'), $theme->version)) . '">' . __('Update', 'installer') . '</a>';
                        break;
                    case 'newer_installed':
                    case 'latest_installed':
                        $actions[] = '<span class="install-now" title="' . esc_attr__('This theme is already installed and is up to date', 'installer') . '">' . _x('Installed', 'theme', 'installer') . '</span>';
                        break;
                }
            }
            if (isset($theme->message) && !empty($theme->message)) {
                //echo wp_kses( $theme->message,   $themes_allowedtags );
                $message = WPRC_Functions::formatMessage((object) $theme->message);
                if (isset($theme->message_type) && $theme->message_type == 'notify') {
                    WPRC_AdminNotifier::addMessage('wprc-theme-info-' . $theme->slug, $message);
                } else {
                    $actions[] = $message;
                }
            } elseif (!($status == 'latest_installed' || $status == 'newer_installed') && (isset($theme->purchase_link) && !empty($theme->purchase_link) && isset($theme->price) && !empty($theme->price))) {
                //$actions[] = '<a href="' . self_admin_url('theme-install.php?tab=theme-information&amp;theme=' . $theme->slug .'&amp;TB_iframe=true&amp;tbWidth=640&amp;tbHeight=484') . '" class="thickbox thickbox-preview onclick" title="' . esc_attr(sprintf(__('Buy &#8220;%s&#8221;','installer'), $name)) . '">' . sprintf(__('Buy %s','installer') ,'('.$theme->price.$theme->currency.')'). '</a>';
                if (current_user_can('install_themes')) {
                    $purl = WPRC_Functions::sanitizeURL($theme->purchase_link);
                    $return_url = rawurlencode(admin_url('theme-install.php?tab=theme-information&repository_id=' . $theme->repository_id . '&theme=' . $theme->slug));
                    $salt = rawurlencode($theme->salt);
                    if (strpos($purl, '?')) {
                        $url_glue = '&';
                    } else {
                        $url_glue = '?';
                    }
                    $purl .= $url_glue . 'return_to=' . $return_url . '&rsalt=' . $salt;
                    $actions[] = '<a href="' . $purl . '&amp;TB_iframe=true&amp;tbWidth=640&amp;tbHeight=484' . '" class="thickbox thickbox-preview onclick" title="' . esc_attr(sprintf(__('Buy &#8220;%s&#8221;', 'installer'), $name)) . '">' . sprintf(__('Buy %s', 'installer'), '(' . $theme->currency->symbol . $theme->price . ' ' . $theme->currency->name . ')') . '</a>';
                    if (empty($theme->repository->repository_username) && empty($theme->repository->repository_password)) {
                        $actions[] = '<a href=" ' . admin_url('admin.php?wprc_c=repository-login&amp;wprc_action=RepositoryLogin&amp;repository_id=' . $theme->repository->id . '&amp;_wpnonce=' . $this->nonce_login) . '" class="thickbox" title="' . __('Log in', 'installer') . '">' . __('Login', 'installer') . '</a>';
                    }
                }
            }
            if (!is_network_admin()) {
                $actions[] = '<a href="' . $preview_link . '" class="thickbox thickbox-preview onclick previewlink" title="' . esc_attr(sprintf(__('Preview &#8220;%s&#8221;', 'installer'), $name)) . '">' . __('Preview', 'installer') . '</a>';
            }
            $actions = apply_filters('theme_install_action_links', $actions, $theme);
        }
        $actions = implode(' | ', $actions);
        ?>
	<a class='thickbox thickbox-preview screenshot'
		href='<?php 
        echo esc_url($preview_link);
        ?>
'
		title='<?php 
        echo esc_attr(sprintf(__('Preview &#8220;%s&#8221;', 'installer'), $name));
        ?>
'>
	<img src='<?php 
        echo esc_url($theme->screenshot_url);
        ?>
' width='150' />
	</a>
	<h3><?php 
        echo $name;
        ?>
</h3>
	<span class='action-links'><?php 
        echo $actions;
        ?>
</span>
	<p><?php 
        echo $desc;
        ?>
</p>
	<?php 
        if ($show_details) {
            ?>
	<a href="#theme_detail" class="theme-detail hide-if-no-js" tabindex='4'><?php 
            _e('Details', 'installer');
            ?>
</a>
	<div class="themedetaildiv hide-if-js">
	<p><strong><?php 
            _e('Version:', 'installer');
            ?>
</strong> <?php 
            echo wp_kses($theme->version, $themes_allowedtags);
            ?>
</p>
	<p><strong><?php 
            _e('Author:', 'installer');
            ?>
</strong> <?php 
            echo wp_kses($theme->author, $themes_allowedtags);
            ?>
</p>
	<?php 
            if (!empty($theme->last_updated)) {
                ?>
	<p><strong><?php 
                _e('Last Updated:', 'installer');
                ?>
</strong> <span title="<?php 
                echo $theme->last_updated;
                ?>
"><?php 
                printf(__('%s ago', 'installer'), human_time_diff(strtotime($theme->last_updated)));
                ?>
</span></p>
	<?php 
            }
            if (!empty($theme->requires)) {
                ?>
	<p><strong><?php 
                _e('Requires WordPress Version:', 'installer');
                ?>
</strong> <?php 
                printf(__('%s or higher', 'installer'), $theme->requires);
                ?>
</p>
	<?php 
            }
            if (!empty($theme->tested)) {
                ?>
	<p><strong><?php 
                _e('Compatible up to:', 'installer');
                ?>
</strong> <?php 
                echo $theme->tested;
                ?>
</p>
	<?php 
            }
            if (!empty($theme->downloaded)) {
                ?>
	<p><strong><?php 
                _e('Downloaded:', 'installer');
                ?>
</strong> <?php 
                printf(_n('%s time', '%s times', $theme->downloaded, 'installer'), number_format_i18n(intval($theme->downloaded)));
                ?>
</p>
	<?php 
            }
            ?>
		<?php 
            if (!isset($theme->num_ratings) || empty($theme->num_ratings)) {
                $theme->num_ratings = 0;
            }
            if (!isset($theme->rating) || empty($theme->rating)) {
                $theme->rating = 0;
            }
            ?>
	<div class="star-holder" title="<?php 
            printf(_n('(based on %s rating)', '(based on %s ratings)', $theme->num_ratings, 'installer'), number_format_i18n(intval($theme->num_ratings)));
            ?>
">
		<div class="star star-rating" style="width: <?php 
            echo esc_attr($theme->rating);
            ?>
px"></div>
		<div class="star star5"><img src="<?php 
            echo admin_url('images/star.png?v=20110615');
            ?>
" alt="<?php 
            esc_attr_e('5 stars');
            ?>
" /></div>
		<div class="star star4"><img src="<?php 
            echo admin_url('images/star.png?v=20110615');
            ?>
" alt="<?php 
            esc_attr_e('4 stars');
            ?>
" /></div>
		<div class="star star3"><img src="<?php 
            echo admin_url('images/star.png?v=20110615');
            ?>
" alt="<?php 
            esc_attr_e('3 stars');
            ?>
" /></div>
		<div class="star star2"><img src="<?php 
            echo admin_url('images/star.png?v=20110615');
            ?>
" alt="<?php 
            esc_attr_e('2 stars');
            ?>
" /></div>
		<div class="star star1"><img src="<?php 
            echo admin_url('images/star.png?v=20110615');
            ?>
" alt="<?php 
            esc_attr_e('1 star');
            ?>
" /></div>
	</div>
	</div>
	<?php 
        }
        /*
        object(stdClass)[59]
        public 'name' => string 'Magazine Basic' (length=14)
        public 'slug' => string 'magazine-basic' (length=14)
        public 'version' => string '1.1' (length=3)
        public 'author' => string 'tinkerpriest' (length=12)
        public 'preview_url' => string 'http://wp-themes.com/?magazine-basic' (length=36)
        public 'screenshot_url' => string 'http://wp-themes.com/wp-content/themes/magazine-basic/screenshot.png' (length=68)
        public 'rating' => float 80
        public 'num_ratings' => int 1
        public 'homepage' => string 'http://wordpress.org/extend/themes/magazine-basic' (length=49)
        public 'description' => string 'A basic magazine style layout with a fully customizable layout through a backend interface. Designed by <a href="http://bavotasan.com">c.bavota</a> of <a href="http://tinkerpriestmedia.com">Tinker Priest Media</a>.' (length=214)
        public 'download_link' => string 'http://wordpress.org/extend/themes/download/magazine-basic.1.1.zip' (length=66)
        */
    }
 public function checkCompatibility($get, $post)
 {
     $msg = sprintf('Repository Reporter check compatibility enter');
     WPRC_Functions::log($msg, 'controller', 'controller.log');
     $reporter = WPRC_Loader::getRequester('compatibility-reporter');
     $check_extension_type = $get['extension_type_singular'];
     $check_extension_name = $get['extension_name'];
     $check_extension_repository_url = $get['repository_url'];
     $check_extension_version = $get['extension_version'];
     $check_extension_slug = isset($get['extension_slug']) ? $get['extension_slug'] : '';
     $parameters = array('check_extension_name' => $check_extension_name, 'check_extension_type' => $check_extension_type, 'check_extension_repository_url' => $check_extension_repository_url, 'check_extension_version' => $check_extension_version, 'check_extension_slug' => $check_extension_slug);
     $report = $reporter->prepareRequest($parameters);
     // send request only once even if it fails
     $response = $reporter->sendRequest($report, true);
     // layout
     if (isset($response) && isset($response->body) && is_array($response->body) && array_key_exists('left_extensions', $response->body)) {
         $left_extensions = $response->body['left_extensions'];
         $right_extensions = array();
         if (is_array($left_extensions) && count($left_extensions) > 0) {
             $left_extension = array_shift($left_extensions);
             $right_extensions = $left_extension['compatibility_info'];
         }
         $no_compatibility_information = false;
         if (count($right_extensions) == 0) {
             $no_compatibility_information = true;
         }
         $version_found = $response->body['version_found'];
     } else {
         $no_compatibility_information = true;
     }
     // Additional attributes to show later the table in a right way
     $report_extensions = $report['request']['right_extensions'];
     $new_right_extensions = array();
     if (isset($right_extensions) && is_array($right_extensions)) {
         foreach ($report_extensions as $report_key => $report_extension) {
             $name = $report_extension['name'];
             $version = $report_extension['version'];
             $extension_counts = 0;
             $last_key = '';
             $first_key = '';
             $works = 0;
             $broken = 0;
             $score = 0;
             foreach ($right_extensions as $key => $right_extension) {
                 if ($extension_counts == 0) {
                     $first_key = $key;
                 }
                 if ($right_extension['name'] == $name) {
                     $extension_counts++;
                     $last_key = $key;
                     $works += $right_extensions[$key]['works'];
                     $broken += $right_extensions[$key]['broken'];
                     $score += $right_extensions[$key]['score'];
                 }
             }
             if ($extension_counts == 1) {
                 $new_right_extensions[$last_key] = $right_extensions[$last_key];
             } elseif ($extension_counts > 1) {
                 $right_extensions[$first_key]['hide'] = false;
                 $right_extensions[$first_key]['link'] = true;
                 $new_right_extensions[$first_key] = $right_extensions[$first_key];
                 $new_right_extensions[$report_key . '_total'] = $right_extensions[$last_key];
                 $new_right_extensions[$report_key . '_total']['works'] = $works;
                 $new_right_extensions[$report_key . '_total']['broken'] = $broken;
                 $new_right_extensions[$report_key . '_total']['score'] = number_format($works * 100 / ($works + $broken), 0);
                 $new_right_extensions[$report_key . '_total']['total'] = true;
                 unset($new_right_extensions[$report_key . '_total']['version']);
             }
         }
     }
     require_once WPRC_TEMPLATES_DIR . '/extension-compatibility-information.tpl.php';
     //WPRC_Loader::includePage('check-compatibility');
     $msg = sprintf('Repository Reporter check compatibility complete');
     WPRC_Functions::log($msg, 'controller', 'controller.log');
 }
 /**
  * Search plugins in multiple repositories 
  * This method replaces 'plugins_api' and 'themes_api' function
  */
 public function extensionsApi($state, $action, $args, $extension_type)
 {
     // default wp behaviour for tabs other than search
     //if ($action=='hot_tags') return false;
     if (isset($_GET['tab'])) {
         if ($_GET['tab'] != 'dashboard' && $_GET['tab'] != 'search' && $_GET['tab'] != 'plugin-information' && $_GET['tab'] != 'theme-information') {
             return false;
         }
     }
     $rauth = true;
     $rpass = '';
     $ruser = '';
     if (isset($_GET['repository_id']) && isset($_GET['user']) && isset($_GET['pass']) && ($action == 'plugin_information' || $action == 'theme_information')) {
         $rm = WPRC_Loader::getModel('repositories');
         $rid = $_GET['repository_id'];
         $repository = $rm->getRepository($rid);
         $ruser = rawurldecode($_GET['user']);
         $rsalt = $repository->repository_authsalt;
         $rpass = rawurldecode($_GET['pass']);
         //WPRC_Security::decrypt($repository->repository_authsalt,rawurldecode($_GET['pass']));
         $login = $rm->testLogin($rid, $ruser, $rpass);
         if ($login != false && empty($login['error'])) {
             $rauth = true;
         } else {
             $rauth = false;
         }
     }
     $repositories_ids = array();
     if (isset($args->repositories)) {
         $repositories_ids = $args->repositories;
         unset($args->repositories);
     }
     $rm = WPRC_Loader::getModel('repositories');
     $repos = $rm->getRepositoriesByIds($repositories_ids);
     $results = array();
     // Remade per_page parameters in order to get consistent pagination
     $per_page = 0;
     $repos_number = count($repos);
     if ($action == 'query_plugins') {
         $per_page = WPRC_PLUGINS_API_QUERY_PLUGINS_PER_PAGE;
     } elseif ($action == 'query_themes') {
         $per_page = WPRC_THEMES_API_QUERY_THEMES_PER_PAGE;
     }
     $results_per_repo = array();
     for ($i = 0; $i < $repos_number; $i++) {
         $res = false;
         $server_url = $repos[$i]->repository_endpoint_url;
         $repository_name = $repos[$i]->repository_name;
         $repository_username = $repos[$i]->repository_username;
         $repository_password = $repos[$i]->repository_password;
         $salt = $repos[$i]->repository_authsalt;
         $rid = $repos[$i]->id;
         $body_array = array('action' => $action);
         if ($repository_username != '' && $repository_password != '') {
             /*$args->username = $repository_username;
               $args->password = $repository_password;*/
             //$send_password=WPRC_Security::encrypt($salt,$repository_password);
             $body_array['auth'] = array('user' => $repository_username, 'pass' => $repository_password, 'salt' => $salt);
             //$body_array['auth'] = array('user'=>$repository_username,'pass'=>$repository_password,'salt'=>$salt);
         } else {
             unset($args->username);
             unset($args->password);
         }
         $request_array = $args;
         $request_array->per_page = $per_page;
         $body_array['request'] = serialize($args);
         if (isset($args->slug)) {
             $body_array['slug'] = $args->slug;
         }
         // debug log
         $reqargs = $body_array;
         if (isset($reqargs['auth'])) {
             $reqargs['auth'] = 'AUTH info';
         }
         $msg = sprintf("API Request to %s, request args: %s", $server_url, print_r($reqargs, true));
         WPRC_Functions::log($msg, 'api', 'api.log');
         unset($reqargs);
         $cached_request_results = apply_filters('wprc_extensions_api_before_each_repository', $server_url, $action, $args);
         if ($cached_request_results) {
             $results[$server_url] = $cached_request_results;
             // log
             $msg = sprintf("API Request to %s, using cached results", $server_url);
             WPRC_Functions::log($msg, 'api', 'api.log');
             continue;
         }
         $request = wp_remote_post($server_url, array('timeout' => 15, 'body' => $body_array));
         // log
         $msg = sprintf("API Request to %s, timeout: %d, response: %s", $server_url, 15, print_r($request, true));
         WPRC_Functions::log($msg, 'api', 'api.log');
         if (is_wp_error($request)) {
             $res = new WP_Error('extensions_api_failed', __('An unexpected HTTP Error occurred during the API request.', 'installer'), $request->get_error_message());
             // log
             $msg = sprintf("API Request to %s, response error: %s", $server_url, print_r($request->get_error_message(), true));
             WPRC_Functions::log($msg, 'api', 'api.log');
         } else {
             $request_body = wp_remote_retrieve_body($request);
             if (is_serialized($request_body)) {
                 $res = @unserialize($request_body);
             }
             if (false === $res) {
                 $res = new WP_Error('extensions_api_failed', __('An unknown error occurred.', 'installer'), wp_remote_retrieve_body($request));
                 // log
                 $msg = sprintf("API Request to %s, unknown error in response body: %s", $server_url, print_r($request_body, true));
                 WPRC_Functions::log($msg, 'api', 'api.log');
             } else {
                 if (is_object($res) && isset($res->error)) {
                     $res = new WP_Error('extensions_api_failed', $res->error, wp_remote_retrieve_body($request));
                     // log
                     $msg = sprintf("API Request to %s, action not implemented error: %s", $server_url, print_r($res, true));
                     WPRC_Functions::log($msg, 'api', 'api.log');
                 } else {
                     if (is_array($res) && isset($res['error'])) {
                         $res = new WP_Error('extensions_api_failed', $res['error'], wp_remote_retrieve_body($request));
                         // log
                         $msg = sprintf("API Request to %s, action not implemented error: %s", $server_url, print_r($res, true));
                         WPRC_Functions::log($msg, 'api', 'api.log');
                     } else {
                         // add some custom info onto the results (like repository salt etc..)
                         if ($action == 'query_plugins') {
                             foreach ($res->plugins as $key => $extension) {
                                 $res->plugins[$key]->salt = $salt;
                                 $res->plugins[$key]->repository_id = $rid;
                                 // strip non-serializable characters
                                 $res->plugins[$key]->description = preg_replace('/[\\x00-\\x08\\x0B\\x0C\\x0E-\\x1F\\x80-\\xFF]/u', '', $res->plugins[$key]->description);
                             }
                         } elseif ($action == 'query_themes') {
                             foreach ($res->themes as $key => $extension) {
                                 $res->themes[$key]->salt = $salt;
                                 $res->themes[$key]->repository_id = $rid;
                                 // strip non-serializable characters
                                 $res->themes[$key]->description = preg_replace('/[\\x00-\\x08\\x0B\\x0C\\x0E-\\x1F\\x80-\\xFF]/u', '', $res->themes[$key]->description);
                             }
                         } elseif ($action == 'plugin_information' || $action == 'theme_information') {
                             if (is_object($res)) {
                                 $res->rauth = $rauth;
                                 $res->pass = $rpass;
                                 $res->user = $ruser;
                                 $res->salt = $salt;
                                 $res->repository_id = $rid;
                             }
                         }
                     }
                 }
             }
         }
         $cached_them = apply_filters('wprc_extensions_api_after_each_repository', $server_url, $action, $args, $res);
         // log
         $msg = sprintf("API Request to %s, results cached: %s", $server_url, $cached_them == false ? 'NO' : 'YES');
         WPRC_Functions::log($msg, 'api', 'api.log');
         // set source
         $results[$server_url] = $res;
     }
     $general_results = new stdClass();
     $general_results->results = $results;
     return $general_results;
 }
 public static function wprc_plugin_update_row($file, $plugin_data)
 {
     $current = get_site_transient('update_plugins');
     if (!isset($current->response[$file])) {
         return false;
     }
     $r = $current->response[$file];
     $plugins_allowedtags = array('a' => array('href' => array(), 'title' => array()), 'abbr' => array('title' => array()), 'acronym' => array('title' => array()), 'code' => array(), 'em' => array(), 'strong' => array());
     $plugin_name = wp_kses($plugin_data['Name'], $plugins_allowedtags);
     if (isset($r->repository_id)) {
         $details_url = self_admin_url('plugin-install.php?tab=plugin-information&repository_id=' . $r->repository_id . '&plugin=' . $r->slug . '&section=changelog&TB_iframe=true&width=640&height=484');
     } else {
         $details_url = self_admin_url('plugin-install.php?tab=plugin-information&plugin=' . $r->slug . '&section=changelog&TB_iframe=true&width=640&height=484');
     }
     $wp_list_table = _get_list_table('WP_Plugins_List_Table');
     if (is_network_admin() || !is_multisite()) {
         echo '<tr class="plugin-update-tr"><td colspan="' . $wp_list_table->get_column_count() . '" class="plugin-update colspanchange"><div class="update-message">';
         if (!current_user_can('update_plugins')) {
             printf(__('There is a new version of %1$s available. <a href="%2$s" class="thickbox" title="%3$s">View version %4$s details</a>.', 'installer'), $plugin_name, esc_url($details_url), esc_attr($plugin_name), $r->new_version);
         } else {
             if (empty($r->package)) {
                 $ext_model = WPRC_Loader::getModel('extensions');
                 $repository = $ext_model->get_extension_repository($file);
                 $nonce_login = wp_create_nonce('installer-login-link');
                 if (!empty($repository)) {
                     printf(__('There is a new version of %1$s available. <a href="%2$s" class="thickbox" title="%3$s">View version %4$s details</a>. To update this plugin, first <a class="thickbox" href="%5$s">log-in to %6$s</a>.', 'installer'), $plugin_name, esc_url($details_url), esc_attr($plugin_name), $r->new_version, admin_url('admin.php?wprc_c=repository-login&amp;wprc_action=RepositoryLogin&amp;repository_id=' . $repository->id . '&amp;_wpnonce=' . $nonce_login), $repository->repository_name);
                 } else {
                     printf(__('There is a new version of %1$s available. <a href="%2$s" class="thickbox" title="%3$s">View version %4$s details</a>. <em>Automatic update is unavailable for this plugin.</em>', 'installer'), $plugin_name, esc_url($details_url), esc_attr($plugin_name), $r->new_version);
                 }
             } else {
                 printf(__('There is a new version of %1$s available. <a href="%2$s" class="thickbox" title="%3$s">View version %4$s details</a> or <a href="%5$s">update now</a>.', 'installer'), $plugin_name, esc_url($details_url), esc_attr($plugin_name), $r->new_version, wp_nonce_url(self_admin_url('update.php?action=upgrade-plugin&plugin=') . $file, 'upgrade-plugin_' . $file));
             }
         }
         //if ( empty($r->package) )
         //{
         /*if (isset($r->message) && !empty($r->message))
         		{
         				echo '<br /> '.wp_kses($r->message, $plugins_allowedtags);
         		}*/
         if (isset($r->message) && !empty($r->message)) {
             $message = WPRC_Functions::formatMessage($r->message);
             if (isset($r->message_type) && $r->message_type == 'notify') {
                 WPRC_AdminNotifier::addMessage('wprc-plugin-info-' . $r->slug, $message);
             } else {
                 echo $message;
             }
         } else {
             if (isset($r->repository_id) && isset($r->purchase) && !empty($r->purchase) && isset($r->price) && !empty($r->price)) {
                 echo '<br /> ';
                 $purl = WPRC_Functions::sanitizeURL($r->purchase);
                 $return_url = rawurlencode(admin_url('plugin-install.php?tab=plugin-information&repository_id=' . $r->repository_id . '&plugin=' . $r->slug));
                 $salt = rawurlencode($r->repository_salt);
                 if (strpos($purl, '?')) {
                     $url_glue = '&';
                 } else {
                     $url_glue = '?';
                 }
                 $purl .= $url_glue . 'return_to=' . $return_url . '&rsalt=' . $salt;
                 echo '<a href="' . $purl . '&TB_iframe=true&width=640&height=484' . '" class="thickbox" title="' . sprintf(__('Upgrade %s', 'installer'), '(' . $r->currency->symbol . $r->price . ' ' . $r->currency->name . ')') . '">' . sprintf(__('Upgrade %s', 'installer'), '(' . $r->currency->symbol . $r->price . ' ' . $r->currency->name . ')') . '</a>';
             }
         }
         //}
         do_action("in_plugin_update_message-{$file}", $plugin_data, $r);
         echo '</div></td></tr>';
     }
 }
    public function display_rows()
    {
        $plugins_allowedtags = array('a' => array('href' => array(), 'title' => array(), 'target' => array()), 'abbr' => array('title' => array()), 'acronym' => array('title' => array()), 'code' => array(), 'pre' => array(), 'em' => array(), 'strong' => array(), 'ul' => array(), 'ol' => array(), 'li' => array(), 'p' => array(), 'br' => array());
        list($columns, $hidden) = $this->get_column_info();
        $style = array();
        foreach ($columns as $column_name => $column_display_name) {
            $style[$column_name] = in_array($column_name, $hidden) ? 'style="display:none;"' : '';
        }
        $nonce_login = wp_create_nonce('installer-login-link');
        foreach ((array) $this->items as $plugin) {
            //echo '<pre>'; print_r($plugin); echo '</pre>';
            if (is_object($plugin)) {
                $plugin = (array) $plugin;
            }
            $title = wp_kses($plugin['name'], $plugins_allowedtags);
            //Limit description to 400char, and remove any HTML.
            $description = strip_tags($plugin['description']);
            if (strlen($description) > 400) {
                $description = mb_substr($description, 0, 400) . '&#8230;';
            }
            //remove any trailing entities
            $description = preg_replace('/&[^;\\s]{0,6}$/', '', $description);
            //strip leading/trailing & multiple consecutive lines
            $description = trim($description);
            $description = preg_replace("|(\r?\n)+|", "\n", $description);
            //\n => <br>
            $description = nl2br($description);
            $version = wp_kses($plugin['version'], $plugins_allowedtags);
            $name = strip_tags($title . ' ' . $version);
            $author = $plugin['author'];
            if (!empty($plugin['author'])) {
                $author = ' <cite>' . sprintf(__('By %s', 'installer'), $author) . '.</cite>';
            }
            $author = wp_kses($author, $plugins_allowedtags);
            $action_links = array();
            $action_links[] = '<a href="' . self_admin_url('plugin-install.php?tab=plugin-information&amp;repository_id=' . $plugin['repository']->id . '&amp;plugin=' . $plugin['slug'] . '&amp;TB_iframe=true&amp;width=600&amp;height=550') . '" class="thickbox" title="' . esc_attr(sprintf(__('More information about %s', 'installer'), $name)) . '">' . __('Details', 'installer') . '</a>';
            // set price
            $no_price_value = __('Free', 'installer');
            $plugin_price = $no_price_value;
            if (array_key_exists('price', $plugin)) {
                $plugin_price = $plugin['price'] != 0 && isset($plugin['price']) ? $plugin['currency']->symbol . $plugin['price'] . ' (' . $plugin['currency']->name . ')' : $no_price_value;
            }
            $plugin_source = '';
            if (array_key_exists('repository', $plugin)) {
                $plugin_source = $plugin['repository']->repository_name;
            }
            if (current_user_can('install_plugins') || current_user_can('update_plugins')) {
                //$plugin['purchase_url'] = 'http://wpml.org/shop/checkout/?buy_now=2'; // DEBUG
                WPRC_Loader::includeListTable('wprc-plugin-information');
                $status = WPRC_PluginInformation::wprc_install_plugin_install_status($plugin);
                //$action_links[]=$status['status'];
                if ($status['status'] != 'latest_installed' && $status['status'] != 'newer_installed') {
                    if (isset($plugin['purchase_link']) && !empty($plugin['purchase_link']) && $plugin_price != $no_price_value) {
                        $purl = WPRC_Functions::sanitizeURL($plugin['purchase_link']);
                        $return_url = rawurlencode(admin_url('plugin-install.php?tab=plugin-information&repository_id=' . $plugin['repository']->id . '&plugin=' . $plugin['slug']));
                        $salt = rawurlencode($plugin['salt']);
                        if (strpos($purl, '?')) {
                            $url_glue = '&';
                        } else {
                            $url_glue = '?';
                        }
                        $purl .= $url_glue . 'return_to=' . $return_url . '&rsalt=' . $salt;
                        $status = array('status' => 'paid', 'url' => $purl, 'version' => $plugin['version']);
                    }
                    /*else
                                 {
                                     WPRC_Loader::includeListTable('wprc-plugin-information');
                    		$status = WPRC_PluginInformation::wprc_install_plugin_install_status( $plugin );    
                                 }*/
                }
                $url_glue = false === strpos($status['url'], '?') ? '?' : '&';
                $status['url'] .= $url_glue . 'repository_id=' . $plugin['repository']->id;
                $showedmessage = false;
                switch ($status['status']) {
                    case 'install':
                        if ($status['url']) {
                            $action_links[] = '<a class="install-now" href="' . $status['url'] . '" title="' . esc_attr(sprintf(__('Install %s', 'installer'), $name)) . '">' . __('Install Now', 'installer') . '</a>';
                        }
                        break;
                    case 'update_available':
                        if ($status['url']) {
                            $action_links[] = '<a href="' . $status['url'] . '" title="' . esc_attr(sprintf(__('Update to version %s', 'installer'), $status['version'])) . '">' . sprintf(__('Update Now', 'installer'), $status['version']) . '</a>';
                        }
                        break;
                    case 'paid':
                        //$action_links[] = '<a href="' . $status['url'] . '" class="thickbox">' . __('Buy' , 'installer') . ' (' . $plugin['currency'] . $plugin['price'].')</a>';
                        if (isset($plugin['message']) && !empty($plugin['message'])) {
                            $action_links[] = WPRC_Functions::formatMessage($plugin['message']);
                            $showedmessage = true;
                        } else {
                            //$action_links[] = '<a href=" ' . admin_url('admin.php?wprc_c=repository-login&wprc_action=RepositoryLogin&repository_id=' . $plugin['repository']->id) . '&buyurl='.rawurlencode($status['url']).'" class="thickbox" title="' . __('Buy', 'installer') . '">' . __('Buy ' , 'installer') . ' (' . $plugin['currency'] . $plugin['price'].')</a>';
                            //$action_links[] = '<a href=" ' . $status['url']  . '" class="thickbox" title="' . __('Buy', 'installer') . '">' . __('Buy' , 'installer') . ' (' . $plugin['currency'] . $plugin['price'].')</a>';
                            $action_links[] = '<a href=" ' . $status['url'] . '&TB_iframe=true' . '" class="thickbox" title="' . sprintf(__('Buy %s', 'installer'), $name) . '">' . sprintf(__('Buy %s', 'installer'), '(' . $plugin['currency']->symbol . $plugin['price'] . ' ' . $plugin['currency']->name . ')') . '</a>';
                        }
                        if (empty($plugin['repository']->repository_username) && empty($plugin['repository']->repository_password)) {
                            $action_links[] = '<a href=" ' . admin_url('admin.php?wprc_c=repository-login&amp;wprc_action=RepositoryLogin&amp;repository_id=' . $plugin['repository']->id . '&amp;_wpnonce=' . $nonce_login) . '" class="thickbox" title="' . __('Log in', 'installer') . '">' . __('Login', 'installer') . '</a>';
                        }
                        break;
                    case 'latest_installed':
                    case 'newer_installed':
                        $action_links[] = '<span title="' . esc_attr__('This plugin is already installed and is up to date', 'installer') . ' ">' . __('Installed', 'installer') . '</span>';
                        break;
                }
                if (isset($plugin['message']) && !empty($plugin['message'])) {
                    $message = WPRC_Functions::formatMessage($plugin['message']);
                    if (isset($plugin['message_type']) && $plugin['message_type'] == 'notify') {
                        WPRC_AdminNotifier::addMessage('wprc-plugin-info-' . $plugin['slug'], $message);
                    } elseif (!$showedmessage) {
                        $action_links[] = $message;
                    }
                }
            }
            // add check compatibility link
            //            $action_links[] = '<a href="' . self_admin_url( 'plugin-install.php?tab=plugin-information&amp;repository_id='. $plugin['repository']->id .'&amp;plugin=' . $plugin['slug'] .
            //                '&amp;TB_iframe=true&amp;width=600&amp;height=550' ) . '" class="thickbox" title="' .
            //                esc_attr( sprintf( __( 'Check compatibility of "%s" plugin with activated extensions', 'installer' ), $name ) ) . '">' . __( 'Check compatibility', 'installer' ) . '</a>';
            $slug = isset($plugin['slug']) ? '&amp;extension_slug=' . $plugin['slug'] : '';
            $action_links[] = '<a href="' . self_admin_url('admin.php?wprc_c=repository-reporter&amp;wprc_action=checkCompatibility&amp;repository_id=' . $plugin['repository']->id . '&amp;repository_url=' . $plugin['repository']->repository_endpoint_url . '&amp;extension_name=' . $plugin['name'] . '&amp;extension_version=' . $plugin['version'] . $slug . '&amp;extension_type_singular=plugin&amp;extension_type=plugins&amp;TB_iframe=true&amp;width=300&amp;height=400') . '" class="thickbox" title="' . esc_attr(sprintf(__('Check compatibility status for "%s" plugin', 'installer'), $name)) . '">' . __('Check compatibility', 'installer') . '</a>';
            $action_links = apply_filters('plugin_install_action_links', $action_links, $plugin);
            if (!isset($plugin['num_ratings']) || empty($plugin['num_ratings'])) {
                $plugin['num_ratings'] = 0;
            }
            if (!isset($plugin['rating']) || empty($plugin['rating'])) {
                $plugin['rating'] = 0;
            }
            ?>
		<tr>
			<td class="name column-name"<?php 
            echo $style['name'];
            ?>
><strong><?php 
            echo $title;
            ?>
</strong>
				<div class="action-links"><?php 
            if (!empty($action_links)) {
                echo implode(' | ', $action_links);
            }
            ?>
</div>
			</td>
			<td class="vers column-version"<?php 
            echo $style['version'];
            ?>
><?php 
            echo $version;
            ?>
</td>
			<td class="vers column-rating"<?php 
            echo $style['rating'];
            ?>
>
				<?php 
            global $wp_version;
            if (version_compare($wp_version, "3.4", "<")) {
                ?>
				<div class="star-holder" title="<?php 
                printf(_n('(based on %s rating)', '(based on %s ratings)', $plugin['num_ratings'], 'installer'), number_format_i18n(intval($plugin['num_ratings'])));
                ?>
">
					<div class="star star-rating" style="width: <?php 
                echo esc_attr($plugin['rating']);
                ?>
px"></div>
					<?php 
                $color = get_user_option('admin_color');
                if (empty($color) || 'fresh' == $color) {
                    $star_url = admin_url('images/gray-star.png?v=20110615');
                } else {
                    $star_url = admin_url('images/star.png?v=20110615');
                }
                // 'Classic' Blue star
                ?>
					<div class="star star5"><img src="<?php 
                echo $star_url;
                ?>
" alt="<?php 
                esc_attr_e('5 stars');
                ?>
" /></div>
					<div class="star star4"><img src="<?php 
                echo $star_url;
                ?>
" alt="<?php 
                esc_attr_e('4 stars');
                ?>
" /></div>
					<div class="star star3"><img src="<?php 
                echo $star_url;
                ?>
" alt="<?php 
                esc_attr_e('3 stars');
                ?>
" /></div>
					<div class="star star2"><img src="<?php 
                echo $star_url;
                ?>
" alt="<?php 
                esc_attr_e('2 stars');
                ?>
" /></div>
					<div class="star star1"><img src="<?php 
                echo $star_url;
                ?>
" alt="<?php 
                esc_attr_e('1 star');
                ?>
" /></div>
				</div>
			<?php 
            } else {
                ?>
				<div class="star-holder" title="<?php 
                printf(_n('(based on %s rating)', '(based on %s ratings)', $plugin['num_ratings'], 'installer'), number_format_i18n(intval($plugin['num_ratings'])));
                ?>
">
					<div class="star star-rating" style="width: <?php 
                echo esc_attr(str_replace(',', '.', $plugin['rating']));
                ?>
px"></div>
				</div>
			<?php 
            }
            ?>
			</td>
			<td class="desc column-description"<?php 
            echo $style['description'];
            ?>
><?php 
            echo $description, $author;
            ?>
</td>
            <td class="source column-source" align="left"><?php 
            echo $plugin_source;
            ?>
</td>
            <td class="price column-price" align="left"><?php 
            echo $plugin_price;
            ?>
</td>
		</tr>
		<?php 
        }
    }
 function testLogin($repository_id, $username, $password, $plain = false)
 {
     //$rm = $this->repo_model;//WPRC_Loader::getModel('repositories');
     $repo = $this->getRepositoryByField('id', $repository_id);
     $body_array = array('action' => 'repository_login');
     $salt = $repo->repository_authsalt;
     //WPRC_Loader::includeSecurity();
     //$body_array['auth'] = array('user'=>$username,'pass'=>WPRC_Security::encrypt($salt,$password),'salt'=>$salt);
     $body_array['auth'] = array('user' => $username, 'pass' => $password, 'salt' => $salt);
     if ($plain) {
         $body_array['auth']['_plain'] = 'true';
     }
     // log
     if (!$plain) {
         $msg = sprintf('Repository Login to %s with auth, timeout: %d, action: %s', $repo->repository_endpoint_url, 5, $body_array['action']);
     } else {
         $msg = sprintf('Repository Login to %s with auth plain, timeout: %d, action: %s', $repo->repository_endpoint_url, 5, $body_array['action']);
     }
     WPRC_Functions::log($msg, 'controller', 'controller.log');
     $request = wp_remote_post($repo->repository_endpoint_url, array('timeout' => 15, 'body' => $body_array));
     // log
     $msg = sprintf('Repository Login to %s with auth, response: %s', $repo->repository_endpoint_url, print_r($request, true));
     WPRC_Functions::log($msg, 'controller', 'controller.log');
     if (is_wp_error($request)) {
         $res = new WP_Error('repository_login_failed', __('An unexpected HTTP Error occurred during the API request.', 'installer'), $request->get_error_message());
         // log
         $msg = sprintf('Repository Login to %s with auth, response error: %s', $repo->repository_endpoint_url, print_r($request->get_error_message()));
         WPRC_Functions::log($msg, 'controller', 'controller.log');
     } else {
         $request_body = wp_remote_retrieve_body($request);
         if (is_serialized($request_body)) {
             $res = @unserialize($request_body);
         }
     }
     if (!isset($res) || $res == false || is_wp_error($res)) {
         // log
         $msg = sprintf('Repository Login to %s with auth, response unserialize error: %s', $repo->repository_endpoint_url, print_r(wp_remote_retrieve_body($request)));
         WPRC_Functions::log($msg, 'controller', 'controller.log');
         return false;
     }
     if (isset($res->error) && !isset($res->success)) {
         $response = array('error' => 1, 'message' => $res->error);
     } else {
         $response = array('error' => 0, 'message' => $res->success);
         $doupdate = false;
         if ($plain && isset($res->pass) && $res->pass != '') {
             $password = $res->pass;
             $doupdate = true;
         }
         if (!$plain) {
             $doupdate = true;
         }
         if ($doupdate) {
             $this->updateRepositoryAuth($repository_id, $username, $password);
             // clear cache
             $rmcache = WPRC_Loader::getModel('cached-requests');
             $rmcache->cleanCache();
             // clear update data
             delete_site_transient('update_plugins');
             delete_site_transient('update_themes');
         }
     }
     return $response;
 }