Plugin Directory

Changeset 658221


Ignore:
Timestamp:
01/24/2013 06:47:45 PM (13 years ago)
Author:
voceplatforms
Message:

releasing version 1.2

Location:
lift-search/trunk
Files:
2 added
18 edited

Legend:

Unmodified
Added
Removed
  • lift-search/trunk/admin/setup.php

    r642501 r658221  
    2020                    <em>1</em> You will need an Amazon Web Services account, visit <a target="_blank" href="http://aws.amazon.com/">Amazon AWS</a>. <a href="http://aws.amazon.com/documentation/" class="button button-secondary" target="_blank">AWS Documentation</a>
    2121                </p>
    22                 <?php if ( ! $step_completed[4] ): ?>
     22                <?php if ( !$step_completed[4] ): ?>
    2323                    <br />
    2424                    <input type="button" value="Next" class="lift-next-step lift-step-button button-primary" data-lift_step="next" />
    2525                <?php endif; ?>
    2626            </div>
    27             <div class="lift-step lift-step-2 <?php echo ( ! $step_completed[4] ? 'hidden' : '' ); ?>">
     27            <div class="lift-step lift-step-2 <?php echo (!$step_completed[4] ? 'hidden' : '' ); ?>">
    2828                <p>
    2929                    <em>2</em> Add your account info. You can retrieve your access keys from the
     
    5858                    </tr>
    5959                </table>
    60                 <?php if ( ! $step_completed[4] ): ?>
     60                <?php if ( !$step_completed[4] ): ?>
    6161                    <br />
    6262                    <input type="button" value="Back" class="lift-prev-step lift-step-button button-primary" data-lift_step="prev"/>
     
    6464                <?php endif; ?>
    6565            </div>
    66             <div class="lift-step lift-step-3 <?php echo ( ! $step_completed[4] ? 'hidden' : '' ); ?>">
     66            <div class="lift-step lift-step-3 <?php echo (!$step_completed[4] ? 'hidden' : '' ); ?>">
    6767                <p><em>3</em> Please enter a search domain name. This must be a unique string to your AWS account. The domain name string can only contain the following characters: a-z (lowercase), 0-9, and - (hyphen). Uppercase letters and underscores are not allowed. The string has a max length of 28 characters.</p>
    6868                <table class="form-table">
     
    8585                    </tr>
    8686                </table>
    87                 <?php if ( ! $step_completed[4] ): ?>
     87                <?php if ( !$step_completed[4] ): ?>
    8888                    <br />
    8989                    <input type="button" value="Back" class="lift-prev-step lift-step-button button-primary" data-lift_step="prev"/>
     
    9191                <?php endif; ?>
    9292            </div>
    93             <div class="lift-step lift-step-4 <?php echo ( ! $step_completed[4] ? 'hidden' : '' ); ?>">
     93            <div class="lift-step lift-step-4 <?php echo (!$step_completed[4] ? 'hidden' : '' ); ?>">
    9494                <p>
    9595                    <em>4</em> Your search domain is ready to go! If this is a new search domain, it will take approximately 30-40 minutes for it to become active and ready to index your documents.
    9696                </p>
    9797                <p>
    98                     <?php if ( ! $step_completed[4] ): ?>
     98                    <?php if ( !$step_completed[4] ): ?>
    9999                        <input type="button" value="Back" class="lift-prev-step lift-step-button button-primary"data-lift_step="prev" />
    100100                    <?php endif; ?>
    101                     <a href="<?php echo admin_url( sprintf( 'options-general.php?page=%s', Lift_Search::ADMIN_STATUS_PAGE ) ); ?>" class="lift-admin-panel<?php echo ($step_completed[4] ? '-initial-completed' : ''); ?> button-primary">View Lift Search Dashboard</a>
     101                    <a href="<?php echo admin_url( sprintf( 'options-general.php?page=%s', Lift_Admin::STATUS_PAGE ) ); ?>" class="lift-admin-panel<?php echo ($step_completed[4] ? '-initial-completed' : ''); ?> button-primary">View Lift Search Dashboard</a>
    102102                </p>
    103103            </div>
  • lift-search/trunk/admin/status.php

    r642501 r658221  
    11<?php
    2 
    3 $cron_enabled = Lift_Batch_Queue::cron_enabled();
     2$cron_enabled = Lift_Batch_Handler::cron_enabled();
    43$status = Lift_Health::get_overall_status();
    54
     
    87
    98if ( 1 == $status['severity'] ) {
    10     $overall_status_text = 'Warning';
    11     $overall_status_class = 'caution';
     9    $overall_status_text = 'Warning';
     10    $overall_status_class = 'caution';
    1211} else if ( 2 == $status['severity'] ) {
    13     $overall_status_text = 'Critical';
    14     $overall_status_class = 'error';
     12    $overall_status_text = 'Critical';
     13    $overall_status_class = 'error';
    1514}
    1615
    1716$overall_status_reasons = $status['reason'];
    18 $remote_domain_status = ( isset( $status['remote_status'] ) ) ? $status['remote_status'] : false ;
     17$remote_domain_status = ( isset( $status['remote_status'] ) ) ? $status['remote_status'] : false;
    1918
    20 if ( ! isset( $remote_domain_status['fatal'] ) ) {
    21     $remote_document_text = ( 1 != $status['remote_status']['num_searchable_docs'] ) ? 'documents' : 'document';
    22     $remote_partition_text = ( 1 != $status['remote_status']['search_partition_count'] ) ? 'partitions' : 'partition';
    23     $remote_instance_text = ( 1 != $status['remote_status']['search_instance_count'] ) ? 'instances' : 'instance';
     19if ( !isset( $remote_domain_status['fatal'] ) ) {
     20    $remote_document_text = ( 1 != $status['remote_status']['num_searchable_docs'] ) ? 'documents' : 'document';
     21    $remote_partition_text = ( 1 != $status['remote_status']['search_partition_count'] ) ? 'partitions' : 'partition';
     22    $remote_instance_text = ( 1 != $status['remote_status']['search_instance_count'] ) ? 'instances' : 'instance';
    2423}
    2524
    2625$remote_domain_status_text = $remote_domain_status['text'];
    2726$domain = Lift_Search::get_search_domain();
     27
     28$batch_interval_display = Lift_Search::get_batch_interval_display();
    2829
    2930?>
     
    3536                <td class="status <?php echo esc_attr( $overall_status_class ); ?>">
    3637                    <h3><?php echo esc_html( $overall_status_text ); ?></h3>
    37                     <?php if ( $overall_status_reasons ) : ?>
    38                         <ul>
    39                         <?php foreach ( $overall_status_reasons as $reason ) : ?>
    40                             <li><?php echo esc_html( $reason ); ?></li>
    41                         <?php endforeach; ?>
    42                         </ul>
    43                     <?php endif; ?>
     38                    <?php if ( $overall_status_reasons ) : ?>
     39                        <ul>
     40                            <?php foreach ( $overall_status_reasons as $reason ) : ?>
     41                                <li><?php echo esc_html( $reason ); ?></li>
     42                            <?php endforeach; ?>
     43                        </ul>
     44                    <?php endif; ?>
    4445                    <p><a href="#lift-logs">view logs below</a></p>
    4546                </td>
     
    5051                                <td>Last: </td>
    5152                                <td>
    52                                     <strong id="last-cron"><?php echo esc_html(Lift_Batch_Queue::get_last_cron_time()); ?></strong>
     53                                    <strong id="last-cron"><?php echo esc_html( Lift_Batch_Handler::get_last_cron_time() ); ?></strong>
    5354                                </td>
    5455                            </tr>
     
    5657                                <td>Next: </td>
    5758                                <td>
    58                                     <strong id="next-cron"><?php echo esc_html(Lift_Batch_Queue::get_next_cron_time()); ?></strong>
     59                                    <strong id="next-cron"><?php echo esc_html( Lift_Batch_Handler::get_next_cron_time() ); ?></strong>
    5960                                </td>
    6061                            </tr>
     
    7172                        <div class="clr"></div>
    7273                        <div class="lift-index-now">
    73                             <form method="get" action="">
    74                                 <input type="hidden" name="page" value="<?php echo esc_attr( Lift_Search::ADMIN_STATUS_PAGE ); ?>">
    75                                 <input type="hidden" name="sync-queue" value="1">
    76                                 <button class="button-primary" <?php echo ( Lift_Batch_Queue::is_batch_locked() || ! Lift_Batch_Queue::ready_for_batch( Lift_Search::get_search_domain() ) ) ? 'disabled' : ''; ?>>Sync Queue Now</button>
    77                             </form>
     74                            <form method="get" action="">
     75                                <input type="hidden" name="page" value="<?php echo esc_attr( Lift_Admin::STATUS_PAGE ); ?>">
     76                                <input type="hidden" name="sync-queue" value="1">
     77                                <button class="button-primary" <?php echo ( Lift_Batch_Handler::is_batch_locked() || !Lift_Batch_Handler::ready_for_batch( Lift_Search::get_search_domain() ) ) ? 'disabled' : ''; ?>>Sync Queue Now</button>
     78                            </form>
    7879                        </div>
    7980                        <div class="clr"></div>
     
    8384                        <div class="alignleft">
    8485                            <div class="misc-pub-section alignleft">
    85                                 <input name="batch-interval" id="lift-search-settings-page-search-config-settings-batch-interval" class="regular-text cron-update" value="<?php echo Lift_Search::get_batch_interval_adjusted(); ?>" type="text">
     86                                <input name="batch-interval" id="lift-search-settings-page-search-config-settings-batch-interval" class="regular-text cron-update" value="<?php echo $batch_interval_display['value']; ?>" type="text">
    8687                                <select name="batch-interval-units" id="lift-search-settings-page-search-config-settings-batch-units">
    87                                     <option value="m" <?php selected( Lift_Search::get_batch_interval_unit(), 'm' ); ?>>Minutes</option>
    88                                     <option value="h" <?php selected( Lift_Search::get_batch_interval_unit(), 'h' ); ?>>Hours</option>
    89                                     <option value="d" <?php selected( Lift_Search::get_batch_interval_unit(), 'd' ); ?>>Days</option>
     88                                    <option value="m" <?php selected( $batch_interval_display['unit'], 'm' ); ?>>Minutes</option>
     89                                    <option value="h" <?php selected( $batch_interval_display['unit'], 'h' ); ?>>Hours</option>
     90                                    <option value="d" <?php selected( $batch_interval_display['unit'], 'd' ); ?>>Days</option>
    9091                                </select>
    9192                                <input type="button" id="update-cron-interval" value="Save" class="button button-secondary"/>
     
    9899                </td>
    99100                <td class="edit">
    100                     <a class="button" href="<?php echo admin_url( 'options-general.php?page=' . Lift_Search::ADMIN_LANDING_PAGE ); ?>">Settings</a>
     101                    <a class="button" href="<?php echo admin_url( 'options-general.php?page=' . Lift_Admin::LANDING_PAGE ); ?>">Settings</a>
    101102                    <div class="clr"></div>
    102103                    <br />
     
    105106            </tr>
    106107        </table>
    107        
    108         <div id="lift-remote-status">
    109             <p>
    110                 Amazon CloudSearch search domain status for <i><?php echo esc_html( $domain ); ?></i>:
    111                 <b><?php echo esc_html( strtoupper( $remote_domain_status_text ) ); ?></b><?php if ( $remote_domain_status && ! ( isset( $remote_domain_status['fatal'] ) ) && $remote_domain_status['needs_indexing'] ) : ?>
    112                 <a href="<?php echo admin_url( 'options-general.php?page=' . Lift_Search::ADMIN_STATUS_PAGE . '&lift-indexdocuments' ); ?>" class="button">Index Now</a><?php endif; ?>.
    113                 <?php if ( ! isset( $remote_domain_status['fatal'] ) ) : ?>
    114                         Your index has <?php echo esc_html( $remote_domain_status['num_searchable_docs'] ); ?> searchable <?php echo $remote_document_text; ?>
    115                         using <?php echo esc_html( $remote_domain_status['search_partition_count'] ); ?> search <?php echo $remote_partition_text; ?>
    116                         served by <?php echo esc_html( $remote_domain_status['search_instance_count'] ); ?> <i><?php echo esc_html( $remote_domain_status['search_instance_type'] ); ?></i> <?php echo $remote_instance_text; ?>.
    117                 <?php endif; ?>
    118             </p>
    119         </div>
    120        
    121         <div class="indent">
    122             <h3><span class="alignright">Documents in Queue: <strong><?php echo number_format( Lift_Batch_Queue::get_queue_count() ); ?></strong></span>Documents to be Synced</h3>
    123             <?php echo Lift_Batch_Queue::get_queue_list(); ?>           
    124             <h3 class="alignleft" id="lift-logs">Recent Logs</h3>
    125             <p class="alignleft" style="padding-top:3px ;margin-left:15px;">
    126                 <a href="<?php echo esc_attr( admin_url( sprintf( 'edit.php?post_type=%s', Voce_Error_Logging::POST_TYPE ) ) ); ?>" class="alignleft">View All</a>
     108
     109        <div id="lift-remote-status">
     110            <p>
     111                Amazon CloudSearch search domain status for <i><?php echo esc_html( $domain ); ?></i>:
     112                <b><?php echo esc_html( strtoupper( $remote_domain_status_text ) ); ?></b>
     113                <?php if ( $remote_domain_status && !( isset( $remote_domain_status['fatal'] ) ) && $remote_domain_status['needs_indexing'] ) : ?>
     114                    <a href="<?php echo admin_url( 'options-general.php?page=' . Lift_Admin::STATUS_PAGE . '&lift-indexdocuments' ); ?>" class="button">Index Now</a>
     115                <?php endif; ?>.
     116                <?php if ( !isset( $remote_domain_status['fatal'] ) ) : ?>
     117                    Your index has <?php echo esc_html( $remote_domain_status['num_searchable_docs'] ); ?> searchable <?php echo $remote_document_text; ?>
     118                    using <?php echo esc_html( $remote_domain_status['search_partition_count'] ); ?> search <?php echo $remote_partition_text; ?>
     119                    served by <?php echo esc_html( $remote_domain_status['search_instance_count'] ); ?> <i><?php echo esc_html( $remote_domain_status['search_instance_type'] ); ?></i> <?php echo $remote_instance_text; ?>.
     120                <?php endif; ?>
    127121            </p>
    128             <?php if ( Voce_Error_Logging::get_log_count() && Voce_Error_Logging::get_log_count() > 0 ): ?>
    129                 <div class="alignright" style="margin-bottom:5px;"><p>
    130                         <span class="alignleft status-message" id="clear-log-status-message" style="padding-top:3px; margin-right:15px;"></span>
    131                         <img id="clear-logs-loader" style="padding-top:3px; margin-right:15px;" src="<?php echo site_url( '/wp-admin/images/loading.gif' ); ?>" class="alignleft hidden"/>
    132                         <input type="button" class="button alignright" id="voce-lift-admin-settings-clear-status-logs" value="Clear Logs" />
    133                     </p></div>
     122        </div>
     123
     124        <div class="indent">
     125            <?php echo Lift_Batch_Handler::get_queue_list(); ?>
     126            <?php if(Lift_Search::error_logging_enabled()) : ?>
     127                <h3 class="alignleft" id="lift-logs">Recent Logs</h3>
     128                <p class="alignleft" style="padding-top:3px ;margin-left:15px;">
     129                    <a href="<?php echo esc_attr( admin_url( sprintf( 'edit.php?post_type=%s', Voce_Error_Logging::POST_TYPE ) ) ); ?>" class="alignleft">View All</a>
     130                </p>
     131                <?php if ( Voce_Error_Logging::get_log_count() && Voce_Error_Logging::get_log_count() > 0 ): ?>
     132                    <div class="alignright" style="margin-bottom:5px;">
     133                        <p>
     134                            <span class="alignleft status-message" id="clear-log-status-message" style="padding-top:3px; margin-right:15px;"></span>
     135                            <img id="clear-logs-loader" style="padding-top:3px; margin-right:15px;" src="<?php echo site_url( '/wp-admin/images/loading.gif' ); ?>" class="alignleft hidden"/>
     136                            <input type="button" class="button alignright" id="voce-lift-admin-settings-clear-status-logs" value="Clear Logs" />
     137                        </p>
     138                    </div>
     139                <?php endif; ?>
     140                <?php echo Lift_Search::RecentLogTable(); ?>
    134141            <?php endif; ?>
    135             <?php echo Lift_Search::RecentLogTable(); ?>
    136142        </div><!-- end indent -->
    137143    </div> <!-- end dashboard -->
  • lift-search/trunk/api/cloud-api.php

    r627882 r658221  
    33class Cloud_API {
    44
    5     private $search_version;
    65    private $error_messages;
    76    private $submission_uri;
    87    private $search_uri;
     8
    99    const API_VERSION = '2011-02-01';
    1010
     
    2020     * @param iLift_HTTP $http_interface
    2121     */
    22     public function __construct($http_interface, $document_endpoint, $search_endpoint, $version = '2011-02-01') {
     22    public function __construct( $http_interface, $document_endpoint, $search_endpoint, $version = '2011-02-01' ) {
    2323
    2424        $this->http_interface = $http_interface;
    2525
    2626        $this->submission_uri = sprintf( 'http://%s/%s/documents/batch', $document_endpoint, $version );
    27         $this->search_uri     = sprintf( 'http://%s/%s/search?', $search_endpoint, $version );
     27        $this->search_uri = sprintf( 'http://%s/%s/search?', $search_endpoint, $version );
    2828    }
    2929
    30     private function send($method = 'POST', $data = null) {
     30    private function send( $method = 'POST', $data = null ) {
    3131
    32         $method = strtoupper($method);
     32        $method = strtoupper( $method );
    3333
    3434        // only use JSON for now
    3535        $headers = array(
    3636            'Content-Type' => 'application/json',
    37             'Accept'       => 'application/json'
     37            'Accept' => 'application/json'
    3838        );
    3939
    40         switch ($method) {
     40        switch ( $method ) {
    4141
    4242            case 'POST':
     
    4949
    5050            default:
    51                 throw new Exception('you did it wrong');
     51                throw new Exception( 'you did it wrong' );
     52        }
    5253
     54        $json = json_decode( $response );
     55
     56        if ( !$json ) {
     57            $this->error_messages = $response;
    5358        }
    54        
    55         $json = json_decode( $response );
    56        
    57         if ( ! $json ) {
    58             $this->error_messages = $response;
    59         }
    6059
    6160        return $json;
    62 
    6361    }
    6462
     
    6765     * @param Cloud_Search_Query $query
    6866     */
    69     public function sendSearch($query) {
    70         $response = $this->send('GET', $query->get_query_string());
     67    public function sendSearch( $query ) {
     68        $response = $this->send( 'GET', $query->get_query_string() );
    7169
    7270        if ( $response && property_exists( $response, 'error' ) ) {
     
    7573        }
    7674
    77         if( in_array( $this->http_interface->getStatusCode(), array( 200, 201, 204 ) ) ) {
     75        if ( in_array( $this->http_interface->getStatusCode(), array( 200, 201, 204 ) ) ) {
    7876            return $response;
    7977        }
    8078
    8179        return false;
    82 
    8380    }
    8481
     
    8784     * @param LiftBatch $batch
    8885     */
    89     public function sendBatch($batch) {
     86    public function sendBatch( $batch ) {
    9087
    91         $response = $this->send('POST', $batch->convert_to_JSON());
     88        $response = $this->send( 'POST', $batch->convert_to_JSON() );
    9289
    9390        if ( $response && ( 'error' === $response->status ) ) {
     
    106103        return $this->error_messages;
    107104    }
     105
    108106}
  • lift-search/trunk/api/cloud-config.php

    r642501 r658221  
    1313        $this->operation = $operation;
    1414        $this->payload = $payload;
    15         $this->key = $credentials['access-key-id'];
    16         $this->secret_key = $credentials['secret-access-key'];
     15        $this->key = $credentials['access-key-id'];
     16        $this->secret_key = $credentials['secret-access-key'];
    1717        $this->http_api = $api;
    1818    }
     
    2121        $temp = array( );
    2222
    23         foreach ($array as $key => $value) {
     23        foreach ( $array as $key => $value ) {
    2424            if ( is_string( $key ) && !is_array( $value ) ) {
    2525                $temp[] = rawurlencode( $key ) . '=' . rawurlencode( $value );
     
    7171
    7272        // Add headers to request and compute the string to sign
    73         foreach ($this->headers as $header_key => $header_value) {
     73        foreach ( $this->headers as $header_key => $header_value ) {
    7474            // Strip line breaks and remove consecutive spaces. Services collapse whitespace in signature calculation
    7575            $this->headers[$header_key] = preg_replace( '/\s+/', ' ', trim( $header_value ) );
     
    8989        $raw = '';
    9090
    91         for ($i = 0; $i < strlen( $str ); $i += 2) {
     91        for ( $i = 0; $i < strlen( $str ); $i += 2 ) {
    9292            $raw .= chr( hexdec( substr( $str, $i, 2 ) ) );
    9393        }
     
    112112        $t = array( );
    113113
    114         foreach ($array as $k => $v) {
    115             if ( is_array($v) ) {
    116                 // json encode value if it is an array
    117                 $value = $this->encode_signature2( json_encode( $v ) );
    118             } else {
    119                 $value = $this->encode_signature2( $v );
    120             }
     114        foreach ( $array as $k => $v ) {
     115            if ( is_array( $v ) ) {
     116                // json encode value if it is an array
     117                $value = $this->encode_signature2( json_encode( $v ) );
     118            } else {
     119                $value = $this->encode_signature2( $v );
     120            }
    121121            $t[] = $this->encode_signature2( $k ) . '=' . $value;
    122122        }
     
    230230    protected static function __flatten_keys( $array, $prefix = '' ) {
    231231
    232         $result = array();
    233 
    234         foreach( $array as $key => $value ) {
     232        $result = array( );
     233
     234        foreach ( $array as $key => $value ) {
    235235
    236236            if ( is_array( $value ) ) {
    237237
    238238                $result += self::__flatten_keys( $value, ( $prefix . $key . '.' ) );
    239 
    240239            } else {
    241240
    242241                $result[$prefix . $key] = $value;
    243 
    244             }
    245 
     242            }
    246243        }
    247244
    248245        return $result;
    249 
    250246    }
    251247
     
    257253     * @return array [response string, Cloud_Config object used for request]
    258254     */
    259     protected static function __make_request( $method, $payload = array(), $credentials = null, $flatten_keys = true ) {
     255    protected static function __make_request( $method, $payload = array( ), $credentials = null, $flatten_keys = true ) {
    260256
    261257        if ( $payload && $flatten_keys ) {
    262258
    263259            $payload = self::__flatten_keys( $payload );
    264 
    265         }
    266        
    267         if ( ! $credentials ) {
     260        }
     261
     262        if ( !$credentials ) {
    268263            $credentials['access-key-id'] = Lift_Search::get_access_key_id();
    269264            $credentials['secret-access-key'] = Lift_Search::get_secret_access_key();
    270265        }
    271        
    272         $api = Lift_Search::get_http_api();
    273 
    274         $config = new Cloud_Config( $credentials, $api, $method, $payload);
     266
     267        $api = Lift_Search::get_http_api();
     268
     269        $config = new Cloud_Config( $credentials, $api, $method, $payload );
    275270
    276271        $r = $config->authenticate();
     
    281276
    282277            if ( isset( $r_json->Error ) ) {
    283                
    284                 self::SetLastError( $r_json );
     278
     279                self::SetLastError( $r_json );
    285280
    286281                return false;
    287 
    288             }
    289 
    290         }
    291 
    292         return array($r, $config);
    293 
     282            }
     283        }
     284
     285        return array( $r, $config );
    294286    }
    295287
     
    298290     * @return boolean
    299291     */
    300     public static function GetDomains( $domain_names = array() ) {
    301 
    302         $payload = array();
    303 
    304         if ( ! empty( $domain_names ) ) {
    305 
    306             foreach (array_values($domain_names) as $i => $domain_name) {
     292    public static function GetDomains( $domain_names = array( ) ) {
     293
     294        $payload = array( );
     295
     296        if ( !empty( $domain_names ) ) {
     297
     298            foreach ( array_values( $domain_names ) as $i => $domain_name ) {
    307299                $payload['DomainNames.member.' . ($i + 1)] = $domain_name;
    308300            }
    309 
    310301        }
    311302
     
    313304
    314305        return ( $r ? json_decode( $r ) : false );
    315 
    316306    }
    317307
     
    324314     */
    325315    public static function TestDomain( $domain_name ) {
    326         $domains = self::GetDomains(array($domain_name));
     316        $domains = self::GetDomains( array( $domain_name ) );
    327317        if ( $domains ) {
    328318            $ds = $domains->DescribeDomainsResponse->DescribeDomainsResult->DomainStatusList;
     
    331321        return false;
    332322    }
    333    
     323
    334324    /**
    335325     * @method CreateDomain
     
    339329
    340330        list($r, $config) = self::__make_request( 'CreateDomain', array( 'DomainName' => $domain_name ) );
    341        
     331
    342332        return ( $r ? json_decode( $r ) : false );
    343 
    344333    }
    345334
     
    381370        return false;
    382371    }
    383    
    384     public static function DescribeDomain( $domain_name ) {
    385         $domains = self::GetDomains(  array($domain_name) );
     372
     373    public static function DescribeDomain( $domain_name ) {
     374        $domains = self::GetDomains( array( $domain_name ) );
    386375        if ( $domains ) {
    387376            $d = $domains->DescribeDomainsResponse->DescribeDomainsResult->DomainStatusList;
     
    390379                return $d[0];
    391380            } else {
    392                 return false;
    393             }
    394         }
    395         return false;
    396     }
    397    
    398     public static function DescribeServiceAccessPolicies( $domain_name ) {
    399         list($r, $config) = self::__make_request( 'DescribeServiceAccessPolicies', array( 'DomainName' => $domain_name ) );
     381                return false;
     382            }
     383        }
     384        return false;
     385    }
     386
     387    public static function DescribeServiceAccessPolicies( $domain_name ) {
     388        list($r, $config) = self::__make_request( 'DescribeServiceAccessPolicies', array( 'DomainName' => $domain_name ) );
    400389
    401390        return ( $r ? json_decode( $r ) : false );
    402     }
    403    
    404     /**
     391    }
     392
     393    /**
    405394     * Retrieve Search Service endpoint for a domain
    406395     *
     
    414403            return $domain->SearchService;
    415404        }
    416        
    417         return false;
    418     }
    419    
    420     /**
     405
     406        return false;
     407    }
     408
     409    /**
    421410     * Retrieve Doc Service endpoint for a domain
    422411     *
     
    430419            return $domain->DocService;
    431420        }
    432        
     421
    433422        return false;
    434423    }
     
    445434
    446435        $payload = array(
    447             'DomainName'     => $domain,
     436            'DomainName' => $domain,
    448437            'RankExpression' => array(
    449                 'RankName'       => $rank_name,
     438                'RankName' => $rank_name,
    450439                'RankExpression' => $rank_expression
    451440            )
     
    461450
    462451                return true;
    463 
    464             }
    465 
    466         }
    467 
    468         return false;
    469 
     452            }
     453        }
     454
     455        return false;
    470456    }
    471457
     
    481467        $payload = array(
    482468            'DomainName' => $domain,
    483             'RankName'   => $rank_name,
     469            'RankName' => $rank_name,
    484470        );
    485471
     
    493479
    494480                return true;
    495 
    496             }
    497 
    498         }
    499 
    500         return false;
    501 
    502     }
    503    
    504     /**
    505      * get a default service access policy. try to be restrictive and use
    506      * the outbound ip/32 and fall back to allow everyone if it can't be determined
    507      *
    508      * @param string $domain
    509      * @return boolean|array
    510      */
    511     public static function GetDefaultServiceAccessPolicy( $domain ) {
    512         $search_service = self::SearchService( $domain );
    513         $doc_service = self::DocService( $domain );
    514      
    515         $services = array($search_service, $doc_service);
    516         $statement = array();
    517         $net = '0.0.0.0/0';
    518         $warn = true; // for future error handling to warn of wide open access
    519        
    520         // try to get the IP address external services see to be more restrictive
    521         if ( $ip = Lift_Search::get_http_api()->get( 'http://ifconfig.me/ip' ) ) {
    522             $net = sprintf( '%s/32', str_replace( "\n", '', $ip) );
    523             $warn = false;
    524         }
    525        
    526         foreach ($services as $service) {
    527             if ($service) {
    528                 $statement[] = array(
    529                     'Effect' => 'Allow',
    530                     'Action' => '*',
    531                     'Resource' => $service->Arn,
    532                     'Condition' => array(
    533                         'IpAddress' => array(
    534                             'aws:SourceIp' => array($net),
    535                         )
    536                     )
    537                 );
    538             }
    539         }
    540        
    541         if ( ! $statement ) {
    542             return false;
    543         }
    544        
    545         $policies = array('Statement' => $statement);
    546        
    547         return $policies;
    548     }
    549    
    550     /**
    551      * call UpdateServiceAccessPolicies for the domain with the given policies
    552      *
    553      * @param string $domain
    554      * @param array $policies
    555      * @return boolean
    556      */
    557     public static function UpdateServiceAccessPolicies( $domain, $policies ) {
    558        
    559         if ( ! $policies ) {
    560             return false;
    561         }
    562        
    563         $payload = array(
    564             'AccessPolicies' => $policies,
    565             'DomainName' => $domain,
    566         );
    567 
    568         list($r, $config) = self::__make_request( 'UpdateServiceAccessPolicies', $payload, null, false );
     481            }
     482        }
     483
     484        return false;
     485    }
     486
     487    /**
     488     * get a default service access policy. try to be restrictive and use
     489     * the outbound ip/32 and fall back to allow everyone if it can't be determined
     490     *
     491     * @param string $domain
     492     * @return boolean|array
     493     */
     494    public static function GetDefaultServiceAccessPolicy( $domain ) {
     495        $search_service = self::SearchService( $domain );
     496        $doc_service = self::DocService( $domain );
     497
     498        $services = array( $search_service, $doc_service );
     499        $statement = array( );
     500        $net = '0.0.0.0/0';
     501        $warn = true; // for future error handling to warn of wide open access
     502        // try to get the IP address external services see to be more restrictive
     503        if ( $ip = Lift_Search::get_http_api()->get( 'http://ifconfig.me/ip' ) ) {
     504            $net = sprintf( '%s/32', str_replace( "\n", '', $ip ) );
     505            $warn = false;
     506        }
     507
     508        foreach ( $services as $service ) {
     509            if ( $service ) {
     510                $statement[] = array(
     511                    'Effect' => 'Allow',
     512                    'Action' => '*',
     513                    'Resource' => $service->Arn,
     514                    'Condition' => array(
     515                        'IpAddress' => array(
     516                            'aws:SourceIp' => array( $net ),
     517                        )
     518                    )
     519                );
     520            }
     521        }
     522
     523        if ( !$statement ) {
     524            return false;
     525        }
     526
     527        $policies = array( 'Statement' => $statement );
     528
     529        return $policies;
     530    }
     531
     532    /**
     533     * call UpdateServiceAccessPolicies for the domain with the given policies
     534     *
     535     * @param string $domain
     536     * @param array $policies
     537     * @return boolean
     538     */
     539    public static function UpdateServiceAccessPolicies( $domain, $policies ) {
     540
     541        if ( !$policies ) {
     542            return false;
     543        }
     544
     545        $payload = array(
     546            'AccessPolicies' => $policies,
     547            'DomainName' => $domain,
     548        );
     549
     550        list($r, $config) = self::__make_request( 'UpdateServiceAccessPolicies', $payload, null, false );
    569551
    570552        if ( $r ) {
     
    574556                self::SetLastError( $r );
    575557            } else if ( isset( $r->UpdateServiceAccessPoliciesResponse->UpdateServiceAccessPoliciesResult->AccessPolicies ) ) {
    576                 $policies = $r->UpdateServiceAccessPoliciesResponse->UpdateServiceAccessPoliciesResult->AccessPolicies;
    577                 if ( ! $options = json_decode( $policies->Options ) || 'Processing' != $policies->Status->State ) {
    578                     // $policies->Options will be blank if there was a malformed request
    579                     return false;
    580                 }
    581                
     558                $policies = $r->UpdateServiceAccessPoliciesResponse->UpdateServiceAccessPoliciesResult->AccessPolicies;
     559                if ( !$options = json_decode( $policies->Options ) || 'Processing' != $policies->Status->State ) {
     560                    // $policies->Options will be blank if there was a malformed request
     561                    return false;
     562                }
     563
    582564                return true;
    583565            }
     
    585567
    586568        return false;
    587     }
    588    
    589     /**
     569    }
     570
     571    /**
    590572     * @method IndexDocuments
    591573     * @param string $domain_name
    592     *
    593     * @return bool true if request completed and documents will be/are being
    594     * indexed or false if request could not be completed or domain was in a
    595     * status that documents could not be indexed
     574    *
     575    * @return bool true if request completed and documents will be/are being
     576    * indexed or false if request could not be completed or domain was in a
     577    * status that documents could not be indexed
    596578     */
    597579    public static function IndexDocuments( $domain_name ) {
     
    599581        list($r, $config) = self::__make_request( 'IndexDocuments', array( 'DomainName' => $domain_name ) );
    600582
    601         return ( isset( $config->status_code ) && 200 == $config->status_code ) ;
    602 
    603     }
    604 
    605     public static function __parse_index_options( $field_type, $passed_options = array() ) {
     583        return ( isset( $config->status_code ) && 200 == $config->status_code );
     584    }
     585
     586    public static function __parse_index_options( $field_type, $passed_options = array( ) ) {
    606587
    607588        $field_types = array(
     
    610591                'options' => array(
    611592                    'default' => array(
    612                         'name'    => 'DefaultValue',
     593                        'name' => 'DefaultValue',
    613594                        'default' => null
    614595                    )
     
    619600                'options' => array(
    620601                    'default' => array(
    621                         'name'    => 'DefaultValue',
     602                        'name' => 'DefaultValue',
    622603                        'default' => null
    623604                    ),
    624                     'facet'   => array(
    625                         'name'    => 'FacetEnabled',
     605                    'facet' => array(
     606                        'name' => 'FacetEnabled',
    626607                        'default' => 'false'
    627608                    ),
    628                     'result'  => array(
    629                         'name'    => 'ResultEnabled',
     609                    'result' => array(
     610                        'name' => 'ResultEnabled',
    630611                        'default' => 'false'
    631612                    )
     
    636617                'options' => array(
    637618                    'default' => array(
    638                         'name'    => 'DefaultValue',
     619                        'name' => 'DefaultValue',
    639620                        'default' => null
    640621                    ),
    641                     'facet'   => array(
    642                         'name'    => 'FacetEnabled',
     622                    'facet' => array(
     623                        'name' => 'FacetEnabled',
    643624                        'default' => 'false'
    644625                    ),
    645                     'result'  => array(
    646                         'name'    => 'ResultEnabled',
     626                    'result' => array(
     627                        'name' => 'ResultEnabled',
    647628                        'default' => 'false'
    648629                    ),
    649                     'search'  => array(
    650                         'name'    => 'SearchEnabled',
     630                    'search' => array(
     631                        'name' => 'SearchEnabled',
    651632                        'default' => 'false'
    652633                    )
     
    656637
    657638        $index_option_name = $field_types[$field_type]['option_name'];
    658         $index_options = array();
     639        $index_options = array( );
    659640
    660641        foreach ( $field_types[$field_type]['options'] as $option_key => $option_info ) {
    661642
    662             $option_name  = $option_info['name'];
     643            $option_name = $option_info['name'];
    663644            $option_value = $option_info['default'];
    664645
     
    666647
    667648                $option_value = $passed_options[$option_key];
    668 
    669             }
    670 
    671             if ( ! is_null( $option_value ) ) {
     649            }
     650
     651            if ( !is_null( $option_value ) ) {
    672652
    673653                $index_options[$option_name] = $option_value;
    674 
    675             }
    676 
     654            }
    677655        }
    678656
    679657        return array( $index_option_name => $index_options );
    680 
    681658    }
    682659
     
    690667     * @return bool
    691668     */
    692     public static function DefineIndexField( $domain, $field_name, $field_type, $options = array() ) {
     669    public static function DefineIndexField( $domain, $field_name, $field_type, $options = array( ) ) {
    693670
    694671        // @TODO: check valid domain format
     
    697674        // @TODO: check text field isn't both "facet" and "result"
    698675
    699         if ( ! in_array( $field_type, array( 'uint', 'text', 'literal' ) ) ) {
     676        if ( !in_array( $field_type, array( 'uint', 'text', 'literal' ) ) ) {
    700677
    701678            return false;
    702 
    703679        }
    704680
     
    722698
    723699                self::SetLastError( $r );
    724 
    725700            } else if ( isset( $r->DefineIndexFieldResponse->DefineIndexFieldResult->IndexField ) ) {
    726701
    727702                return true;
    728 
    729             }
    730 
    731         }
    732 
    733         return false;
    734 
    735 
     703            }
     704        }
     705
     706        return false;
    736707    }
    737708
     
    743714     * @return boolean True if a position response
    744715     */
    745     public static function TestConnection( $credentials = array() ) {
    746 
    747         list($r, $config) = self::__make_request( 'DescribeDomains', array(), $credentials );
    748 
    749         if ( ! $config ) {
    750             return false;
    751         }
    752        
     716    public static function TestConnection( $credentials = array( ) ) {
     717
     718        list($r, $config) = self::__make_request( 'DescribeDomains', array( ), $credentials );
     719
     720        if ( !$config ) {
     721            return false;
     722        }
     723
    753724        return ( 200 == $config->status_code );
    754 
    755725    }
    756726
     
    766736        $schema = Cloud_Schemas::GetSchema( $schema );
    767737
    768         if ( ! $schema ) {
     738        if ( !$schema ) {
    769739            return false;
    770740        }
     
    772742        foreach ( $schema as $index ) {
    773743
    774             $index = array_merge( array( 'options' => array() ), $index );
     744            $index = array_merge( array( 'options' => array( ) ), $index );
    775745
    776746            $r = self::DefineIndexField( $domain, $index['field_name'], $index['field_type'], $index['options'] );
     
    779749                return false;
    780750            }
    781 
    782751        }
    783752
    784753        return self::GetDomains( array( $domain ) );
    785 
    786     }
    787 
     754    }
    788755
    789756}
  • lift-search/trunk/api/cloud-schemas.php

    r627882 r658221  
    7777    );
    7878
    79     public static function GetSchema($schema){
     79    public static function GetSchema( $schema ) {
    8080        $schema = self::$$schema;
    81         if($schema){
     81        if ( $schema ) {
    8282            return $schema;
    8383        } else {
     
    8585        }
    8686    }
     87
    8788}
  • lift-search/trunk/api/cloud-search.php

    r627882 r658221  
    11<?php
     2
    23/*
    34
    4 Example usage:
     5  Example usage:
    56
    6 $query = new Cloud_Search_Query('post_content:"ratchet"');
     7  $query = new Cloud_Search_Query('post_content:"ratchet"');
    78
    8 $query->add_facet('post_category');
    9 $query->add_return_field('id');
    10 $query->add_rank('post_date_gmt', 'DESC');
     9  $query->add_facet('post_category');
     10  $query->add_return_field('id');
     11  $query->add_rank('post_date_gmt', 'DESC');
    1112
    12 $query_string = $query->get_query_string();
     13  $query_string = $query->get_query_string();
    1314
    14 */
    15 
     15 */
    1616
    1717class Cloud_Search_Query {
    1818
    19     protected $facets = array();
    20     protected $return_fields = array();
    21     protected $size  = 10;
     19    protected $facets = array( );
     20    protected $return_fields = array( );
     21    protected $size = 10;
    2222    protected $start = 0;
    2323    protected $boolean_query = '';
    24     protected $ranks = array();
     24    protected $ranks = array( );
    2525
    2626    public function __construct( $boolean_query = '' ) {
    27 
    2827        $this->boolean_query = $boolean_query;
    29 
    3028    }
    3129
    3230    public function set_boolean_query( $boolean_query ) {
    33 
    3431        $this->boolean_query = $boolean_query;
    35 
    3632    }
    3733
    3834    public function add_facet( $facet ) {
    39 
    40         $this->facets = array_merge( $this->facets, (array) $facet );
    41 
     35        $this->facets = array_merge( $this->facets, ( array ) $facet );
    4236    }
    4337
    4438    public function add_return_field( $field ) { // string or array
    45 
    46         $this->return_fields = array_merge( $this->return_fields, (array) $field );
    47 
     39        $this->return_fields = array_merge( $this->return_fields, ( array ) $field );
    4840    }
    4941
    5042    private function __validate_size( $size ) {
    51         if( (int)$size != $size || (int)$size < 0 ) {
     43        if ( ( int ) $size != $size || ( int ) $size < 0 ) {
    5244            throw new CloudSearchAPIException( 'Size must be a positive integer.', 2 );
    5345        }
     
    5547
    5648    public function set_size( $size = 10 ) {
    57        
    5849        $this->__validate_size( $size );
    59 
    6050        $this->size = $size;
    6151    }
    6252
    6353    private function __validate_start( $start ) {
    64         if( (int)$start != $start || (int)$start < 0 ) {
     54        if ( ( int ) $start != $start || ( int ) $start < 0 ) {
    6555            throw new CloudSearchAPIException( 'Start must be a positive integer', 1 );
    6656        }
     
    6858
    6959    public function set_start( $start ) {
    70 
    7160        $this->__validate_start( $start );
    72 
    7361        $this->start = $start;
    74 
    7562    }
    7663
    7764    public function add_rank( $field, $order ) {
    78 
    79         $order = ('DESC' === strtoupper($order)) ? 'DESC' : 'ASC';
    80 
     65        $order = ('DESC' === strtoupper( $order )) ? 'DESC' : 'ASC';
    8166        $this->ranks[$field] = $order;
    82 
    8367    }
    8468
    8569    public function get_query_string() {
     70        $ranks = array( );
    8671
    87         $ranks = array();
    88         foreach ($this->ranks as $field => $order) {
     72        foreach ( $this->ranks as $field => $order ) {
    8973            $ranks[] = ('DESC' === $order) ? "-{$field}" : $field;
    9074        }
    9175
    92         $params = array_filter(array(
    93             'bq'            => $this->boolean_query,
    94             'facet'         => implode(',', $this->facets),
    95             'return-fields' => implode(',', $this->return_fields),
    96             'size'          => $this->size,
    97             'start'         => $this->start,
    98             'rank'          => implode(',', $ranks)
    99         ));
     76        $params = array_filter( array(
     77            'bq' => $this->boolean_query,
     78            'facet' => implode( ',', $this->facets ),
     79            'return-fields' => implode( ',', $this->return_fields ),
     80            'size' => $this->size,
     81            'start' => $this->start,
     82            'rank' => implode( ',', $ranks )
     83            ) );
    10084
    10185        return http_build_query( $params );
    102 
    10386    }
    10487
     
    10689
    10790class CloudSearchAPIException extends Exception {
    108 
     91   
    10992}
  • lift-search/trunk/api/lift-batch.php

    r642501 r658221  
    5151            // pass
    5252        } else {
    53             $this->errors[] = array(
    54                 'code' => 100,
    55                 'message' => 'Tried to pass an invalid data type to constructor',
    56             );
     53            $this->errors[] = array(
     54                'code' => 100,
     55                'message' => 'Tried to pass an invalid data type to constructor',
     56            );
    5757            throw new Lift_Batch_Exception( $this->errors );
    5858        }
     
    6969        }
    7070
    71         foreach (array( 'type', 'id', 'version' ) as $prop) {
     71        foreach ( array( 'type', 'id', 'version' ) as $prop ) {
    7272            if ( !property_exists( $document, $prop ) ) {
    7373                $this->errors[] = array(
     
    7878            if ( empty( $document->{$prop} ) ) {
    7979                $this->errors[] = array(
    80                     'code' => 310,
     80                    'code' => 310,
    8181                    'message' => sprintf( 'Required field is empty: %s', $prop )
    8282                );
     
    9696     */
    9797    public function add_document( $document ) {
    98         $document = (object) $document;
     98        $document = ( object ) $document;
    9999        if ( !$this->can_add( $document ) ) {
    100100            throw new Lift_Batch_Exception( $this->errors );
     
    113113            if ( empty( $documents ) ) {
    114114                $this->errors[] = array(
    115                     'code' => 220,
    116                     'message' => 'Passed empty array'
    117                 );
     115                    'code' => 220,
     116                    'message' => 'Passed empty array'
     117                );
    118118                throw new Lift_Batch_Exception( $this->errors );
    119119            }
    120             for ($i = 0; $i < count( $documents ); $i++) {
     120            for ( $i = 0; $i < count( $documents ); $i++ ) {
    121121                try {
    122122                    $this->add_document( $documents[$i] );
    123123                } catch ( Lift_Batch_Exception $e ) {
    124124                    $this->errors[] = array(
    125                         'code' => 400,
     125                        'code' => 400,
    126126                        'message' => sprintf( 'Failed adding document at index %s', $i ),
    127127                        'failedIndex' => $i
     
    132132            return $this->documents;
    133133        } else {
    134             $this->errors[] = array(
    135                 'code' => 110,
    136                 'message' => sprintf( 'Expecting array, given: %s', gettype( $documents ) ),
    137             );
     134            $this->errors[] = array(
     135                'code' => 110,
     136                'message' => sprintf( 'Expecting array, given: %s', gettype( $documents ) ),
     137            );
    138138            throw new Lift_Batch_Exception( $this->errors );
    139139        }
     
    151151     * @return int Number of rows deleted, or FALSE on failure ( # / 2 = documents )
    152152     */
    153     public function delete_document( $args = array() ) {
    154 
     153    public function delete_document( $args = array( ) ) {
    155154        global $wpdb;
    156155
    157156
    158157        // set conditions
    159         $where = array();
     158        $where = array( );
    160159        $where[] = 'sub_p.post_type = "lift_queued_document"';
    161160
    162161        // remove specific ID
    163         if ( array_key_exists('id', $args) && (int)$args['id'] >= 1 ) {
    164             $where[] = sprintf( 'sub_p.ID = %d', (int)$args['id'] );
     162        if ( array_key_exists( 'id', $args ) && ( int ) $args['id'] >= 1 ) {
     163            $where[] = sprintf( 'sub_p.ID = %d', ( int ) $args['id'] );
    165164        }
    166165
    167166        // remove batch starting from specific ID
    168         if ( array_key_exists('start_from', $args) && (int)$args['start_from'] >= 1 ) {
    169             $where[] = sprintf( 'sub_p.ID >= %d', (int)$args['start_from'] );
     167        if ( array_key_exists( 'start_from', $args ) && ( int ) $args['start_from'] >= 1 ) {
     168            $where[] = sprintf( 'sub_p.ID >= %d', ( int ) $args['start_from'] );
    170169        }
    171170
     
    174173        $limit = '';
    175174
    176         if ( array_key_exists('limit', $args) && (int)$args['limit'] >= 1 ) {
    177             $limit = sprintf( 'LIMIT %d', (int)$args['limit'] );
    178         }
    179 
     175        if ( array_key_exists( 'limit', $args ) && ( int ) $args['limit'] >= 1 ) {
     176            $limit = sprintf( 'LIMIT %d', ( int ) $args['limit'] );
     177        }
    180178
    181179        return $wpdb->query(
     
    186184                            SELECT sub_p.ID
    187185                                FROM {$wpdb->posts} sub_p
    188                                 WHERE ".implode(' AND ', $where)."
     186                                WHERE " . implode( ' AND ', $where ) . "
    189187                                ORDER BY sub_p.ID ASC
    190188                                {$limit}
     
    192190                        LEFT JOIN {$wpdb->postmeta} pm ON p.ID = pm.post_id"
    193191                )
    194             );
    195 
     192        );
    196193    }
    197194
     
    203200    public function check_document_length( $document ) {
    204201        $json = json_encode( $document );
    205         return (bool) (strlen( $json ) <= self::DOCUMENT_LIMIT);
     202        return ( bool ) (strlen( $json ) <= self::DOCUMENT_LIMIT);
    206203    }
    207204
     
    211208     */
    212209    public function check_documents_length() {
    213         return (bool) ($this->get_documents_length() <= self::BATCH_LIMIT);
     210        return ( bool ) ($this->get_documents_length() <= self::BATCH_LIMIT);
    214211    }
    215212
     
    229226    public function can_add( $document ) {
    230227        if ( !is_object( $document ) || !$this->check_required_fields( $document ) ) {
    231             $this->errors[] = array(
    232                 'code' => 120,
    233                 'message' => 'Document is not an object',
    234             );
     228            $this->errors[] = array(
     229                'code' => 120,
     230                'message' => 'Document is not an object',
     231            );
    235232            throw new Lift_Batch_Exception( $this->errors );
    236233        }
     
    242239        } else {
    243240            $this->errors[] = array(
    244                 'code' => 500,
     241                'code' => 500,
    245242                'message' => 'Batch limit reached',
    246243                'current_count' => count( $this->documents ),
     
    249246            return false;
    250247        }
    251        
    252         return false;
     248
     249        return false;
    253250    }
    254251
     
    260257     */
    261258    public function sanitize( $document ) {
    262         if ( property_exists($document, 'fields') && is_array( $document->fields ) ) {
    263             $document->fields = array_change_key_case($document->fields);
    264             foreach ($document->fields as $key => $value) {
     259        if ( property_exists( $document, 'fields' ) && is_array( $document->fields ) ) {
     260            $document->fields = array_change_key_case( $document->fields );
     261            foreach ( $document->fields as $key => $value ) {
    265262                if ( $value === null ) {
    266263                    $document->fields[$key] = "";
     
    274271        $json = json_encode( $this->documents );
    275272        if ( empty( $this->documents ) ||
    276                 $json === null ||
    277                 !$json ) {
     273            $json === null ||
     274            !$json ) {
    278275            return false;
    279276        } else {
  • lift-search/trunk/api/lift-http.php

    r627882 r658221  
    33interface iLift_HTTP {
    44
    5     public function post( $url, $data, $headers = array() );
     5    public function post( $url, $data, $headers = array( ) );
    66
    7     public function get( $url, $headers = array() );
     7    public function get( $url, $headers = array( ) );
    88
    99    public function getStatusCode();
    1010
    1111    public function getResponse();
    12 
    1312}
    1413
     
    1817    protected $response;
    1918
    20     private function makeRequest( $url, $method = 'POST', $data = '', $headers = array() ) {
    21         // @TODO: better error handling to pass up to caller
    22        
     19    private function makeRequest( $url, $method = 'POST', $data = '', $headers = array( ) ) {
     20        // @TODO: better error handling to pass up to caller
     21
    2322        $args = array(
    2423            'method' => strtoupper( $method ),
     
    4342    }
    4443
    45     public function get( $url, $headers = array() ) {
     44    public function get( $url, $headers = array( ) ) {
    4645        if ( empty( $url ) ) {
    4746            return false;
     
    5150    }
    5251
    53     public function post( $url, $data, $headers = array() ) {
     52    public function post( $url, $data, $headers = array( ) ) {
    5453        if ( empty( $url ) || empty( $data ) ) {
    5554            return false;
     
    6665        return $this->response;
    6766    }
     67
    6868}
    6969
    7070class Lift_HTTP_WP_VIP extends Lift_HTTP_WP implements iLift_HTTP {
    7171
    72     public function get( $url, $headers = array() ) {
     72    public function get( $url, $headers = array( ) ) {
    7373
    7474        $this->response = vip_safe_wp_remote_get( $url, '', 3, 1, 20, compact( 'headers' ) );
     
    8181
    8282        return wp_remote_retrieve_body( $this->response );
    83 
    8483    }
    8584
     
    9695        //Setup cURL
    9796        $this->setOptions();
    98 
    9997    }
    10098
     
    122120    }
    123121
    124     public function get( $url, $headers = array() ) {
     122    public function get( $url, $headers = array( ) ) {
    125123        $request = $this->makeRequest( 'get', $url, '', $headers );
    126124        return $request;
    127125    }
    128126
    129     public function post( $url, $data, $headers = array() ) {
     127    public function post( $url, $data, $headers = array( ) ) {
    130128        $request = $this->makeRequest( 'post', $url, $data, $headers );
    131129        return $request;
     
    133131
    134132    function makeRequest( $method, $url, $data, $headers ) {
    135        
     133
    136134        curl_setopt( $this->channel, CURLOPT_URL, $url );
    137135
     
    139137            curl_setopt( $this->channel, CURLOPT_POST, true );
    140138            curl_setopt( $this->channel, CURLOPT_POSTFIELDS, $data );
    141            
    142139        }
    143140
    144         curl_setopt( $this->channel, CURLOPT_HTTPHEADER, $headers);
     141        curl_setopt( $this->channel, CURLOPT_HTTPHEADER, $headers );
    145142
    146143        $this->response = curl_exec( $this->channel );
     
    149146
    150147        // @TODO: wp_error style handling here (timeouts, etc)
    151         if( ! in_array( $this->response_code, array( 200, 201, 204 ) ) ) {
     148        if ( !in_array( $this->response_code, array( 200, 201, 204 ) ) ) {
    152149            return false;
    153150        }
     
    155152        return $this->response;
    156153    }
     154
    157155}
  • lift-search/trunk/lib/posts-to-sdf.php

    r627882 r658221  
    1414     */
    1515    private static $post_fields = array(
    16         'ID'            => 'intval',
    17         'post_content'  => array(__CLASS__, '__strip_tags_shortcodes'),
     16        'ID' => 'intval',
     17        'post_content' => array( __CLASS__, '__strip_tags_shortcodes' ),
    1818        'post_date_gmt' => 'strtotime',
    19         'post_excerpt'  => array(__CLASS__, '__strip_tags_shortcodes'),
    20         'post_author'   => 'intval',
    21         'post_category' => array(__CLASS__, '__format_post_categories'),
    22         'tags_input'    => array(__CLASS__, '__format_post_tags')
     19        'post_excerpt' => array( __CLASS__, '__strip_tags_shortcodes' ),
     20        'post_author' => 'intval',
     21        'post_category' => array( __CLASS__, '__format_post_categories' ),
     22        'tags_input' => array( __CLASS__, '__format_post_tags' )
    2323    );
    2424
     
    5252        // @TODO: performance
    5353        return array_map( function( $tag ) {
    54             $term = get_term_by( 'name', $tag, 'post_tag' );
    55             return (int) $term->term_id;
    56         }, $tags );
    57 
     54                    $term = get_term_by( 'name', $tag, 'post_tag' );
     55                    return ( int ) $term->term_id;
     56                }, $tags );
    5857    }
    5958
     
    7877
    7978            self::$document_id_prefix = apply_filters( 'lift_document_id_prefix', self::$document_id_prefix );
    80 
    8179        }
    8280
     
    9088     * @return array formatted posts
    9189     */
    92     function get_posts_for_batch_add( $args = array() ) {
     90    function get_posts_for_batch_add( $args = array( ) ) {
    9391
    94         $posts = get_posts($args);
     92        $posts = get_posts( $args );
    9593
    96         foreach ($posts as $i => $post) {
     94        foreach ( $posts as $i => $post ) {
    9795            $posts[$i] = self::format_post( $post->ID, array( 'action' => 'add', 'time' => time() ) );
    9896        }
     
    112110
    113111        // Only valid actions
    114         if ( ! in_array( $data['action'], $valid_types ) ) {
     112        if ( !in_array( $data['action'], $valid_types ) ) {
    115113            return false;
    116114        }
    117115
    118116        // Any non-negative number
    119         if ( $data['time'] == (int)$data['time'] && $data['time'] < 0 ) {
     117        if ( $data['time'] == ( int ) $data['time'] && $data['time'] < 0 ) {
    120118            return false;
    121119        }
    122120
    123121        // $post must be post ID or object
    124         if ( ! is_numeric( $post ) && ! is_object( $post ) ) {
     122        if ( !is_numeric( $post ) && !is_object( $post ) ) {
    125123            return false;
    126124        }
    127125
    128         $fields = array();
    129         $_post  = is_numeric( $post ) ? get_post( $post, ARRAY_A ) : (array) $post;
     126        $fields = array( );
     127        $_post = is_numeric( $post ) ? get_post( $post, ARRAY_A ) : ( array ) $post;
    130128
    131129        if ( 'add' === $data['action'] ) {
    132130
    133             $field_names = apply_filters( 'lift_document_fields', array_keys($_post), $_post['ID'] );
     131            $field_names = apply_filters( 'lift_document_fields', array_keys( $_post ), $_post['ID'] );
    134132
    135133            foreach ( $field_names as $field ) {
    136                 $value = isset($_post[$field]) ? $_post[$field] : null;
    137                
    138                 if(isset(self::$post_fields[$field])) {
     134                $value = isset( $_post[$field] ) ? $_post[$field] : null;
     135
     136                if ( isset( self::$post_fields[$field] ) ) {
    139137                    $value = call_user_func( self::$post_fields[$field], $value );
    140138                }
    141                
     139
    142140                $value = apply_filters( 'lift_document_field_' . $field, $value, $_post['ID'] );
    143141
     
    147145
    148146                    $value = preg_replace( '/[\x00-\x09\x0B\x0C\x0E-\x1F\x7F]/', '', $value );
    149 
    150147                }
    151148
     
    154151
    155152            $fields = array_change_key_case( $fields );
    156            
    157             $fields = apply_filters('lift_document_fields_result', $fields, $_post['ID']);
    158153
     154            $fields = apply_filters( 'lift_document_fields_result', $fields, $_post['ID'] );
    159155        }
    160156
    161157        $document = array(
    162             'type'    => $data['action'],
    163             'id'      => self::get_document_id_prefix() . $_post['ID'],
     158            'type' => $data['action'],
     159            'id' => self::get_document_id_prefix() . $_post['ID'],
    164160            'version' => $data['time'],
    165161        );
    166        
    167         if($data['action'] == 'add') {
    168             $document['lang']    = 'en';
    169             $document['fields']  = $fields;
     162
     163        if ( $data['action'] == 'add' ) {
     164            $document['lang'] = 'en';
     165            $document['fields'] = $fields;
    170166        }
    171167
    172168        $document = apply_filters( 'lift_document', $document, $_post['ID'], $data['action'] );
    173169
    174         $document['fields'] = (object) array_filter($document['fields'], function( $value ) {
    175             return ! is_null( $value );
    176         });
     170        if(isset($document['fields'])) {
     171            $document['fields'] = ( object ) array_filter( $document['fields'], function( $value ) {
     172                        return !is_null( $value );
     173                    } );
     174        }
    177175
    178176        return $document;
  • lift-search/trunk/lift-search.php

    r642501 r658221  
    11<?php
     2
    23/*
    34  Plugin Name: Lift Search
    4   Version: 1.1
     5  Version: 1.2
    56  Plugin URI: http://getliftsearch.com/
    67  Description: Improves WordPress search using Amazon CloudSearch
     
    1617require_once('api/cloud-config.php');
    1718require_once('lib/posts-to-sdf.php');
    18 require_once('wp/lift-batch-queue.php');
     19require_once('wp/lift-batch-handler.php');
    1920require_once('wp/lift-health.php');
    2021require_once('wp/lift-wp-search.php');
     
    2627
    2728    class Lift_Search {
     29        /**
     30         * Option name for the marker of whether the user finisehd the setup process
     31         */
    2832
    2933        const INITIAL_SETUP_COMPLETE_OPTION = 'lift-initial-setup-complete';
     34        const DB_VERSION = 2;
     35
     36        /**
     37         * Option name for storing all user based options
     38         */
    3039        const SETTINGS_OPTION = 'lift-settings';
    31         const SEARCH_DOMAIN = 'search-domain';
    32 
    33         // Note: batch-interval should be in seconds, regardless of what batch-interval-units is set to
    34         private static $default_settings = array( 'batch-interval' => 300, 'batch-interval-units' => 'm' );
    35         private static $allowed_post_types = array( 'post', 'page' );
    36 
    37         const ADMIN_LANDING_PAGE = 'lift-search/admin/setup.php';
    38         const ADMIN_STATUS_PAGE = 'lift-search/admin/status.php';
    3940        const INDEX_DOCUMENTS_HOOK = 'lift_index_documents';
    4041        const SET_ENDPOINTS_HOOK = 'lift_set_endpoints';
    4142        const NEW_DOMAIN_CRON_INTERVAL = 'lift-index-documents';
    4243
     44        /**
     45         * Returns whether setup has been complete by testing whether all
     46         * required data is set
     47         * @return bool
     48         */
     49        public static function is_setup_complete() {
     50            return self::get_access_key_id() && self::get_secret_access_key()
     51                && self::get_search_domain() && get_option( self::INITIAL_SETUP_COMPLETE_OPTION, 0 );
     52        }
     53
     54        public static function error_logging_enabled() {
     55            return !( defined( 'DISABLE_LIFT_ERROR_LOGGING' ) && DISABLE_LIFT_ERROR_LOGGING )
     56                && ( class_exists( 'Voce_Error_Logging' ) || file_exists( __DIR__ . '/lib/voce-error-loggin/voce-error-logging' ) );
     57        }
     58
    4359        public static function init() {
    44             add_action( 'admin_menu', array( __CLASS__, 'add_settings' ) );
    45 
    46             add_action( 'admin_init', array( __CLASS__, 'admin_init' ) );
    47             add_filter( 'plugin_row_meta', array( __CLASS__, 'settings_link' ), 10, 2 );
    48             add_filter( 'plugin_action_links_' . plugin_basename( __FILE__ ), array( __CLASS__, 'settings_link' ), 10, 2 );
    49 
    50             add_action( 'wp_ajax_lift_test_access', array( __CLASS__, 'ajax_test_access' ) );
    51             add_action( 'wp_ajax_lift_test_domain', array( __CLASS__, 'ajax_test_domain' ) );
    52 
    53             add_action( 'wp_ajax_lift_delete_error_logs', array( __CLASS__, 'ajax_delete_error_logs' ) );
    54 
    55             add_action( 'wp_ajax_lift_update_cron_interval', array( __CLASS__, 'ajax_update_cron_interval' ) );
    56 
    57             add_action( 'wp_ajax_lift_create_domain', array( __CLASS__, 'ajax_create_domain' ) );
    58 
    59             add_action( 'wp_ajax_lift_set_cron_status', array( __CLASS__, 'ajax_set_cron_status' ) );
     60
     61            if ( self::error_logging_enabled() && !class_exists( 'Voce_Error_Logging' )
     62                && file_exists( __DIR__ . '/lib/voce-error-loggin/voce-error-logging' ) ) {
     63                require_once (__DIR__ . '/lib/voce-error-loggin/voce-error-logging');
     64            }
     65
     66            if ( self::get_search_endpoint() ) {
     67                add_action( 'init', array( 'Lift_WP_Search', 'init' ) );
     68            }
     69
     70            if ( self::get_document_endpoint() ) {
     71                add_action( 'init', array( 'Lift_Batch_Handler', 'init' ) );
     72            }
     73
     74            if ( is_admin() ) {
     75                require_once(__DIR__ . '/admin/admin.php');
     76                Lift_Admin::init();
     77            }
     78
     79            add_action( 'init', array( __CLASS__, '__upgrade_check' ) );
     80
     81            //need cron hooks to be set prior to init
     82            add_action( Lift_Batch_Handler::BATCH_CRON_HOOK, array( 'Lift_Batch_Handler', 'send_next_batch' ) );
     83            add_action( Lift_Batch_Handler::QUEUE_ALL_CRON_HOOK, array( 'Lift_Batch_Handler', 'process_queue_all' ) );
     84
    6085
    6186            // @TODO only enqueue on search template or if someone calls the form
    6287            add_action( 'wp_enqueue_scripts', function() {
    63                         wp_enqueue_script( 'lift-search-form', plugins_url( 'js/lift-search-form.js', __FILE__ ), array( 'jquery' ) );
    64                         wp_enqueue_style( 'lift-search', plugins_url( 'sass/style.css', __FILE__ ) );
    65                     } );
    66 
    67             if ( self::get_search_endpoint() ) {
    68                 Lift_WP_Search::init();
    69             }
    70 
    71             if ( self::get_document_endpoint() ) {
    72                 Lift_Batch_Queue::init();
    73             }
     88                    wp_enqueue_script( 'lift-search-form', plugins_url( 'js/lift-search-form.js', __FILE__ ), array( 'jquery' ) );
     89                    wp_enqueue_style( 'lift-search', plugins_url( 'sass/style.css', __FILE__ ) );
     90                } );
    7491
    7592            //default sdf filters
    7693            add_filter( 'lift_document_fields_result', function($fields, $post_id) {
    77                         $taxonomies = array( 'post_tag', 'category' );
    78                         foreach ($taxonomies as $taxonomy) {
    79                             if ( array_key_exists( 'taxonomy_' . $taxonomy, $fields ) ) {
    80                                 unset( $fields['taxonomy_' . $taxonomy] );
    81                                 $terms = get_the_terms( $post_id, $taxonomy );
    82                                 $fields['taxonomy_' . $taxonomy . '_id'] = array( );
    83                                 $fields['taxonomy_' . $taxonomy . '_label'] = array( );
    84                                 foreach ($terms as $term) {
    85                                     $fields['taxonomy_' . $taxonomy . '_id'][] = $term->term_id;
    86                                     $fields['taxonomy_' . $taxonomy . '_label'][] = $term->name;
    87                                 }
     94                    $taxonomies = array( 'post_tag', 'category' );
     95                    foreach ( $taxonomies as $taxonomy ) {
     96                        if ( array_key_exists( 'taxonomy_' . $taxonomy, $fields ) ) {
     97                            unset( $fields['taxonomy_' . $taxonomy] );
     98                            $terms = get_the_terms( $post_id, $taxonomy );
     99                            $fields['taxonomy_' . $taxonomy . '_id'] = array( );
     100                            $fields['taxonomy_' . $taxonomy . '_label'] = array( );
     101                            foreach ( $terms as $term ) {
     102                                $fields['taxonomy_' . $taxonomy . '_id'][] = $term->term_id;
     103                                $fields['taxonomy_' . $taxonomy . '_label'][] = $term->name;
    88104                            }
    89105                        }
    90 
    91                         if ( array_key_exists( 'post_author', $fields ) ) {
    92                             $display_name = get_user_meta( $fields['post_author'], 'display_name', true );
    93 
    94                             if ( $display_name ) {
    95                                 $fields['post_author_name'] = $display_name;
    96                             }
     106                    }
     107
     108                    if ( array_key_exists( 'post_author', $fields ) ) {
     109                        $display_name = get_user_meta( $fields['post_author'], 'display_name', true );
     110
     111                        if ( $display_name ) {
     112                            $fields['post_author_name'] = $display_name;
    97113                        }
    98 
    99                         return $fields;
    100                     }, 10, 2 );
     114                    }
     115
     116                    return $fields;
     117                }, 10, 2 );
    101118
    102119            add_filter( 'cron_schedules', function( $schedules ) {
    103                         $schedules[Lift_Search::NEW_DOMAIN_CRON_INTERVAL] = array(
    104                             'interval' => 60 * 5, // 5 mins
    105                             'display' => '',
    106                         );
    107 
    108                         return $schedules;
    109                     } );
    110 
    111             add_action( self::INDEX_DOCUMENTS_HOOK, array( __CLASS__, 'cron_index_documents' ) );
    112             add_action( self::SET_ENDPOINTS_HOOK, array( __CLASS__, 'cron_set_endpoints' ) );
    113         }
    114 
    115         public static function admin_init() {
    116 
    117             // delete all data
    118             if ( current_user_can( 'administrator' ) && isset( $_GET['lift-delete-all'] ) ) {
    119                 self::delete_all_data();
    120                 wp_redirect( admin_url( 'options-general.php?page=' . Lift_Search::ADMIN_STATUS_PAGE ) );
    121             }
    122 
    123             if ( isset( $_GET['page'] ) && Lift_Search::ADMIN_STATUS_PAGE == $_GET['page'] ) {
    124 
    125                 // require landing page to be filled out
    126                 if ( !isset( $_GET['lift-setup-complete'] ) &&
    127                         (!(self::get_access_key_id() && self::get_secret_access_key() && self::get_search_domain() && get_option( self::INITIAL_SETUP_COMPLETE_OPTION, 0 )) )
    128                 ) {
    129                     wp_redirect( admin_url( 'options-general.php?page=' . Lift_Search::ADMIN_LANDING_PAGE ) );
    130                 }
    131 
    132                 // send IndexDocuments request
    133                 if ( current_user_can( 'manage_options' ) && isset( $_GET['lift-indexdocuments'] ) ) {
    134                     Cloud_Config_Request::IndexDocuments( self::get_search_domain() );
    135                     wp_redirect( admin_url( 'options-general.php?page=' . Lift_Search::ADMIN_STATUS_PAGE ) );
    136                 }
    137 
    138                 // send next batch
    139                 if ( current_user_can( 'manage_options' ) && isset( $_GET['sync-queue'] ) ) {
    140                     Lift_Batch_Queue::send_next_batch();
    141                     wp_redirect( admin_url( 'options-general.php?page=' . Lift_Search::ADMIN_STATUS_PAGE ) );
    142                 }
    143             }
    144 
    145             foreach (array( 'user_admin_notices', 'admin_notices' ) as $filter) {
    146                 add_action( $filter, function() {
    147                             if ( !(get_option( Lift_Search::INITIAL_SETUP_COMPLETE_OPTION, 0 ) && Lift_Search::get_access_key_id() && Lift_Search::get_secret_access_key() && Lift_Search::get_search_domain() ) ) {
    148                                 if ( !isset( $_GET['page'] ) || (isset( $_GET['page'] ) && Lift_Search::ADMIN_LANDING_PAGE != $_GET['page']) ) {
    149                                     Lift_Search::configure_lift_nag();
    150                                 }
    151                             }
    152                         } );
    153             }
    154         }
    155 
    156         /**
    157          * Add link to access settings page on Plugin mainpage
    158          * @param array $links
    159          * @param string $page
    160          * @return array
    161          */
    162         public static function settings_link( $links, $page ) {
    163             if ( $page == plugin_basename( __FILE__ ) ) {
    164                 $links[] = '<a href="' . admin_url( 'options-general.php?page=' . Lift_Search::ADMIN_LANDING_PAGE ) . '">Settings</a>';
    165             }
    166             return $links;
    167         }
    168 
    169         /**
    170          * Setup settings in admin
    171          * @method add_settings
    172          */
    173         public static function add_settings() {
    174             $capability = apply_filters( 'lift_settings_capability', 'manage_options' );
    175 
    176             add_options_page( 'Lift: Search for WordPress', 'Lift Search', $capability, self::ADMIN_STATUS_PAGE );
    177             add_submenu_page( '', 'Lift: Search for Wordpress', 'Lift Search', $capability, self::ADMIN_LANDING_PAGE );
    178 
    179             wp_enqueue_style( 'lift-search', plugins_url( 'sass/admin.css', __FILE__ ) );
    180 
    181             // since add_options/submenu_page doesn't give us the correct hook...
    182             foreach (array( 'lift-search/admin/setup.php', 'lift-search/admin/status.php' ) as $hook) {
    183                 add_action( "load-{$hook}", function() {
    184                             wp_enqueue_script( 'lift-admin-settings', plugins_url( 'js/admin-settings.js', __FILE__ ), array( 'jquery' ) );
    185                         } );
    186             }
    187         }
    188 
    189         /**
    190          * deletes all Lift: options, transients, queued posts, error logs, cron
    191          * jobs
    192          *
    193          * NOTE: not currently used anywhere but intended to be run manually for
    194          * debugging/testing but can be used in a uninstall hook later
    195          */
    196         public static function delete_all_data() {
    197             global $wpdb;
    198 
    199             delete_option( self::SETTINGS_OPTION );
    200             delete_option( self::INITIAL_SETUP_COMPLETE_OPTION );
    201             delete_option( Lift_Batch_Queue::LAST_CRON_TIME_OPTION );
    202             delete_option( self::INITIAL_SETUP_COMPLETE_OPTION );
    203             delete_option( Lift_Batch_Queue::QUEUE_ALL_MARKER_OPTION );
    204             delete_transient( Lift_Batch_Queue::BATCH_LOCK );
    205 
    206             $wpdb->delete( $wpdb->posts, array( 'post_type ' => Lift_Document_Update_Queue::STORAGE_POST_TYPE ) );
    207 
    208             Voce_Error_Logging::delete_logs( array( 'lift-search' ) );
    209 
    210             wp_clear_scheduled_hook( self::INDEX_DOCUMENTS_HOOK );
    211             wp_clear_scheduled_hook( Lift_Batch_Queue::BATCH_CRON_HOOK );
    212             wp_clear_scheduled_hook( Lift_Batch_Queue::QUEUE_ALL_CRON_HOOK );
    213         }
    214 
    215         public static function ajax_set_cron_status() {
    216             $set_cron = (bool) intval( $_POST['cron'] );
    217 
    218             if ( $set_cron ) {
    219                 Lift_Batch_Queue::enable_cron();
    220             } else {
    221                 Lift_Batch_Queue::disable_cron();
    222             }
    223 
    224             echo json_encode( array(
    225                 'set_cron' => $set_cron,
    226                 'last_cron' => Lift_Batch_Queue::get_last_cron_time(),
    227                 'next_cron' => Lift_Batch_Queue::get_next_cron_time()
    228             ) );
    229             die;
    230         }
    231 
    232         public static function ajax_test_access() {
    233             echo json_encode( self::test_access( trim( $_POST['id'] ), trim( $_POST['secret'] ) ) );
    234             die;
    235         }
    236 
    237         private function test_access( $id = '', $secret = '' ) {
     120                    $schedules[Lift_Search::NEW_DOMAIN_CRON_INTERVAL] = array(
     121                        'interval' => 60 * 5, // 5 mins
     122                        'display' => '',
     123                    );
     124
     125                    if ( Lift_Search::get_batch_interval() > 0 ) {
     126                        $interval = Lift_Search::get_batch_interval();
     127                    } else {
     128                        $interval = 86400;
     129                    }
     130
     131                    $schedules[Lift_Batch_Handler::CRON_INTERVAL] = array(
     132                        'interval' => $interval,
     133                        'display' => '',
     134                    );
     135
     136                    return $schedules;
     137                } );
     138
     139            //hooking into the index documents cron to tell AWS to start indexing documents
     140            add_action( self::INDEX_DOCUMENTS_HOOK, function() {
     141                    $domain_name = self::__get_setting( 'search-domain' );
     142
     143                    if ( !$domain_name ) {
     144                        return;
     145                    }
     146
     147                    $r = Cloud_Config_Request::IndexDocuments( $domain_name );
     148
     149                    if ( $r ) {
     150                        wp_clear_scheduled_hook( self::INDEX_DOCUMENTS_HOOK );
     151                    }
     152                } );
     153
     154            //hooking into endpoints cron to "asynchronously" retrieve the endpoint data
     155            //from AWS
     156            add_action( self::SET_ENDPOINTS_HOOK, function() {
     157                    $domain_name = self::get_search_domain();
     158
     159                    if ( !$domain_name ) {
     160                        return;
     161                    }
     162
     163                    $document_endpoint = Cloud_Config_Request::DocumentEndpoint( $domain_name );
     164                    $search_endpoint = Cloud_Config_Request::SearchEndpoint( $domain_name );
     165
     166                    if ( $document_endpoint && $search_endpoint ) {
     167                        self::__set_setting( 'document-endpoint', $document_endpoint );
     168                        self::__set_setting( 'search-endpoint', $search_endpoint );
     169                        wp_clear_scheduled_hook( self::SET_ENDPOINTS_HOOK );
     170                    }
     171                } );
     172        }
     173
     174        public function test_access( $id = '', $secret = '' ) {
    238175
    239176            $credentials = array( 'access-key-id' => $id, 'secret-access-key' => $secret );
     
    260197        }
    261198
    262         public static function ajax_test_domain() {
    263 
    264             $test_access = self::test_access( self::get_access_key_id(), self::get_secret_access_key() );
    265             if ( $test_access['error'] ) {
    266                 echo json_encode( $test_access );
    267                 die;
    268             }
    269 
    270             $domain = strtolower( trim( $_POST['domain'] ) );
    271 
    272             $error = false;
    273             $replacing_domain = ( self::get_search_domain() != $domain );
    274 
    275             try {
    276                 if ( Cloud_Config_Request::TestDomain( $domain ) ) {
    277                     $status_message = 'Success';
    278                     self::__set_setting( self::SEARCH_DOMAIN, $domain );
    279 
    280                     $document_endpoint = Cloud_Config_Request::DocumentEndpoint( $domain );
    281                     $search_endpoint = Cloud_Config_Request::SearchEndpoint( $domain );
    282 
    283                     try {
    284                         if ( $document_endpoint && $search_endpoint ) {
    285                             self::__set_setting( 'document-endpoint', $document_endpoint );
    286                             self::__set_setting( 'search-endpoint', $search_endpoint );
    287                         } else {
    288                             $status_message = 'Unable to set endpoints. If this is a newly-created search domain it will take up to 30 minutes for endpoints to become available. Please try back later.';
    289                             $error = true;
    290 
    291                             self::__set_setting( self::SEARCH_DOMAIN, $domain );
    292                         }
    293                     } catch ( Exception $e ) {
    294                         //@todo add exception logging for endpoint failure
    295                         $status_message = "Unable to set endpoints. Please check the search domain's status in the AWS Console";
    296                         $error = true;
    297 
    298                         self::__set_setting( self::SEARCH_DOMAIN, $domain );
    299                     }
    300                 } else {
    301                     $status_message = 'Domain could not be found. <span class="">Would you like to <a id="lift-create-domain" data-domain="' . esc_attr( $domain ) . '" href="#">create this domain with Lift\'s default indexes</a>?</span>';
    302                     $error = true;
    303                 }
    304             } catch ( Exception $e ) {
    305                 // @todo add exception logging for domain check failure
    306                 $status_message = 'There was an error checking the domain. Please try again.';
    307                 $error = true;
    308             }
    309 
    310             if ( !$error && $replacing_domain ) {
    311                 // mark setup complete
    312                 update_option( self::INITIAL_SETUP_COMPLETE_OPTION, 1 );
    313                 Lift_Batch_Queue::enable_cron();
    314                 Lift_Batch_Queue::queue_all();
    315             }
    316 
    317             echo json_encode( array( 'error' => $error, 'message' => $status_message ) );
    318             die;
    319         }
    320 
    321         public static function ajax_create_domain() {
    322 
    323             $domain = strtolower( trim( $_POST['domain'] ) );
    324 
    325             $error = false;
    326             $status_messages = array( );
    327 
    328             $r = Cloud_Config_Request::CreateDomain( $domain );
    329 
    330             if ( $r ) {
    331 
    332                 self::__set_setting( self::SEARCH_DOMAIN, $domain );
    333 
    334                 $r = Cloud_Config_Request::LoadSchema( $domain );
    335 
    336                 if ( $r ) {
    337                     if ( $r->DescribeDomainsResponse->DescribeDomainsResult->DomainStatusList ) {
    338                         $status_messages[] = 'Index created succesfully.';
    339                         self::__set_setting( 'document-endpoint', '' );
    340                         self::__set_setting( 'search-endpoint', '' );
    341                         self::add_new_domain_crons(); // add crons
    342                     } else {
    343                         $status_messages[] = 'There was an error creating an index for your domain.';
    344                         $error = true;
    345 
    346                         Lift_Search::event_log( 'Cloud_Config_Request::LoadSchema (http success)', $r, array( 'error' ) );
    347                     }
    348                 } else {
    349                     $status_message = 'There was an error creating an index for your domain.';
    350                     $status_messages[] = $status_message;
    351                     $error = true;
    352 
    353                     Lift_Search::event_log( 'Cloud_Config_Request::LoadSchema', $status_message, array( 'error' ) );
    354                 }
    355 
    356                 $r = Cloud_Config_Request::UpdateServiceAccessPolicies( $domain, Cloud_Config_Request::GetDefaultServiceAccessPolicy( $domain ) );
    357 
    358                 if ( $r ) {
    359                     $status_messages[] = 'Service Access Policies successfully configured.';
    360                 } else {
    361                     $status_messages[] = 'Service Access Policies could not be set. You will need to use the AWS Console to set them for this search domain.';
    362                     $error = true;
    363 
    364                     Lift_Search::event_log( 'Cloud_Config_Request::UpdateServiceAccessPolicies', $r, array( 'error' ) );
    365                 }
    366             } else {
    367                 $status_message = 'There was an error creating your domain. Please make sure the domain name follows the rules above and try again.';
    368                 $status_messages[] = $status_message;
    369                 $error = true;
    370 
    371                 Lift_Search::event_log( 'Cloud_Config_Request::CreateDomain', $status_message, array('error' ) );
    372             }
    373 
    374             if ( !$error ) {
    375                 // mark setup complete, enable cron and queue all posts
    376                 update_option( self::INITIAL_SETUP_COMPLETE_OPTION, 1 );
    377                 Lift_Batch_Queue::enable_cron();
    378                 Lift_Batch_Queue::queue_all();
    379 
    380                 $status_messages[] = "New search domains take approximately 30-45 minutes to become active. Once your search domain is
    381                     available on CloudSearch, Lift will complete it's configuration, index all posts on your site, and
    382                     queue up new posts to be synced periodically.";
    383             }
    384 
    385             echo json_encode( array(
    386                 'error' => $error,
    387                 'message' => join( ' ', $status_messages ),
    388             ) );
    389 
    390             exit;
    391         }
    392 
    393         public static function ajax_delete_error_logs() {
    394             $response = Voce_Error_Logging::delete_logs( array( 'lift-search' ) );
    395             echo json_encode( $response );
    396             die();
    397         }
    398 
    399199        /**
    400200         * schedule crons needed for new domains. clear existing crons first.
    401201         *
    402202         */
    403         private static function add_new_domain_crons() {
     203        public static function add_new_domain_crons() {
    404204            wp_clear_scheduled_hook( self::INDEX_DOCUMENTS_HOOK );
    405205            wp_clear_scheduled_hook( self::SET_ENDPOINTS_HOOK );
     
    407207            wp_schedule_event( time(), self::NEW_DOMAIN_CRON_INTERVAL, self::INDEX_DOCUMENTS_HOOK );
    408208            wp_schedule_event( time(), self::NEW_DOMAIN_CRON_INTERVAL, self::SET_ENDPOINTS_HOOK );
    409         }
    410 
    411         /**
    412          * cron hook to send an IndexDocuments request to CloudSearch. cron
    413          * is unscheduled when the documents are indexed successfully.
    414          *
    415          */
    416         public static function cron_index_documents() {
    417             $domain_name = self::__get_setting( self::SEARCH_DOMAIN );
    418 
    419             if ( !$domain_name ) {
    420                 return;
    421             }
    422 
    423             $r = Cloud_Config_Request::IndexDocuments( $domain_name );
    424 
    425             if ( $r ) {
    426                 wp_clear_scheduled_hook( self::INDEX_DOCUMENTS_HOOK );
    427             }
    428209        }
    429210
     
    450231        }
    451232
    452         public static function ajax_update_cron_interval() {
    453             $units = (string) $_POST['cron_interval_units'];
    454             $units = in_array( $units, array( 'm', 'h', 'd' ) ) ? $units : 'm';
    455 
    456             $interval = (int) $_POST['cron_interval'];
    457             $interval = ($units == 'm' && $interval < 1 ? 1 : $interval);
    458 
    459             switch ( $units ) {
    460                 case 'd':
    461                     $interval *= 24;
    462                 case 'h':
    463                     $interval *= 60;
    464                 case 'm':
    465                     $interval *= 60;
    466             }
    467 
    468             self::__set_setting( 'batch-interval', $interval );
    469             self::__set_setting( 'batch-interval-units', $units );
    470 
    471             if ( Lift_Batch_Queue::cron_enabled() ) {
    472                 Lift_Batch_Queue::disable_cron(); // kill the scheduled event
    473                 $last_time = get_option( Lift_Batch_Queue::LAST_CRON_TIME_OPTION, time() );
    474 
    475                 wp_schedule_event( $last_time + $interval, Lift_Batch_Queue::CRON_INTERVAL, Lift_Batch_Queue::BATCH_CRON_HOOK ); // schedule the next one based on the last
    476 
    477                 Lift_Batch_Queue::enable_cron();
    478             }
    479 
    480             echo json_encode( array(
    481                 'last_cron' => Lift_Batch_Queue::get_last_cron_time(),
    482                 'next_cron' => Lift_Batch_Queue::get_next_cron_time()
    483             ) );
    484             die;
    485         }
    486 
    487         /**
    488          * Get a setting using Voce_Settings_API
     233        /**
     234         * Get a setting lift setting
    489235         * @param string $setting
    490236         * @param string $group
     
    492238         */
    493239        private static function __get_setting( $setting ) {
    494             $option = get_option( self::SETTINGS_OPTION, array( ) );
    495             // Ensure this is an array. WP does not despite the request for a default.
    496             if ( is_array( $option ) ) {
    497                 $settings = array_merge( self::$default_settings, $option );
    498                 return (isset( $settings[$setting] )) ? $settings[$setting] : false;
     240            // Note: batch-interval should be in seconds, regardless of what batch-interval-units is set to
     241            $default_settings = array( 'batch-interval' => 300, 'batch-interval-units' => 'm' );
     242
     243            $settings = get_option( self::SETTINGS_OPTION, array( ) );
     244
     245            if ( !is_array( $settings ) ) {
     246                $settings = $default_settings;
    499247            } else {
    500                 return $option;
    501             }
     248                $settings = wp_parse_args( $settings, $default_settings );
     249            }
     250
     251            return (isset( $settings[$setting] )) ? $settings[$setting] : false;
    502252        }
    503253
     
    517267
    518268        /**
     269         * Sets the access key id
     270         * @param type $value
     271         */
     272        public static function set_access_key_id( $value ) {
     273            self::__set_setting( 'access-key-id', $value );
     274        }
     275
     276        /**
    519277         * Get secret access key
    520278         * @return string
     
    525283
    526284        /**
     285         * Sets the secret key id
     286         * @param type $value
     287         */
     288        public static function set_secret_access_key( $value ) {
     289            self::__set_setting( 'secret-access-key', $value );
     290        }
     291
     292        /**
    527293         * Get search domain
    528294         * @return string
    529295         */
    530296        public static function get_search_domain() {
    531             return apply_filters( 'lift_search_domain', self::__get_setting( self::SEARCH_DOMAIN ) );
     297            return apply_filters( 'lift_search_domain', self::__get_setting( 'search-domain' ) );
     298        }
     299
     300        public static function set_search_domain( $value ) {
     301            self::__set_setting( 'search-domain', $value );
     302            self::__update_endpoints();
     303        }
     304
     305        private static function __update_endpoints() {
     306            if ( $search_domain = self::get_search_domain() ) {
     307                $document_endpoint = Cloud_Config_Request::DocumentEndpoint( $search_domain );
     308                $search_endpoint = Cloud_Config_Request::SearchEndpoint( $search_domain );
     309
     310                if ( $document_endpoint && $search_endpoint ) {
     311                    self::__set_setting( 'document-endpoint', $document_endpoint );
     312                    self::__set_setting( 'search-endpoint', $search_endpoint );
     313                }
     314            }
    532315        }
    533316
     
    537320         */
    538321        public static function get_search_endpoint() {
     322            if ( !self::__get_setting( 'search-endpoint' ) ) {
     323                self::__update_endpoints();
     324            }
    539325            return apply_filters( 'lift_search_endpoint', self::__get_setting( 'search-endpoint' ) );
     326        }
     327
     328        public static function set_search_endpoint( $value ) {
     329            self::__set_setting( 'search-endpoint', $value );
    540330        }
    541331
     
    545335         */
    546336        public static function get_document_endpoint() {
     337            if ( !self::__get_setting( 'document-endpoint' ) ) {
     338                self::__update_endpoints();
     339            }
    547340            return apply_filters( 'lift_document_endpoint', self::__get_setting( 'document-endpoint' ) );
     341        }
     342
     343        public static function set_document_endpoint( $value ) {
     344            self::__set_setting( 'document-endpoint', $value );
    548345        }
    549346
     
    556353        }
    557354
    558         /**
    559          * Get batch interval setting, adjusted for time unit
    560          * @return int
    561          */
    562         public static function get_batch_interval_adjusted() {
    563             $adjusted = self::get_batch_interval();
    564 
    565             switch ( self::get_batch_interval_unit() ) {
     355        public static function get_batch_interval_display() {
     356            $value = self::get_batch_interval();
     357            $unit = self::__get_setting( 'batch-interval-unit' );
     358            switch ( $unit ) {
    566359                case 'd':
    567                     $adjusted /= 24;
     360                    $value /= 24;
    568361                case 'h':
    569                     $adjusted /= 60;
     362                    $value /= 60;
    570363                case 'm':
    571                     $adjusted /= 60;
    572             }
    573 
    574             return apply_filters( 'lift_batch_interval_adjusted', $adjusted );
    575         }
    576 
    577         /**
    578          * Get batch interval unit setting
    579          * @return string
    580          */
    581         public static function get_batch_interval_unit() {
    582             return apply_filters( 'lift_batch_interval_unit', self::__get_setting( 'batch-interval-units' ) );
     364                default:
     365                    $unit = 'm';
     366                    $value /= 60;
     367            }
     368
     369            return apply_filters( 'lift_batch_interval_display', compact( 'value', 'unit' ) );
     370        }
     371
     372        /**
     373         * Sets the batch interval based off of user facing values
     374         * @param int $value The number of units
     375         * @param string $unit The shorthand value of the unit, options are 'm','h','d'
     376         */
     377        public static function set_batch_interval_display( $value, $unit ) {
     378            $old_interval = self::get_batch_interval_display();
     379            $has_changed = false;
     380
     381            foreach ( array( 'value', 'unit' ) as $key ) {
     382                if ( $old_interval[$key] != $$key ) {
     383                    $has_changed = true;
     384                    break;
     385                }
     386            }
     387
     388            if ( $has_changed ) {
     389                $interval = $value;
     390                switch ( $unit ) {
     391                    case 'd':
     392                        $interval *= 24;
     393                    case 'h':
     394                        $interval *= 60;
     395                    case 'm':
     396                    default:
     397                        $unit = 'm';
     398                        $interval *= 60;
     399                }
     400
     401                self::__set_setting( 'batch-interval-unit', $unit );
     402                self::__set_setting( 'batch-interval', $interval );
     403
     404                if ( Lift_Batch_Handler::cron_enabled() ) {
     405                    $last_time = get_option( Lift_Batch_Handler::LAST_CRON_TIME_OPTION, time() );
     406
     407                    Lift_Batch_Handler::enable_cron( $last_time + $interval );
     408                }
     409            }
    583410        }
    584411
     
    598425            $lift_http = self::get_http_api();
    599426            return new Cloud_API( $lift_http,
    600                             Lift_Search::get_document_endpoint(), Lift_Search::get_search_endpoint(), '2011-02-01' );
     427                    Lift_Search::get_document_endpoint(), Lift_Search::get_search_endpoint(), '2011-02-01' );
    601428        }
    602429
    603430        public static function get_indexed_post_types() {
    604             return apply_filters( 'lift_indexed_post_types', self::$allowed_post_types );
    605         }
    606 
    607         public static function configure_lift_nag() {
    608             ?>
    609             <div id="banneralert" class="lift-colorized">
    610                 <div class="lift-balloon">
    611                     <img src="<?php echo plugin_dir_url( __FILE__ ) ?>img/logo.png" alt="Lift Logo">
    612                 </div>
    613                 <div class="lift-message"><p><strong>Welcome to Lift</strong>:  Now that you've activated the Lift plugin it's time to set it up. Click below to get started. </p></div>
    614                 <div><a class="lift-btn" href="<?php echo admin_url( 'options-general.php?page=' . Lift_Search::ADMIN_LANDING_PAGE ) ?>">Configure Lift</a></div>
    615                 <div class="clr"></div>
    616             </div>
    617             <script>
    618                 jQuery(document).ready(function($) {
    619                     var $bannerAlert = $('#banneralert');
    620                     if ( $bannerAlert.length ) {
    621                         $('.wrap h2').first().after($bannerAlert);
    622                     }
    623                 });
    624             </script>
    625             <?php
     431            return apply_filters( 'lift_indexed_post_types', array( 'post', 'page' ) );
     432        }
     433
     434        public static function get_indexed_post_fields( $post_type ) {
     435            return apply_filters( 'lift_indexed_post_fields', array(
     436                    'post_title',
     437                    'post_content',
     438                    'post_excerpt',
     439                    'post_date_gmt',
     440                    'post_excerpt',
     441                    'post_status',
     442                    'post_type',
     443                    'post_author'
     444                    ), $post_type );
    626445        }
    627446
    628447        public static function RecentLogTable() {
     448            if ( !self::error_logging_enabled() ) {
     449                return '<div class="notice">Error Logging is Disabled</div>';
     450            }
     451
    629452            $args = array(
    630453                'post_type' => Voce_Error_Logging::POST_TYPE,
     
    666489            return $html;
    667490        }
    668        
     491
    669492        /**
    670493         * Log Events
     
    673496         * @return boolean
    674497         */
    675         public static function event_log($message, $error, $tags = array()){
    676             if(function_exists('voce_error_log')){
    677                 return voce_error_log( $message, $error, array_merge(array( 'lift-search'), (array) $tags) );
     498        public static function event_log( $message, $error, $tags = array( ) ) {
     499            if ( function_exists( 'voce_error_log' ) ) {
     500                return voce_error_log( $message, $error, array_merge( array( 'lift-search' ), ( array ) $tags ) );
    678501            } else {
    679502                return false;
     
    681504        }
    682505
     506        public static function __upgrade_check() {
     507            global $wpdb;
     508
     509            $db_version = get_option( 'lift_db_version', 0 );
     510            if ( $db_version < 2 ) {
     511
     512                $post_ids = $wpdb->get_col( "SELECT ID FROM $wpdb->posts " .
     513                    "WHERE post_type = '" . Lift_Document_Update_Queue::STORAGE_POST_TYPE . "'" );
     514
     515                $queue_id = Lift_Document_Update_Queue::get_active_queue_id();
     516
     517                foreach ( $post_ids as $post_id ) {
     518                    if ( $update_meta = get_post_meta( $post_id, 'lift_content', true ) ) {
     519                        if ( is_string( $update_meta ) )
     520                            $update_meta = maybe_unserialize( $update_meta ); //previous versions double serialized meta
     521
     522                        $meta_key = 'lift_update_' . $update_meta['document_type'] . '_' . $update_meta['document_id'];
     523                        $new_meta = array(
     524                            'document_id' => $update_meta['document_id'],
     525                            'document_type' => $update_meta['document_type'],
     526                            'action' => $update_meta['action'],
     527                            'fields' => $update_meta['fields'],
     528                            'update_date_gmt' => get_post_time( 'Y-m-d H:i:s', true, $post_id ),
     529                            'update_date' => get_post_time( 'Y-m-d H:i:s', false, $post_id )
     530                        );
     531                        update_post_meta( $queue_id, $meta_key, $new_meta );
     532
     533                        wp_delete_post( $post_id );
     534                    }
     535                }
     536
     537                update_option( 'lift_db_version', 2 );
     538            }
     539        }
     540
    683541    }
    684542
    685     Lift_Search::init();
     543    add_action( 'plugins_loaded', array( 'Lift_Search', 'init' ) );
    686544}
     545
     546
     547register_deactivation_hook( __FILE__, '_lift_deactivate' );
     548
     549function _lift_deactivate() {
     550    // @TODO Clean up batch posts and any scheduled crons
     551    //clean up options
     552    delete_option( Lift_Search::INITIAL_SETUP_COMPLETE_OPTION );
     553    delete_option( Lift_Search::SETTINGS_OPTION );
     554    delete_option( 'lift_db_version' );
     555
     556    if ( class_exists( 'Voce_Error_Logging' ) ) {
     557        Voce_Error_Logging::delete_logs( array( 'lift-search' ) );
     558    }
     559
     560    wp_clear_scheduled_hook( Lift_Search::INDEX_DOCUMENTS_HOOK );
     561
     562    Lift_Batch_Handler::_deactivation_cleanup();
     563    Lift_Document_Update_Queue::_deactivation_cleanup();
     564}
  • lift-search/trunk/readme.txt

    r642501 r658221  
    44Requires at least: 3.4.2
    55Tested up to: 3.5
    6 Stable tag: 1.1
     6Stable tag: 1.2
    77License: GPLv2 or later
    88License URI: http://www.gnu.org/licenses/gpl-2.0.html
     
    8484The Query Parameter to enter (step #8) is "s".
    8585
     86= What index fields are used when Lift configures a new search domain? =
     87The index fields are set as follows:
     88`Field                    Type     Facet          Result   Search
     89-----------------------  -------  -------------  ------   -------------
     90id                       uint     Yes (default)  No       Yes (default)
     91post_author              uint     Yes (default)  No       Yes (default)
     92post_author_name         text     No             Yes      Yes (default)
     93taxonomy_category_id     literal  Yes            No       No
     94taxonomy_category_label  text     No             No       Yes (default)
     95post_content             text     No             No       Yes (default)
     96post_date_gmt            uint     Yes (default)  No       Yes (default)
     97post_status              literal  Yes            No       No
     98post_title               text     No             Yes      Yes (default)
     99post_type                literal  Yes            No       Yes
     100comment_count            uint     Yes (default)  No       Yes (default)
     101taxonomy_tags_id         literal  Yes            No       No
     102taxonomy_tags_label      text     No             No       Yes (default)`
     103
     104= Which post types are indexed by default? How do I modify which post types are indexed? =
     105By default, posts and pages are indexed. To modify this, use the `lift_indexed_post_types` filter which is an array of post types to index.
     106
    86107== Screenshots ==
    87108
     
    91112
    92113== Changelog ==
     114
     115= 1.2 =
     116* Bug Fix: Fixed bug where some fields would be deleted from AWS after update.
     117* Bug Fix: Fixed issue with ALTERNATE_CRON compatibility.
     118* Bug Fix: Fixed initialization of queuing all posts after setup.
     119* Bug Fix: Fixed post status handling when searching from the wp-admin.
     120* Refactor: Added un-install hooks for cleanup after deactivation.
     121* Refactor: Performance tweaks.
     122* Refactor: Removed references to WP_PLUGIN_DIR for more flexible installations
     123* Refactor: Updated storage for queued updates.
     124* Refactor: Added ability to disable voce-error-logging integration.
    93125
    94126= 1.1 =
  • lift-search/trunk/sass/admin.css

    r627882 r658221  
    77/* line 14, admin.scss */
    88#banneralert { margin-bottom: 10px; }
     9/* line 16, admin.scss */
     10#banneralert .clr { clear: both; margin: 0; height: 0; font-size: 0; }
    911
    10 /* line 18, admin.scss */
     12/* line 24, admin.scss */
    1113.lift-colorized { font-family: arial,sans-serif; padding: 12px; border: 1px #8bcce4 solid; background: #b3e2f3; /* Old browsers */ background: -moz-linear-gradient(top, #b3e2f3 59%, white 94%); /* FF3.6+ */ background: -webkit-gradient(linear, left top, left bottom, color-stop(59%, #b3e2f3), color-stop(94%, white)); /* Chrome,Safari4+ */ background: -webkit-linear-gradient(top, #b3e2f3 59%, white 94%); /* Chrome10+,Safari5.1+ */ background: -o-linear-gradient(top, #b3e2f3 59%, white 94%); /* Opera 11.10+ */ background: -ms-linear-gradient(top, #b3e2f3 59%, white 94%); /* IE10+ */ background: linear-gradient(to bottom, #b3e2f3 59%, #ffffff 94%); /* W3C */ filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#b3e2f3',endColorstr='#ffffff',GradientType=0 ); /* IE6-9 */ /* radii */ -moz-border-radius: 3px; -webkit-border-radius: 3px; border-radius: 3px; }
    1214
    13 /* line 29, admin.scss */
     15/* line 35, admin.scss */
    1416.lift-btn { border: 1px #416b05 solid; padding: 8px 46px; text-align: center; width: 200px; background: #c0fb6c; /* Old browsers */ background: -moz-linear-gradient(top, #c0fb6c 0%, #99d93c 2%, #609b0d 98%, #aceb53 100%); /* FF3.6+ */ background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #c0fb6c), color-stop(2%, #99d93c), color-stop(98%, #609b0d), color-stop(100%, #aceb53)); /* Chrome,Safari4+ */ background: -webkit-linear-gradient(top, #c0fb6c 0%, #99d93c 2%, #609b0d 98%, #aceb53 100%); /* Chrome10+,Safari5.1+ */ background: -o-linear-gradient(top, #c0fb6c 0%, #99d93c 2%, #609b0d 98%, #aceb53 100%); /* Opera 11.10+ */ background: -ms-linear-gradient(top, #c0fb6c 0%, #99d93c 2%, #609b0d 98%, #aceb53 100%); /* IE10+ */ background: linear-gradient(to bottom, #c0fb6c 0%, #99d93c 2%, #609b0d 98%, #aceb53 100%); /* W3C */ filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#c0fb6c',endColorstr='#aceb53',GradientType=0 ); /* IE6-9 */ color: #fff; text-shadow: rgba(0, 0, 0, 0.75) 0px 1px 0px; -moz-border-radius: 3px; -webkit-border-radius: 3px; border-radius: 3px; }
    1517
    16 /* line 39, admin.scss */
     18/* line 45, admin.scss */
    1719.lift-btn a { color: #fff; }
    1820
    19 /* line 40, admin.scss */
     21/* line 46, admin.scss */
    2022td.lift-sync { padding-bottom: .5em; }
    2123
    22 /* line 44, admin.scss */
     24/* line 50, admin.scss */
    2325.lift-auto-update-options h4 { margin-top: 0px; margin-bottom: .5em; }
    2426
    25 /* line 45, admin.scss */
     27/* line 51, admin.scss */
    2628#lift-submit-row { width: 315px; }
    2729
    28 /* line 48, admin.scss */
     30/* line 54, admin.scss */
    2931.lift-admin { /****** SETUP PAGE ******/ /****** STATUS PAGE ******/ }
    30 /* line 50, admin.scss */
     32/* line 56, admin.scss */
    3133.lift-admin .clr { clear: both; margin: 0; height: 0; font-size: 0; }
    32 /* line 56, admin.scss */
     34/* line 62, admin.scss */
    3335.lift-admin a { text-decoration: none; }
    34 /* line 60, admin.scss */
     36/* line 66, admin.scss */
    3537.lift-admin p em { background: #d7e5f1; display: inline-block; margin-left: -58px; margin-right: 13px; font-size: 1.5em; line-height: 42px; height: 42px; width: 42px; border-radius: 21px; font-style: normal; text-align: center; color: #464646; }
    36 /* line 75, admin.scss */
     38/* line 81, admin.scss */
    3739.lift-admin input[attr=disabled] { background: #999; color: #777; }
    38 /* line 80, admin.scss */
     40/* line 86, admin.scss */
    3941.lift-admin .indent { padding: 15px 2.7472527473%; border-top: 1px solid #d1d1d1; }
    40 /* line 84, admin.scss */
     42/* line 90, admin.scss */
    4143.lift-admin .lift-light-grey { color: #999; }
    42 /* line 88, admin.scss */
     44/* line 94, admin.scss */
    4345.lift-admin .header-img, .lift-admin .header-img img { width: 100%; }
    44 /* line 92, admin.scss */
     46/* line 98, admin.scss */
    4547.lift-admin h2.lift-logo { display: block; background: url(../img/lift-logo.png) no-repeat 0 8px; padding-left: 44px; }
    46 /* line 96, admin.scss */
     48/* line 102, admin.scss */
    4749.lift-admin h2.lift-logo em { color: #0e5abd; font: italic 0.8125em Georgia, serif; }
    48 /* line 101, admin.scss */
     50/* line 107, admin.scss */
    4951.lift-admin #update-ajax-loader { position: absolute; margin: 7px 0 0 -20px; }
    50 /* line 106, admin.scss */
     52/* line 112, admin.scss */
    5153.lift-admin .success-message { color: green; }
    52 /* line 109, admin.scss */
     54/* line 115, admin.scss */
    5355.lift-admin .error-message { color: red; }
    54 /* line 112, admin.scss */
     56/* line 118, admin.scss */
    5557.lift-admin .width-70 { width: 70%; }
    56 /* line 114, admin.scss */
     58/* line 120, admin.scss */
    5759.lift-admin .width-70 input, .lift-admin .width-70 select { margin-bottom: 10px; }
    58 /* line 117, admin.scss */
     60/* line 123, admin.scss */
    5961.lift-admin .width-70 .misc-pub-section { padding-top: 0; }
    60 /* line 121, admin.scss */
     62/* line 127, admin.scss */
    6163.lift-admin .width-30 { width: 30%; }
    62 /* line 124, admin.scss */
     64/* line 130, admin.scss */
    6365.lift-admin .btn { border: 1px solid #bbb; border-radius: 8px; line-height: 18px; padding: 0 10px; font-size: 14px; text-decoration: none; margin-left: 10px; color: #464646; font-family: 'Helvetica Nueue', Helvetica, Arial, sans-serif; }
    64 /* line 139, admin.scss */
     66/* line 145, admin.scss */
    6567.lift-admin .ordered-list { padding-left: 58px; }
    66 /* line 141, admin.scss */
     68/* line 147, admin.scss */
    6769.lift-admin .ordered-list p { line-height: 1em; }
    68 /* line 144, admin.scss */
     70/* line 150, admin.scss */
    6971.lift-admin .ordered-list .form-table th:first-child { padding-left: 0; }
    70 /* line 147, admin.scss */
     72/* line 153, admin.scss */
    7173.lift-admin .ordered-list .lift-step-3[disabled="disabled"], .lift-admin .ordered-list .lift-step-4[disabled="disabled"] { color: #ccc; cursor: default; }
    72 /* line 156, admin.scss */
     74/* line 162, admin.scss */
    7375.lift-admin .dashboard { border: 1px solid #d1d1d1; padding-bottom: 15px; }
    74 /* line 160, admin.scss */
     76/* line 166, admin.scss */
    7577.lift-admin .dashboard #lift-remote-status { padding: 0 8px; }
    76 /* line 164, admin.scss */
     78/* line 170, admin.scss */
    7779.lift-admin .dashboard .lift-snapshot { width: 100%; border-bottom: 1px solid #e6e6e6; font-size: 16px; border-spacing: 0; }
    78 /* line 169, admin.scss */
     80/* line 175, admin.scss */
    7981.lift-admin .dashboard .lift-snapshot hr { background: #999; background: rgba(0, 0, 0, 0.2); margin: 12px 0; height: 1px; overflow: hidden; font-size: 0; border: none; }
    80 /* line 178, admin.scss */
     82/* line 184, admin.scss */
    8183.lift-admin .dashboard .lift-snapshot h3 { margin: 4px 0 16px 0; }
    82 /* line 181, admin.scss */
     84/* line 187, admin.scss */
    8385.lift-admin .dashboard .lift-snapshot td { background: #f6f6f6; width: 66%; border-left: 1px solid #d1d1d1; padding: 13px 14px 0 14px; vertical-align: top; }
    84 /* line 187, admin.scss */
     86/* line 193, admin.scss */
    8587.lift-admin .dashboard .lift-snapshot td.status { vertical-align: middle; width: 20%; background: #99cd67; border-bottom: 7px solid #659b31; border-left: none; padding-left: 13px; }
    86 /* line 195, admin.scss */
     88/* line 201, admin.scss */
    8789.lift-admin .dashboard .lift-snapshot td.edit { vertical-align: middle; text-align: center; width: 14%; background: #f6f6f6 url(../img/status.png) no-repeat 0 -64px; padding: 0 10px; }
    88 /* line 203, admin.scss */
    89 .lift-admin .dashboard .lift-snapshot td.status h3 { font: bold 1.375em/1.18182em "Helvetica Neue", Helvetica, Arial, sans-serif; color: #fff; padding: 0 0 0 47px; text-transform: uppercase; position: relative; margin-bottom: 0; }
    90 /* line 211, admin.scss */
     90/* line 209, admin.scss */
     91.lift-admin .dashboard .lift-snapshot td.status h3 { font: bold 1.375em/1.182em "Helvetica Neue", Helvetica, Arial, sans-serif; color: #fff; padding: 0 0 0 47px; text-transform: uppercase; position: relative; margin-bottom: 0; }
     92/* line 217, admin.scss */
    9193.lift-admin .dashboard .lift-snapshot td.status h3:after { position: absolute; content: ''; display: block; background: url(../img/status.png) no-repeat; width: 34px; height: 34px; top: -3px; left: 0; }
    92 /* line 223, admin.scss */
     94/* line 229, admin.scss */
    9395.lift-admin .dashboard .lift-snapshot td.status p { display: none; text-align: left; margin: 0; padding: 0 0 0 49px; font-weight: normal; font-size: .85em; }
    94 /* line 230, admin.scss */
     96/* line 236, admin.scss */
    9597.lift-admin .dashboard .lift-snapshot td.status p a { font-size: .75em; text-decoration: none; }
    96 /* line 234, admin.scss */
     98/* line 240, admin.scss */
    9799.lift-admin .dashboard .lift-snapshot td.status p a:hover { text-decoration: underline; }
    98 /* line 239, admin.scss */
     100/* line 245, admin.scss */
    99101.lift-admin .dashboard .lift-snapshot td.status ul { padding: 0 3px 0 20px; list-style: square; font-size: .85em; }
    100 /* line 247, admin.scss */
     102/* line 253, admin.scss */
    101103.lift-admin .dashboard .lift-snapshot td.status.caution { background-color: #fac604; border-color: #d3a700; }
    102 /* line 251, admin.scss */
     104/* line 257, admin.scss */
    103105.lift-admin .dashboard .lift-snapshot td.status.caution p a { color: #7e6400; }
    104 /* line 255, admin.scss */
     106/* line 261, admin.scss */
    105107.lift-admin .dashboard .lift-snapshot td.status.caution h3:after { background-position: -44px 0; }
    106 /* line 259, admin.scss */
     108/* line 265, admin.scss */
    107109.lift-admin .dashboard .lift-snapshot td.status.error { background-color: #c10c0c; border-color: #8f0909; }
    108 /* line 263, admin.scss */
     110/* line 269, admin.scss */
    109111.lift-admin .dashboard .lift-snapshot td.status.error p a { color: #fff; }
    110 /* line 267, admin.scss */
     112/* line 273, admin.scss */
    111113.lift-admin .dashboard .lift-snapshot td.status.error h3:after { background-position: -93px 0; }
    112 /* line 272, admin.scss */
     114/* line 278, admin.scss */
    113115.lift-admin .dashboard .lift-snapshot td.status.caution p, .lift-admin .dashboard .lift-snapshot td.status.error p { display: block; }
    114 /* line 279, admin.scss */
     116/* line 285, admin.scss */
    115117.lift-admin .dashboard .lift-snapshot .status-message { font-weight: bold; }
    116 /* line 283, admin.scss */
     118/* line 289, admin.scss */
    117119.lift-admin .dashboard .lift-snapshot input.cron-update { width: 5em; text-align: center; }
    118 /* line 288, admin.scss */
     120/* line 294, admin.scss */
    119121.lift-admin .dashboard .lift-snapshot table.lift-schedule { width: 110%; float: right; }
    120 /* line 291, admin.scss */
     122/* line 297, admin.scss */
    121123.lift-admin .dashboard .lift-snapshot table.lift-schedule td { padding: 0px; border: none; text-align: right; }
    122 /* line 297, admin.scss */
     124/* line 303, admin.scss */
    123125.lift-admin .dashboard .lift-snapshot table.lift-schedule td:first-child { width: 10%; text-align: left; }
    124 /* line 303, admin.scss */
     126/* line 309, admin.scss */
    125127.lift-admin .dashboard .lift-snapshot .lift-index-now { padding-top: .5em; float: right; }
    126 /* line 310, admin.scss */
     128/* line 316, admin.scss */
    127129.lift-admin .dashboard .misc-pub-section { border: none; font-size: .75em; margin: 0; padding: 7px 0 0 0; }
    128 /* line 317, admin.scss */
     130/* line 323, admin.scss */
    129131.lift-admin .dashboard .log-table td { text-align: left; }
    130 /* line 321, admin.scss */
     132/* line 327, admin.scss */
    131133.lift-admin .dashboard #set-cron-status { text-align: center; position: relative; display: block; margin: 0; float: right; width: 110px; height: 30px; border-radius: 6px; -moz-border-radius: 6px; -webkit-border-radius: 6px; background: #F6F6F6; -webkit-transition: all 0.25s ease-in-out; -moz-transition: all 0.25s ease-in-out; transition: all 0.25s ease-in-out; cursor: pointer; -webkit-box-shadow: inset 1px 1px 10px 1px #999; box-shadow: inset 1px 1px 10px 1px #999; }
    132 /* line 340, admin.scss */
     134/* line 346, admin.scss */
    133135.lift-admin .dashboard #set-cron-status .slider-button { display: block; width: 60px; height: 30px; line-height: 30px; padding-top: 0; padding-bottom: 0; border-radius: 6px; -moz-border-radius: 6px; -webkit-border-radius: 6px; text-align: center; box-sizing: border-box; -moz-box-sizing: border-box; -webkit-box-sizing: border-box; }
    134 /* line 355, admin.scss */
     136/* line 361, admin.scss */
    135137.lift-admin .dashboard #set-cron-status .on { margin-left: 49px; }
    136 /* line 358, admin.scss */
     138/* line 364, admin.scss */
    137139.lift-admin .dashboard #set-cron-status.disabled, .lift-admin .dashboard #set-cron-status.disabled span:hover, .lift-admin .dashboard #set-cron-status.disabled span:focus { cursor: default !important; border-color: #bbb; }
    138 /* line 362, admin.scss */
     140/* line 368, admin.scss */
    139141.lift-admin .dashboard #set-cron-status.disabled .on, .lift-admin .dashboard #set-cron-status.disabled .on:hover { background: gray; border: 1px solid #999; box-shadow: none; -moz-box-shadow: none; -webkit-box-shadow: none; border-color: #999; }
  • lift-search/trunk/sass/admin.scss

    r627882 r658221  
    1414#banneralert {
    1515    margin-bottom: 10px;
     16    .clr {
     17        clear: both;
     18        margin: 0;
     19        height: 0;
     20        font-size: 0;
     21    }
    1622}
    1723
  • lift-search/trunk/wp/lift-health.php

    r633627 r658221  
    44
    55    class Lift_Health {
    6        
    7         /**
    8          * Combine the remote and local health into one
    9          *
    10          * @return array
    11          */
    12         public static function get_overall_status() {
    13            
    14             $local_status = self::get_local_status();
    15             $remote_status = self::get_remote_status();
    16            
    17             $reason = array();
    18            
    19             if ( $local_status['reason'] ) {
    20                 $reason[] = $local_status['reason'];
    21             }
    22             if ( $remote_status['reason'] ) {
    23                 $reason[] = $remote_status['reason'];
    24             }
    25 
    26             $severity = max( $local_status['severity'], $remote_status['severity'] );
    27             $errors = ( $local_status['errors'] or $remote_status['errors'] );
    28            
    29             $remote_status = $remote_status['status'];
    30             $local_status = $local_status['status'];
    31 
    32             $results = compact(
    33                 'severity',
    34                 'reason',
    35                 'errors',
    36                 'remote_status',
    37                 'local_status'
    38             );
    39 
    40             return $results;
    41         }
     6
     7        /**
     8         * Combine the remote and local health into one
     9         *
     10         * @return array
     11         */
     12        public static function get_overall_status() {
     13
     14            $local_status = self::get_local_status();
     15            $remote_status = self::get_remote_status();
     16
     17            $reason = array( );
     18
     19            if ( $local_status['reason'] ) {
     20                $reason[] = $local_status['reason'];
     21            }
     22            if ( $remote_status['reason'] ) {
     23                $reason[] = $remote_status['reason'];
     24            }
     25
     26            $severity = max( $local_status['severity'], $remote_status['severity'] );
     27            $errors = ( $local_status['errors'] or $remote_status['errors'] );
     28
     29            $remote_status = $remote_status['status'];
     30            $local_status = $local_status['status'];
     31
     32            $results = compact(
     33                'severity', 'reason', 'errors', 'remote_status', 'local_status'
     34            );
     35
     36            return $results;
     37        }
    4238
    4339        /**
     
    5147         */
    5248        public static function get_local_status() {
     49            if(!Lift_Search::error_logging_enabled()) {
     50                return array('severity' => 0, 'reason' => '', 'errors' => false, 'status' => 0);
     51            }
     52           
    5353            $intervals = array(
    5454                60 * 60 => array( 'severity' => 2, 'threshold' => 5 ), // 1 hr
     
    5959
    6060            $severity = 0;
    61             $reason = '';
    62             $errors = false;
     61            $reason = '';
     62            $errors = false;
    6363
    6464            foreach ( $intervals as $interval => $data ) {
     
    6767                add_filter( 'posts_where', array( __CLASS__, 'filter_posts_where' ) );
    6868                $q = new WP_Query( array(
    69                             'posts_per_page' => -1,
    70                             'post_type' => Voce_Error_Logging::POST_TYPE,
    71                             'tax_query' => array( array(
    72                                     'taxonomy' => Voce_Error_Logging::TAXONOMY,
    73                                     'field' => 'slug',
    74                                     'terms' => array( 'error', 'lift-search' ),
    75                                     'operator' => 'AND'
     69                        'posts_per_page' => 1,
     70                        'post_type' => Voce_Error_Logging::POST_TYPE,
     71                        'tax_query' => array( array(
     72                                'taxonomy' => Voce_Error_Logging::TAXONOMY,
     73                                'field' => 'slug',
     74                                'terms' => array( 'error', 'lift-search' ),
     75                                'operator' => 'AND'
    7676                            ) ),
    7777                        ) );
    7878                remove_filter( 'posts_where', array( __CLASS__, 'filter_posts_where' ) );
    7979
    80                 $post_count = $q->post_count;
    81                
     80                $post_count = $q->found_posts;
     81
    8282                if ( $post_count >= $data['threshold'] ) {
    83                     $errors = true;
     83                    $errors = true;
    8484                    $severity = $data['severity'];
    85                     $reason = sprintf( '%d or more errors in the last %s', $data['threshold'], human_time_diff( time() - $interval ) );
     85                    $reason = sprintf( '%d or more errors in the last %s', $data['threshold'], human_time_diff( time() - $interval ) );
    8686                }
    8787
     
    9595
    9696            $results = array(
    97                 'errors' => $errors,
     97                'errors' => $errors,
    9898                'severity' => $severity,
    99                 'reason' => $reason,
     99                'reason' => $reason,
    100100                'status' => $error_counts,
    101101            );
     
    106106        /**
    107107         * used for local health checks to get recent logs
    108         *
     108        *
    109109         * @global int $lift_health_interval
    110110         * @param string $where
     
    119119            return $where;
    120120        }
    121        
    122         /**
    123          * use the config API to get the CloudSearch domain/index status
    124          *
    125          * @return array
    126          */
    127         public static function get_remote_status() {
    128             $domain = Cloud_Config_Request::DescribeDomain( Lift_Search::get_search_domain() );
    129            
    130             if ( ! $domain ) {
    131                 return array(
    132                     'errors' => true,
    133                     'reason' => 'Domain has been deleted or the CloudSearch API request failed.',
    134                     'severity' => 2,
    135                     'status' => array(
    136                         'fatal' => true,
    137                         'text' => 'Domain has been deleted or the CloudSearch API request failed',
    138                     ),
    139                 );
    140             }
    141 
    142             $errors = false;
    143             $severity = 0;
    144             $reason = '';
    145            
    146             $text = 'active';
    147            
    148             $pending = ( ! $domain->Created && ! $domain->Deleted );
    149             $deleting = $domain->Deleted;
    150             $processing = $domain->Processing;
    151             $num_searchable_docs = $domain->NumSearchableDocs;
    152             $needs_indexing = $domain->RequiresIndexDocuments;
    153             $search_instance_count = $domain->SearchInstanceCount;
    154             $search_instance_type = $domain->SearchInstanceType;
    155             $search_partition_count = $domain->SearchPartitionCount;
    156            
    157             if ( $deleting ) {
    158                 $severity = 2;
    159                 $reason = 'CloudSearch domain being deleted';
    160                 $text = 'being deleted';
    161             } else if ( $needs_indexing || $processing  ) {
    162                 if ( 0 == $search_instance_count ) {
    163                     $severity = 1;
    164                     $reason = 'CloudSearch domain loading';
    165                     $text = 'loading';
    166                 } else if ( $needs_indexing ) {
    167                     $severity = 1;
    168                     $reason = 'CloudSearch domain needs indexing';
    169                     $text = 'needs indexing';
    170                 } else {
    171                     $severity = 1;
    172                     $reason = 'CloudSearch domain processing';
    173                     $text = 'processing';
    174                 }
    175             } else if ( $pending ) {
    176                 $severity = 1;
    177                 $reason = 'CloudSearch domain pending';
    178                 $text = 'pending';
    179             }
    180            
    181             if (0 != $severity) {
    182                 $errors = true;
    183             }
    184            
    185            
    186             $status = compact(
    187                 'text',
    188                 'pending',
    189                 'deleting',
    190                 'processing',
    191                 'num_searchable_docs',
    192                 'needs_indexing',
    193                 'search_instance_count',
    194                 'search_instance_type',
    195                 'search_partition_count'
    196             );
    197            
    198             $status['api_error'] = false;
    199             $status['text'] = $text;
    200            
    201             $results = array(
    202                 'errors' => $errors,
     121
     122        /**
     123         * use the config API to get the CloudSearch domain/index status
     124         *
     125         * @return array
     126         */
     127        public static function get_remote_status() {
     128            $domain = Cloud_Config_Request::DescribeDomain( Lift_Search::get_search_domain() );
     129
     130            if ( !$domain ) {
     131                return array(
     132                    'errors' => true,
     133                    'reason' => 'Domain has been deleted or the CloudSearch API request failed.',
     134                    'severity' => 2,
     135                    'status' => array(
     136                        'fatal' => true,
     137                        'text' => 'Domain has been deleted or the CloudSearch API request failed',
     138                    ),
     139                );
     140            }
     141
     142            $errors = false;
     143            $severity = 0;
     144            $reason = '';
     145
     146            $text = 'active';
     147
     148            $pending = (!$domain->Created && !$domain->Deleted );
     149            $deleting = $domain->Deleted;
     150            $processing = $domain->Processing;
     151            $num_searchable_docs = $domain->NumSearchableDocs;
     152            $needs_indexing = $domain->RequiresIndexDocuments;
     153            $search_instance_count = $domain->SearchInstanceCount;
     154            $search_instance_type = $domain->SearchInstanceType;
     155            $search_partition_count = $domain->SearchPartitionCount;
     156
     157            if ( $deleting ) {
     158                $severity = 2;
     159                $reason = 'CloudSearch domain being deleted';
     160                $text = 'being deleted';
     161            } else if ( $needs_indexing || $processing ) {
     162                if ( 0 == $search_instance_count ) {
     163                    $severity = 1;
     164                    $reason = 'CloudSearch domain loading';
     165                    $text = 'loading';
     166                } else if ( $needs_indexing ) {
     167                    $severity = 1;
     168                    $reason = 'CloudSearch domain needs indexing';
     169                    $text = 'needs indexing';
     170                } else {
     171                    $severity = 1;
     172                    $reason = 'CloudSearch domain processing';
     173                    $text = 'processing';
     174                }
     175            } else if ( $pending ) {
     176                $severity = 1;
     177                $reason = 'CloudSearch domain pending';
     178                $text = 'pending';
     179            }
     180
     181            if ( 0 != $severity ) {
     182                $errors = true;
     183            }
     184
     185
     186            $status = compact(
     187                'text', 'pending', 'deleting', 'processing', 'num_searchable_docs', 'needs_indexing', 'search_instance_count', 'search_instance_type', 'search_partition_count'
     188            );
     189
     190            $status['api_error'] = false;
     191            $status['text'] = $text;
     192
     193            $results = array(
     194                'errors' => $errors,
    203195                'severity' => $severity,
    204                 'reason' => $reason,
    205                 'status' => $status,
    206             );
    207                
    208             return $results;
    209         }
     196                'reason' => $reason,
     197                'status' => $status,
     198            );
     199
     200            return $results;
     201        }
    210202
    211203    }
  • lift-search/trunk/wp/lift-search-form.php

    r642501 r658221  
    11<?php
    2 
    32// Make sure class name doesn't exist
    43if ( !class_exists( 'Lift_Search_Form' ) ) {
     
    3736        private function __construct() {
    3837            add_filter( 'lift_filters_default_fields', function($defaults) {
    39                         $remove = array( 'post_categories', 'post_tags' );
    40                         $filtered = array_diff( $defaults, $remove );
    41                         return $filtered;
    42                     } );
     38                    $remove = array( 'post_categories', 'post_tags' );
     39                    $filtered = array_diff( $defaults, $remove );
     40                    return $filtered;
     41                } );
    4342
    4443            $this->additional_fields();
     
    7372         */
    7473        public function add_sort_field() {
    75             if ( ! $selected = Lift_Search_Form::get_query_var( 'orderby' ) ) {
     74            if ( !$selected = Lift_Search_Form::get_query_var( 'orderby' ) ) {
    7675                $selected = 'relevancy';
    7776            }
    7877            $options = array(
    79                 'label' => ($selected) ? ucwords($selected) : 'Sort By',
     78                'label' => ($selected) ? ucwords( $selected ) : 'Sort By',
    8079                'value' => array(
    8180                    'Date' => 'date',
     
    116115            $types = Lift_Search::get_indexed_post_types();
    117116            $selected_types = Lift_Search_Form::get_query_var( 'post_types' );
    118             $label = ( ! $selected_types ) ? 'All Types' : '';
    119             $selected_labels = array();
    120             if ( ! is_array( $selected_types) ) {
     117            $label = (!$selected_types ) ? 'All Types' : '';
     118            $selected_labels = array( );
     119            if ( !is_array( $selected_types ) ) {
    121120                $selected_types = array( $selected_types );
    122121            }
    123            
     122
    124123            $values = array(
    125124                'All Types' => ''
    126125            );
    127            
     126
    128127            foreach ( $types as $type ) {
    129128                $num = (isset( $wp_query->query_vars['facets'] ) && isset( $wp_query->query_vars['facets']['post_type'][$type] )) ? sprintf( '(%s)', $wp_query->query_vars['facets']['post_type'][$type] ) : '';
     
    132131                $values[sprintf( '%s %s', $type_object->label, $num )] = $type;
    133132            }
    134            
    135            
     133
     134
    136135            foreach ( $values as $k => $v ) {
    137136                if ( in_array( $v, $selected_types ) ) {
     
    139138                }
    140139            }
    141            
    142             if ( ! $label ) {
     140
     141            if ( !$label ) {
    143142                $label = join( ' / ', $selected_labels );
    144143            }
     
    171170                '30 Days' => $date_end - (86400 * 30)
    172171            );
    173            
     172
    174173            $selected_label = 'Date';
    175174            foreach ( $values as $k => $v ) {
     
    179178            }
    180179            $label = ( $date_start ) ? $selected_label : 'All Dates';
    181            
     180
    182181            $this->add_field( 'date_start', 'select', array(
    183182                'label' => $label,
    184183                'value' => $values,
    185                 'selected' => (int) $date_start,
     184                'selected' => ( int ) $date_start,
    186185            ) );
    187186        }
     
    215214         */
    216215        public function form() {
    217             $search_term = (is_search()) ? get_search_query() : "" ;
    218             $html = '<form role="search" class="lift-search" id="searchform"><div>';
     216            $search_term = (is_search()) ? get_search_query() : "";
     217            $html = '<form role="search" class="lift-search" id="searchform" action="'.site_url().'/"><div>';
    219218            $html .= "<input type='text' name='s' id='s' value='$search_term' />";
    220             $html .= ' <input type="submit" id="searchsubmit" value="'. esc_attr__('Search') .'" />';
     219            $html .= ' <input type="submit" id="searchsubmit" value="' . esc_attr__( 'Search' ) . '" />';
    221220            $html .= $this->form_filters();
    222221            $html .= "</div></form>";
     
    226225
    227226        public function loop() {
    228             $path = WP_PLUGIN_DIR . '/lift-search/templates/lift-loop.php';
     227            $path = dirname(__DIR__) . '/lift-search/templates/lift-loop.php';
    229228            include_once $path;
    230229        }
    231230
    232231        public function form_filters() {
    233             if ( ! is_search() ) {
     232            if ( !is_search() ) {
    234233                return;
    235234            }
    236            
     235
    237236            $fields = apply_filters( 'lift_filters_form_field_objects', $this->fields );
    238237            $html = '<fieldset class="lift-search-form-filters">';
     
    263262                    $html .= $field->faux_element( $counter == count( $fields ) );
    264263                }
    265                 $counter ++;
     264                $counter++;
    266265            }
    267266            $html .= "</ul></div>";
     
    426425                return false;
    427426            }
    428            
     427
    429428            $options = '';
    430429            $has_selection = false;
    431430            $last_class = ( $last ) ? 'last' : '';
    432            
     431
    433432            foreach ( $this->options['value'] as $k => $v ) {
    434433                $selected = "";
     
    440439                    $has_selection = true;
    441440                }
    442                 $options .= sprintf( '<li class="lift-list-item %s %s" data-lift_value="%s" ><a href="#">%s</a></li>', $selected, $last, $v, $k ) ;
    443             }
    444            
     441                $options .= sprintf( '<li class="lift-list-item %s %s" data-lift_value="%s" ><a href="#">%s</a></li>', $selected, $last, $v, $k );
     442            }
     443
    445444            $selected_class = ( $has_selection ) ? 'selected' : '';
    446            
    447             $html = sprintf('<li class="lift-list-toggler %s" id="lift-list-toggler-%s" data-role="list-toggler"><a href="#" class="%s">%s</a>', $last_class, $this->id, $selected_class, $this->options['label'] );
     445
     446            $html = sprintf( '<li class="lift-list-toggler %s" id="lift-list-toggler-%s" data-role="list-toggler"><a href="#" class="%s">%s</a>', $last_class, $this->id, $selected_class, $this->options['label'] );
    448447            $html .= "<ul class='lift-select-list lift-hidden' data-lift_bind='$this->id'>";
    449448            $html .= $options;
     
    494493    public function __construct() {
    495494        parent::__construct(
    496                 'lift_form_widget', "Lift Search Form", array( 'description' => "Add a Lift search form" )
     495            'lift_form_widget', "Lift Search Form", array( 'description' => "Add a Lift search form" )
    497496        );
    498497    }
     
    506505        extract( $args );
    507506        $title = apply_filters( 'widget_title', empty( $instance['title'] ) ? '' : $instance['title'], $instance, $this->id_base );
    508        
     507
    509508        echo $before_widget;
    510509        if ( $title )
    511510            echo $before_title . $title . $after_title;
    512        
     511
    513512        if ( class_exists( 'Lift_Search_Form' ) ) {
    514513            echo Lift_Search_Form::GetInstance()->form();
     
    516515        echo $after_widget;
    517516    }
    518    
     517
    519518    function form( $instance ) {
    520         $instance = wp_parse_args( (array) $instance, array( 'title' => '') );
     519        $instance = wp_parse_args( ( array ) $instance, array( 'title' => '' ) );
    521520        $title = $instance['title'];
    522 ?>
    523         <p><label for="<?php echo $this->get_field_id('title'); ?>"><?php _e('Title:'); ?> <input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo esc_attr($title); ?>" /></label></p>
    524 <?php
     521        ?>
     522        <p><label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( 'Title:' ); ?> <input class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" type="text" value="<?php echo esc_attr( $title ); ?>" /></label></p>
     523        <?php
    525524    }
    526525
    527526    function update( $new_instance, $old_instance ) {
    528527        $instance = $old_instance;
    529         $new_instance = wp_parse_args((array) $new_instance, array( 'title' => ''));
    530         $instance['title'] = strip_tags($new_instance['title']);
     528        $new_instance = wp_parse_args( ( array ) $new_instance, array( 'title' => '' ) );
     529        $instance['title'] = strip_tags( $new_instance['title'] );
    531530        return $instance;
    532531    }
     
    535534
    536535add_action( 'widgets_init', function() {
    537             register_widget( 'Lift_Form_Widget' );
    538         } );
    539 
     536        register_widget( 'Lift_Form_Widget' );
     537    } );
     538
  • lift-search/trunk/wp/lift-update-queue.php

    r627882 r658221  
    1414
    1515    const STORAGE_POST_TYPE = 'lift_queued_document';
    16 
    17     public static function get_queue_count() {
    18         global $wpdb;
    19        
    20         if(false === ($queue_count = wp_cache_get('lift_update_queue_count'))) {
    21             $queue_count = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT( 1 ) FROM $wpdb->posts
    22                 WHERE post_type = %s", self::STORAGE_POST_TYPE) );
    23            
    24             wp_cache_set('lift_update_queue_count', $queue_count);
    25         }
    26        
    27         return $queue_count;
    28     }
    29    
     16    const QUEUE_IDS_OPTION = 'lift_queue_ids';
     17
     18    /**
     19     * Gives the post_id representing the closed/completed queue.
     20     * The closed queue is the one that is currently no longer accepting
     21     * new changes and is waiting or in the process of being sent in batches
     22     *
     23     * @return int
     24     */
     25    public static function get_closed_queue_id() {
     26        return self::get_queue_id( 'closed' );
     27    }
     28
     29    /**
     30     * Gives the post_id representing the current active queue that all
     31     * new changes are saved to. 
     32     *
     33     * @return int
     34     */
     35    public static function get_active_queue_id() {
     36        return self::get_queue_id( 'active' );
     37    }
     38
     39    /**
     40     * Closes the active queue and creates a new active queue to start
     41     * storing new updates
     42     *
     43     * @return type
     44     */
     45    public static function close_active_queue() {
     46        $lock_name = 'lift_close_active_queue';
     47       
     48        $lock_key = md5( uniqid( microtime() . mt_rand(), true ) );
     49        if ( !get_transient( $lock_name ) ) {
     50            set_transient( $lock_name, $lock_key, 60 );
     51        }
     52
     53        if ( get_transient( $lock_name ) !== $lock_key ) {
     54            //another server/request has this lock
     55            return;
     56        }
     57       
     58       
     59        $active_queue_id = self::get_active_queue_id();
     60        $closed_queue_id = self::get_closed_queue_id();
     61       
     62        update_option( self::QUEUE_IDS_OPTION, array(
     63            'active' => $closed_queue_id,
     64            'closed' => $active_queue_id
     65        ));
     66       
     67        delete_transient($lock_name);
     68    }
     69
     70    private static function get_queue_id( $type ) {
     71        $queue_ids = get_option( self::QUEUE_IDS_OPTION, array( ) );
     72
     73        $queue_id = isset( $queue_ids[$type] ) ? $queue_ids[$type] : false;
     74
     75        if ( !$queue_id || !get_post( $queue_id ) ) {
     76            //queue post doesn't yet exist, create one
     77            $queue_id = wp_insert_post( array(
     78                'post_type' => self::STORAGE_POST_TYPE,
     79                'post_status' => 'publish',
     80                'post_title' => 'lift queue post'
     81                ) );
     82
     83            $queue_ids[$type] = $queue_id;
     84
     85            update_option( self::QUEUE_IDS_OPTION, $queue_ids );
     86        }
     87
     88        return $queue_id;
     89    }
     90
    3091    /**
    3192     * Sets a document field to be queued for an update
     
    52113
    53114    /**
    54      * Gets the instance of the LiftUpdateDocument for the given document.
     115     * Gets the instance of the LiftUpdateDocument for the given document from the active
     116     * batch.  A new instance is created if there isn't yet one.
    55117     * @param int $document_id
    56118     * @param string $document_type
     
    58120     */
    59121    public static function get_queued_document_updates( $document_id, $document_type = 'post' ) {
    60         $key = $document_type . '_' . $document_id;
     122        $key = 'lift_update_' . $document_type . '_' . $document_id;
    61123        if ( isset( self::$document_update_docs[$key] ) ) {
    62124            return self::$document_update_docs[$key];
    63125        }
    64126
    65         if ( $update_post = self::get_document_update_post( $document_id, $document_type ) ) {
    66             $post_meta_content = get_post_meta($update_post->ID, 'lift_content', true);
    67             $update_data = ( array ) maybe_unserialize( $post_meta_content );
     127        if ( is_array( $update_data = get_post_meta( self::get_active_queue_id(), $key ) ) ) {
    68128            $action = isset( $update_data['action'] ) ? $update_data['action'] : 'add';
    69129            $fields = isset( $update_data['fields'] ) ? ( array ) $update_data['fields'] : array( );
     
    75135        self::$document_update_docs[$key] = $document_update_doc;
    76136        return $document_update_doc;
    77     }
    78 
    79     /**
    80      * Retrieves the post used to store the queued document update
    81      * @param int $document_id
    82      * @param string $document_type
    83      * @return WP_Post|null
    84      */
    85     private static function get_document_update_post( $document_id, $document_type ) {
    86         $post_name = $document_type . '-' . $document_id;
    87         if ( false === ($post_id = wp_cache_get( 'lift_queue_post_id_' . $post_name ) ) ) {
    88             $posts = get_posts( array(
    89                 'post_type' => self::STORAGE_POST_TYPE,
    90                 'posts_per_page' => 1,
    91                 'name' => $post_name,
    92                 'fields' => 'ids'
    93                 ) );
    94 
    95             if ( count( $posts ) === 1 ) {
    96                 $post_id = $posts[0];
    97                 wp_cache_set( 'lift_queue_post_id_' . $post_name, $post_id );
    98                 wp_cache_delete('lift_update_queue_count');
    99             }
    100         }
    101 
    102         return $post_id ? get_post( $post_id ) : false;
    103137    }
    104138
     
    127161
    128162        add_action( 'shutdown', array( __CLASS__, '_save_updates' ) );
    129        
     163
    130164        Lift_Post_Update_Watcher::init();
    131165        Lift_Post_Meta_Update_Watcher::init();
    132166        Lift_Taxonomy_Update_Watcher::init();
     167    }
     168
     169    public static function query_updates( $args = array( ) ) {
     170        global $wpdb;
     171
     172        $defaults = array(
     173            'page' => 1,
     174            'per_page' => 10,
     175            'queue_ids' => self::get_active_queue_id(),
     176        );
     177
     178        extract( $args = wp_parse_args( $args, $defaults ) );
     179
     180        $page = is_int( $page ) ? max( $page, 1 ) : 1;
     181        $per_page = intval( $per_page );
     182
     183        $queue_ids = array_map( 'intval', ( array ) $queue_ids );
     184
     185
     186        $limit = 'LIMIT ' . ($page - 1) * $per_page . ', ' . $per_page;
     187
     188        $query = "SELECT SQL_CALC_FOUND_ROWS meta_id, meta_key, post_id FROM $wpdb->postmeta " .
     189            "WHERE post_id in (" . join( ',', $queue_ids ) . ") AND meta_key like 'lift_update_%' " .
     190            "ORDER BY meta_id " .
     191            $limit;
     192
     193        $meta_rows = $wpdb->get_results( $query );
     194        $found_rows = $wpdb->get_var( "SELECT FOUND_ROWS()" );
     195
     196        return ( object ) array(
     197                'query_args' => $args,
     198                'meta_rows' => $meta_rows,
     199                'found_rows' => $found_rows,
     200                'num_pages' => ceil( $found_rows / $per_page )
     201        );
    133202    }
    134203
     
    141210                continue;
    142211            }
    143             $new = false;
    144             if ( false == ($post = self::get_document_update_post( $change_doc->document_id, $change_doc->document_type ) ) ) {
    145                 $post = array(
    146                         'post_type' => self::STORAGE_POST_TYPE,
    147                         'post_name' => $change_doc->document_type . '-' . $change_doc->document_id,
    148                         'post_title' => $change_doc->document_type . '-' . $change_doc->document_id,
    149                         'post_status' => 'publish',
    150                         'post_content' => '',
    151                 );
    152                 $new = true;
    153             }
    154 
    155             $post_content = serialize( array(
     212
     213            $key = 'lift_update_' . $change_doc->document_type . '_' . $change_doc->document_id;
     214
     215            $update_data = array(
    156216                'document_id' => $change_doc->document_id,
    157217                'document_type' => $change_doc->document_type,
    158218                'action' => $change_doc->action,
    159                 'fields' => $change_doc->fields
    160                 ) );
    161 
    162 
    163             if ( ( $post_id = wp_insert_post( $post ) ) && $new ) {
    164                 wp_cache_set( 'lift_queue_post_id_' . $change_doc->document_type . '_' . $change_doc->document_id, $post_id );
    165             }
    166             update_post_meta($post_id, 'lift_content', $post_content);
    167         }
    168     }
    169 
    170 }
     219                'fields' => $change_doc->fields,
     220                'update_date_gmt' => current_time( 'mysql', 1 ),
     221                'update_date' => current_time( 'mysql' )
     222            );
     223            update_post_meta( self::get_active_queue_id(), $key, $update_data );
     224        }
     225    }
     226
     227    public static function _deactivation_cleanup() {
     228        global $wpdb;
     229
     230        $batch_post_ids = $wpdb->get_col( $wpdb->prepare( "SELECT ID FROM $wpdb->posts
     231            WHERE post_type = %s", self::STORAGE_POST_TYPE ) );
     232        foreach ( $batch_post_ids as $post_id ) {
     233            wp_delete_post( $post_id, true );
     234        }
     235    }
     236
     237}
     238
    171239add_action( 'init', array( 'Lift_Document_Update_Queue', 'init' ), 2 );
    172240
  • lift-search/trunk/wp/lift-wp-search.php

    r627882 r658221  
    99 * functionality:
    1010 *
    11  *  lift_search_facets: Array - Modify the facets set on the Lift Search Query
     11 *  lift_search_facets: Array - Modify the facets set on the Lift Search Query
    1212 *
    13  *  lift_override_post_results: Boolean - If set to be true, a Lift search will be skipped
     13 *  lift_override_post_results: Boolean - If set to be true, a Lift search will be skipped
    1414 *  and default WP search is performed
    1515 *
    16  *  lift_filter_query: Lift_Search_Query - Modify the Lift_Search_Query that was
    17  *  created from the WP_Query
     16 *  lift_filter_query: Lift_Search_Query - Modify the Lift_Search_Query that was
     17 *  created from the WP_Query
    1818 *
    1919 */
     
    2323
    2424    public static function init() {
    25         add_filter( 'posts_request', function( $request, $wp_query ){
    26             if( $wp_query->is_search() )
    27                 return false;
    28             return $request;
    29         }, 10, 2);
    30 
    31         add_filter( 'posts_results', array(  __CLASS__, 'posts_results'), 10, 2 );
     25        add_filter( 'posts_request', function( $request, $wp_query ) {
     26                if ( $wp_query->is_search() )
     27                    return false;
     28                return $request;
     29            }, 10, 2 );
     30
     31        add_filter( 'posts_results', array( __CLASS__, 'posts_results' ), 10, 2 );
    3232        add_filter( 'query_vars', function($query_vars) {
    33             return array_merge( $query_vars, array( 'facet', 'date_start', 'date_end', 'post_types' ) );
    34         });
     33                return array_merge( $query_vars, array( 'facet', 'date_start', 'date_end', 'post_types' ) );
     34            } );
    3535    }
    3636
     
    4040     * @return object $lift_search_query
    4141     */
    42     public static function lift_search_query($wp_query){
     42    public static function lift_search_query( $wp_query ) {
    4343
    4444        $lift_search_query = new Cloud_Search_Query();
     
    4848        $tax_queries = self::parse_tax_queries( $wp_query->tax_query );
    4949
    50         $parameters = array();
     50        $parameters = array( );
    5151
    5252        // label
     
    5656        $post_type = $wp_query->get( 'post_types' );
    5757        if ( $post_type && ( 'any' !== $post_type ) ) {
    58             $post_type_field_obj = new Lift_Field('post_type', $post_type);
    59             $post_type_field = new Lift_Field_Expression(array( $post_type_field_obj ));
     58            $post_type_field_obj = new Lift_Field( 'post_type', $post_type );
     59            $post_type_field = new Lift_Field_Expression( array( $post_type_field_obj ) );
    6060
    6161            $parameters[] = self::build_match_expression( $post_type_field );
    6262        }
    6363
    64         $parameters[] = self::get_query_post_status($wp_query);
     64        $parameters[] = self::get_query_post_status( $wp_query );
    6565
    6666        foreach ( array( 'post_category', 'post_tag' ) as $taxonomy ) {
    6767            if ( isset( $tax_queries[$taxonomy] ) ) {
    68                 $post_taxonomy_field_obj = new Lift_Field($taxonomy, $tax_queries[$taxonomy], false);
    69                 $post_taxonomy_field = new Lift_Field_Expression(array( $post_type_field_obj ));
     68                $post_taxonomy_field_obj = new Lift_Field( $taxonomy, $tax_queries[$taxonomy], false );
     69                $post_taxonomy_field = new Lift_Field_Expression( array( $post_type_field_obj ) );
    7070
    7171                $parameters[] = self::build_match_expression( $post_taxonomy_field );
     
    7474
    7575        $date_start = $wp_query->get( 'date_start' );
    76         $date_end   = $wp_query->get( 'date_end' );
     76        $date_end = $wp_query->get( 'date_end' );
    7777
    7878        if ( $date_start || $date_end ) {
     
    101101
    102102        $orderby_values = array(
    103             'date'      => 'post_date_gmt',
     103            'date' => 'post_date_gmt',
    104104            'relevancy' => 'text_relevance',
    105             'lift'      => 'weighted_text_relevance'
     105            'lift' => 'weighted_text_relevance'
    106106        );
    107107
    108108        // rank
    109         $order   = $wp_query->get( 'order' );
    110         $orderby = isset($orderby_values[$wp_query->get('orderby')]) ? $orderby_values[$wp_query->get('orderby')] : $orderby_values['relevancy'];
     109        $order = $wp_query->get( 'order' );
     110        $orderby = isset( $orderby_values[$wp_query->get( 'orderby' )] ) ? $orderby_values[$wp_query->get( 'orderby' )] : $orderby_values['relevancy'];
    111111
    112112        if ( $orderby )
     
    119119    }
    120120
    121     public static function get_query_post_status($wp_query){
    122         $ret_status = array();
    123         if ( ! empty( $_REQUEST['post_status'] ) ) {
    124             $q_status = $_REQUEST['post_status'];
    125             if ( ! is_array( $q_status ) )
    126                 $q_status = array($q_status);
    127             $public_states = get_post_stati(array('public' => true));
    128             if ( !in_array('any', $q_status) && !in_array('all', $q_status) ){
    129                 foreach($q_status as $status){
    130                     if(in_array($status, $public_states))
    131                         $ret_status[] = $status;
     121    public static function get_query_post_status( $wp_query ) {
     122
     123        $q = $wp_query->query_vars;
     124       
     125        $user_ID = get_current_user_id();
     126
     127        //mimic wp_query logic around post_type since it isn't performed on an accessible copy
     128        $post_type = $q['post_type'];
     129        if ( $wp_query->is_tax && empty( $post_type ) ) {
     130            $post_type = array( );
     131            $taxonomies = wp_list_pluck( $wp_query->tax_query->queries, 'taxonomy' );
     132            foreach ( get_post_types( array( 'exclude_from_search' => false ) ) as $pt ) {
     133                $object_taxonomies = $pt === 'attachment' ? get_taxonomies_for_attachments() : get_object_taxonomies( $pt );
     134                if ( array_intersect( $taxonomies, $object_taxonomies ) )
     135                    $post_type[] = $pt;
     136            }
     137            if ( !$post_type )
     138                $post_type = 'any';
     139        }
     140
     141        //direct copy from wp_query 3.5
     142        if ( is_array( $post_type ) ) {
     143            $post_type_cap = 'multiple_post_type';
     144        } else {
     145            $post_type_object = get_post_type_object( $post_type );
     146            if ( empty( $post_type_object ) )
     147                $post_type_cap = $post_type;
     148        }
     149
     150        //direct copy from wp_query 3.5
     151        if ( 'any' == $post_type ) {
     152            //unused code
     153        } elseif ( !empty( $post_type ) && is_array( $post_type ) ) {
     154            //unused code
     155        } elseif ( !empty( $post_type ) ) {
     156            $post_type_object = get_post_type_object( $post_type );
     157        } elseif ( $wp_query->is_attachment ) {
     158            $post_type_object = get_post_type_object( 'attachment' );
     159        } elseif ( $wp_query->is_page ) {
     160            $post_type_object = get_post_type_object( 'page' );
     161        } else {
     162            $post_type_object = get_post_type_object( 'post' );
     163        }
     164
     165        //direct copy from wp_query 3.5
     166        if ( !empty( $post_type_object ) ) {
     167            $edit_cap = $post_type_object->cap->edit_post;
     168            $read_cap = $post_type_object->cap->read_post;
     169            $edit_others_cap = $post_type_object->cap->edit_others_posts;
     170            $read_private_cap = $post_type_object->cap->read_private_posts;
     171        } else {
     172            $edit_cap = 'edit_' . $post_type_cap;
     173            $read_cap = 'read_' . $post_type_cap;
     174            $edit_others_cap = 'edit_others_' . $post_type_cap . 's';
     175            $read_private_cap = 'read_private_' . $post_type_cap . 's';
     176        }
     177
     178        if ( !empty( $q['post_status'] ) ) {
     179            $statuswheres = array( );
     180            $q_status = $q['post_status'];
     181            $stati_expression = new Lift_Expression_Set( 'and' );
     182
     183            if ( !is_array( $q_status ) )
     184                $q_status = explode( ',', $q_status );
     185            $r_status = array( );
     186            $r_stati_expression = new Lift_Expression_Set( );
     187            $p_status = array( );
     188            $p_stati_expression = new Lift_Expression_Set();
     189            $e_status = array( );
     190            $e_stati_expression = new Lift_Expression_Set( 'and' );
     191
     192            if ( in_array( 'any', $q_status ) ) {
     193                foreach ( get_post_stati( array( 'exclude_from_search' => true ) ) as $status ) {
     194                    $e_stati_expression->addExpression( new Lift_Expression_Field( 'post_status', '-' . $status ) );
     195                }
     196            } else {
     197                foreach ( get_post_stati() as $status ) {
     198                    if ( in_array( $status, $q_status ) ) {
     199                        if ( 'private' == $status ) {
     200                            $p_stati_expression->addExpression( new Lift_Expression_Field( 'post_status', $status ) );
     201                        } else {
     202                            $r_stati_expression->addExpression( new Lift_Expression_Field( 'post_status', $status ) );
     203                        }
     204                    }
     205                }
     206            }
     207
     208            if ( empty( $q['perm'] ) || 'readable' != $q['perm'] ) {
     209                foreach ( $p_stati_expression->sub_expressions as $expression ) {
     210                    $r_stati_expression->addExpression( $expression );
     211                }
     212                unset( $p_stati_expression );
     213            }
     214
     215            if ( isset( $r_stati_expression ) && count( $r_stati_expression ) ) {
     216                if ( !empty( $q['perm'] ) && 'editable' == $q['perm'] && !current_user_can( $edit_others_cap ) ) {
     217                    $tmp_expression = new Lift_Expression_Set( 'and', array( new Lift_Expression_Field( 'post_author', $user_ID, false ), $r_stati_expression ) );
     218                    $stati_expression->addExpression( $tmp_expression );
     219                } else {
     220                    $stati_expression->addExpression( $r_stati_expression );
     221                }
     222            }
     223
     224            if ( !empty( $p_status ) ) {
     225                if ( !empty( $q['perm'] ) && 'readable' == $q['perm'] && !current_user_can( $read_private_cap ) ) {
     226                    $tmp_expression = new Lift_Expression_Set( 'and', array( new Lift_Expression_Field( 'post_author', $user_ID, false ), $p_stati_expression ) );
     227                    $stati_expression->addExpression( $tmp_expression );
     228                } else {
     229                    $stati_expression->addExpression( $p_stati_expression );
    132230                }
    133231            }
    134232        } elseif ( !$wp_query->is_singular ) {
     233            $stati_expression = new Lift_Expression_Set( );
    135234
    136235            // Add public states.
    137             $public_states = get_post_stati( array('public' => true) );
    138             foreach ( (array) $public_states as $state ) {
    139                 $ret_status[] = $state;
     236            $public_states = get_post_stati( array( 'public' => true ) );
     237            foreach ( ( array ) $public_states as $state ) {
     238                $stati_expression->addExpression( new Lift_Expression_Field( 'post_status', $state ) );
    140239            }
    141240
    142241            if ( $wp_query->is_admin ) {
    143242                // Add protected states that should show in the admin all list.
    144                 $admin_all_states = get_post_stati( array('protected' => true, 'show_in_admin_all_list' => true) );
    145                 foreach ( (array) $admin_all_states as $state )
    146                     $ret_status[] = $state;
    147             }
    148 
    149             $ret_status_field_objects = self::build_field_objs( 'post_status', $ret_status );
    150 
    151             $ret_status_field = new Lift_Field_Expression($ret_status_field_objects);
     243                $admin_all_states = get_post_stati( array( 'protected' => true, 'show_in_admin_all_list' => true ) );
     244                foreach ( ( array ) $admin_all_states as $state )
     245                    $stati_expression->addExpression( new Lift_Expression_Field( 'post_status', $state ) );
     246            }
    152247
    153248            if ( is_user_logged_in() ) {
    154249                // Add private states that are limited to viewing by the author of a post or someone who has caps to read private states.
    155                 $private_states = get_post_stati( array('private' => true) );
    156 
    157                 $post_author_field_object = new Lift_Field('post_author', get_current_user_id(), false);
    158 
    159                 foreach ( (array) $private_states as $state ) {
    160                     $state_field_object = new Lift_Field('post_status', $state);
    161                     $state_field = new Lift_Field_Expression(array( $state_field_object, $post_author_field_object ), 'and');
    162 
    163                     $ret_status_field->field_objs[] = $state_field;
    164                 }
    165             }
    166 
    167             $matched_expression = self::build_match_expression( $ret_status_field );
    168         }
    169 
    170         return $matched_expression;
     250                $private_states = get_post_stati( array( 'private' => true ) );
     251                foreach ( ( array ) $private_states as $state ) {
     252                    if ( current_user_can( $read_private_cap ) ) {
     253                        $stati_expression->addExpression( new Lift_Expression_Field( 'post_status', $state ) );
     254                    } else {
     255                        $tmp_expression = new Lift_Expression_Set( 'and', array(
     256                                new Lift_Expression_Field( 'post_author', $user_ID, false ),
     257                                new Lift_Expression_Field( 'post_status', $state ),
     258                                ) );
     259                        $stati_expression->addExpression( $tmp_expression );
     260                    }
     261                }
     262            }
     263        }
     264
     265        return (string) $stati_expression;
    171266    }
    172267
     
    179274     * @return array $posts
    180275     */
    181     public static function posts_results( $posts, $wp_query ){
     276    public static function posts_results( $posts, $wp_query ) {
    182277        if ( !apply_filters( 'lift_override_post_results', true ) || !$wp_query->is_search() )
    183278            return $posts;
     
    188283        $lift_api = Lift_Search::get_search_api();
    189284
    190         $lift_results = $lift_api->sendSearch($lift_query);
    191 
    192         if( !empty($lift_results) && is_object($lift_results) ){
     285        $lift_results = $lift_api->sendSearch( $lift_query );
     286
     287        if ( !empty( $lift_results ) && is_object( $lift_results ) ) {
    193288            // include response post ids in query
    194             $hits = array();
     289            $hits = array( );
    195290            array_map( function($hit) use (&$hits) {
    196                     if(property_exists($hit, 'data') && property_exists($hit->data, 'id') ){
    197                         $hits[] = (is_array($hit->data->id)) ? array_shift($hit->data->id) : $hit->data->id;
     291                    if ( property_exists( $hit, 'data' ) && property_exists( $hit->data, 'id' ) ) {
     292                        $hits[] = (is_array( $hit->data->id )) ? array_shift( $hit->data->id ) : $hit->data->id;
    198293                    }
    199294                }, $lift_results->hits->hit
     
    202297            // include facets on query
    203298            if ( isset( $lift_results->facets ) )
    204                 $wp_query->set( 'facets', self::format_facet_constraints($lift_results->facets) );
     299                $wp_query->set( 'facets', self::format_facet_constraints( $lift_results->facets ) );
    205300
    206301            _prime_post_caches( $hits );
    207             $posts = array_values( array_filter( array_map( 'get_post', $hits ), function($val){
    208                 return (!is_null($val) && !is_wp_error($val) && is_object($val) && $val->post_status == 'publish');
    209             }) );
    210             $wp_query->post_count = count($posts);
     302            $posts = array_values( array_map( 'get_post', $hits ) );
     303            $wp_query->post_count = count( $posts );
    211304            $wp_query->found_posts = $lift_results->hits->found;
    212             $wp_query->max_num_pages = ceil( $wp_query->found_posts / get_query_var('posts_per_page') );
     305            $wp_query->max_num_pages = ceil( $wp_query->found_posts / get_query_var( 'posts_per_page' ) );
    213306            $wp_query->posts = $posts;
    214 
    215307        }
    216308        return $posts;
     
    223315     */
    224316    private static function parse_tax_queries( $tax_queries ) {
    225         $parsed_tax_queries = array();
     317        $parsed_tax_queries = array( );
    226318
    227319        $defaults = array(
    228320            'taxonomy' => '',
    229             'terms' => array(),
     321            'terms' => array( ),
    230322            'include_children' => true,
    231323            'field' => 'term_id',
     
    235327        foreach ( $tax_queries as $tax_query ) {
    236328            // Lift search currently only supports the IN operator for taxonomies, if anything else,
    237             if ( ! is_array( $tax_query ) ||
    238                 !isset($tax_query['operator']) ||
    239                 $tax_query['operator'] =! 'IN' ||
    240                     empty( $tax_query['taxonomy'] ) ){
     329            if ( !is_array( $tax_query ) ||
     330                !isset( $tax_query['operator'] ) ||
     331                $tax_query['operator'] = !'IN' ||
     332                empty( $tax_query['taxonomy'] ) ) {
    241333                continue;
    242334            }
     
    244336            $tax_query = array_merge( $defaults, $tax_query );
    245337
    246             $tax_query['terms'] = (array) $tax_query['terms'];
     338            $tax_query['terms'] = ( array ) $tax_query['terms'];
    247339
    248340            // if terms ids are provided, we can just add them to the $parsed_tax_queries array,
    249341            // otherwise we have to get each id
    250             if ( $tax_query['field'] == 'term_id' ){
     342            if ( $tax_query['field'] == 'term_id' ) {
    251343
    252344                if ( isset( $parsed_tax_queries[$tax_query['taxonomy']] ) )
    253                     $parsed_tax_queries[$tax_query['taxonomy']] = array_merge ( $parsed_tax_queries[$tax_query['taxonomy']], $tax_query['terms'] );
     345                    $parsed_tax_queries[$tax_query['taxonomy']] = array_merge( $parsed_tax_queries[$tax_query['taxonomy']], $tax_query['terms'] );
    254346                else
    255347                    $parsed_tax_queries[$tax_query['taxonomy']] = $tax_query['terms'];
     
    261353                    }
    262354                }
    263 
    264355            } else {
    265356
    266                 $terms = array();
     357                $terms = array( );
    267358
    268359                foreach ( $tax_query['terms'] as $term ) {
     
    273364                        // if tax query has the include_children argument set to true
    274365                        if ( $tax_query['include_children'] )
    275                             $terms = array_merge ( $terms, get_term_children( $term_obj->term_id, $term_obj->taxonomy ) );
     366                            $terms = array_merge( $terms, get_term_children( $term_obj->term_id, $term_obj->taxonomy ) );
    276367                    }
    277368                }
     
    284375    }
    285376
     377    /**
     378     * Helper function to build an array of Lift_Field objects of the same field with multiple values
     379     * @param string $field_name
     380     * @param array $field_values
     381     * @param bool $is_string true if the field is a string
     382     * @return Lift_Field
     383     */
    286384    private function build_field_objs( $field_name, $field_values, $is_string = true ) {
    287385
    288         $field_objects = array();
     386        $field_objects = array( );
    289387
    290388        foreach ( $field_values as $field_value ) {
    291             $field_objects[] = new Lift_Field($field_name, $field_value, ( $is_string === true ) ? $is_string : false);
     389            $field_objects[] = new Lift_Field( $field_name, $field_value, ( $is_string === true ) ? $is_string : false );
    292390        }
    293391
     
    302400     * If multiple values, the expression will take the form:  ($operator $field:$value1 ... $field:$valueN)
    303401     *
    304      * @return string
     402     * @param Lift_Field_Expression $field
     403     * @return string
    305404     */
    306405    private static function build_match_expression( $field ) {
    307406
    308         $expression = array();
     407        $expression = array( );
    309408
    310409        if ( is_a( $field, 'Lift_Field_Expression' ) && is_array( $field->field_objs ) ) {
     
    318417            foreach ( $field->field_objs as $field_obj ) {
    319418
    320                 if (is_a( $field_obj , 'Lift_Field_Expression' ) ) {
     419                if ( is_a( $field_obj, 'Lift_Field_Expression' ) ) {
    321420
    322421                    $expression[] = self::build_match_expression( $field_obj );
    323 
    324422                } else {
    325423
    326424                    if ( $field_obj->is_string ) {
    327425
    328                         $expression[]= $field_obj->field_name . ":'" . addslashes( $field_obj->field_value ) . "'";
    329 
     426                        $expression[] = $field_obj->field_name . ":'" . addslashes( $field_obj->field_value ) . "'";
    330427                    } else {
    331428
    332                         $expression[]= "{$field_obj->field_name}:{$field_obj->field_value}";
     429                        $expression[] = "{$field_obj->field_name}:{$field_obj->field_value}";
    333430                    }
    334431                }
     
    341438    }
    342439
    343     private static function format_facet_constraints($facets){
    344         $formatted_facets = array();
    345         $facets = self::object_to_array($facets);
    346         if(is_array($facets)) {
    347             foreach($facets as $facet_type => $facet_value){
    348                 $formatted_facets[$facet_type] = array();
    349                 if(isset($facet_value['constraints'])){
    350                     foreach($facet_value['constraints'] as $facet){
    351                         if(isset($facet['value']) && isset($facet['count']))
     440    private static function format_facet_constraints( $facets ) {
     441        $formatted_facets = array( );
     442        $facets = self::object_to_array( $facets );
     443        if ( is_array( $facets ) ) {
     444            foreach ( $facets as $facet_type => $facet_value ) {
     445                $formatted_facets[$facet_type] = array( );
     446                if ( isset( $facet_value['constraints'] ) ) {
     447                    foreach ( $facet_value['constraints'] as $facet ) {
     448                        if ( isset( $facet['value'] ) && isset( $facet['count'] ) )
    352449                            $formatted_facets[$facet_type][$facet['value']] = $facet['count'];
    353450                    }
     
    358455    }
    359456
    360     private static function object_to_array($data){
    361         if (is_array($data) || is_object($data)){
    362             $result = array();
    363             foreach ($data as $key => $value){
    364                 $result[$key] = self::object_to_array($value);
     457    private static function object_to_array( $data ) {
     458        if ( is_array( $data ) || is_object( $data ) ) {
     459            $result = array( );
     460            foreach ( $data as $key => $value ) {
     461                $result[$key] = self::object_to_array( $value );
    365462            }
    366463            return $result;
     
    368465        return $data;
    369466    }
     467
    370468}
    371469
    372 class Lift_Field_Expression {
    373     public $field_objs;
     470abstract class aLift_Expression {
     471
     472    public function __construct() {
     473        //nothing to do here
     474    }
     475
     476    abstract public function __toString();
     477}
     478
     479class Lift_Expression_Set extends aLift_Expression implements Countable {
     480
     481    public $sub_expressions;
    374482    public $operator;
    375483
    376     function __construct($field_objs, $operator = 'or'){
    377         $this->field_objs = $field_objs;
     484    public function __construct( $operator = 'or', $sub_expressions = array( ) ) {
     485        parent::__construct();
     486        $this->sub_expressions = $sub_expressions;
    378487        $this->operator = $operator;
    379488    }
     489
     490    /**
     491     *
     492     * @param aLift_Expression $expression
     493     */
     494    public function addExpression( $expression ) {
     495        $this->sub_expressions[] = $expression;
     496    }
     497
     498    public function __toString() {
     499        return sprintf( '(%s %s)', $this->operator, join( ' ', $this->sub_expressions ) );
     500    }
     501
     502    public function count() {
     503        return count( $this->sub_expressions );
     504    }
     505
    380506}
    381507
    382 
    383 class Lift_Field {
     508class Lift_Expression_Field extends aLift_Expression {
     509
    384510    public $field_name;
    385511    public $field_value;
    386512    public $is_string;
    387513
    388     function __construct($field_name, $field_value, $is_string = true){
     514    public function __construct( $field_name, $field_value, $is_string = true ) {
     515        parent::__construct();
    389516        $this->field_name = $field_name;
    390517        $this->field_value = $field_value;
    391518        $this->is_string = $is_string;
    392519    }
     520
     521    public function __toString() {
     522        if ( $this->is_string ) {
     523            return $this->field_name . ":'" . addslashes( $this->field_value ) . "'";
     524        } else {
     525            return "{$this->field_name}:{$this->field_value}";
     526        }
     527    }
     528
    393529}
     530
     531/**
     532 * @deprecated
     533 */
     534class Lift_Field_Expression {
     535
     536    public $field_objs;
     537    public $operator;
     538
     539    /**
     540     * @param array $field_Array of Lift_Field objects
     541     * @param string $operator default 'or'
     542     */
     543    public function __construct( $field_objs, $operator = 'or' ) {
     544        $this->field_objs = $field_objs;
     545        $this->operator = $operator;
     546    }
     547
     548    public function __toString() {
     549        return '';
     550    }
     551
     552}
     553
     554/**
     555 * @deprecated
     556 */
     557class Lift_Field {
     558
     559    public $field_name;
     560    public $field_value;
     561    public $is_string;
     562
     563    function __construct( $field_name, $field_value, $is_string = true ) {
     564        $this->field_name = $field_name;
     565        $this->field_value = $field_value;
     566        $this->is_string = $is_string;
     567    }
     568
     569}
  • lift-search/trunk/wp/update-watchers/post.php

    r627882 r658221  
    44
    55    public static function get_watched_post_types() {
    6         return apply_filters( 'lift_watched_post_types', array( 'post', 'page' ) );
     6        return apply_filters( 'lift_watched_post_types', Lift_Search::get_indexed_post_types() );
    77    }
    88
     
    1919                ), $post_type );
    2020    }
    21    
    22     public static function check_post_validity($post_status, $post_type) {
    23         return ( ! in_array( $post_status, array( 'open', 'auto-draft' ) ) && in_array( $post_type, Lift_Post_Update_Watcher::get_watched_post_types() ) );
     21
     22    public static function check_post_validity( $post_status, $post_type ) {
     23        return (!in_array( $post_status, array( 'open', 'auto-draft' ) ) && in_array( $post_type, Lift_Post_Update_Watcher::get_watched_post_types() ) );
    2424    }
    2525
     
    2828        //catch new posts
    2929        add_filter( 'wp_insert_post_data', function($data, $postarr) {
    30                 if ( Lift_Post_Update_Watcher::check_post_validity($data['post_status'], $data['post_type']) ) {
     30                if ( Lift_Post_Update_Watcher::check_post_validity( $data['post_status'], $data['post_type'] ) ) {
    3131
    3232                    if ( empty( $postarr['ID'] ) ) {
     
    3535                        add_action( 'save_post', function($post_id, $post) {
    3636                                //check to make sure this isn't a revision insert
    37                             $_post = $post;
     37                                $_post = $post;
    3838                                if ( in_array( get_post_type( $post_id ), Lift_Post_Update_Watcher::get_watched_post_types() ) ) {
    3939                                    Lift_Post_Update_Watcher::queue_entire_post( $post_id );
     
    5151                $post_status = get_post_status( $post_id );
    5252                $post_type = get_post_type( $post_id );
    53                 if ( Lift_Post_Update_Watcher::check_post_validity($post_status, $post_type) ) {
    54                     if($post_before->post_status == 'auto-draft') {
     53                if ( Lift_Post_Update_Watcher::check_post_validity( $post_status, $post_type ) ) {
     54                    if ( $post_before->post_status == 'auto-draft' ) {
    5555                        Lift_Post_Update_Watcher::queue_entire_post( $post_id );
    5656                    } else {
     
    6969                $post_status = get_post_status( $post_id );
    7070                $post_type = get_post_type( $post_id );
    71                 if ( Lift_Post_Update_Watcher::check_post_validity($post_status, $post_type) ) {
     71                if ( Lift_Post_Update_Watcher::check_post_validity( $post_status, $post_type ) ) {
    7272                    lift_queue_deletion( $post_id, 'post' );
    7373                }
     
    133133
    134134    public function get_watched_taxonomies( $post_type ) {
    135        
     135
    136136        $default_taxonomies = array(
    137             'post' => array('category', 'post_tag'),
     137            'post' => array( 'category', 'post_tag' ),
    138138        );
    139         return apply_filters( 'lift_watched_taxonomies', isset($default_taxonomies[$post_type]) ? $default_taxonomies[$post_type] : array(), $post_type );
     139        return apply_filters( 'lift_watched_taxonomies', isset( $default_taxonomies[$post_type] ) ? $default_taxonomies[$post_type] : array( ), $post_type );
    140140    }
    141141
     
    144144                $post_type = get_post_type( $post_id );
    145145                if ( in_array( $taxonomy, Lift_Taxonomy_Update_Watcher::get_watched_taxonomies( $post_type ) ) ) {
    146                     if ( $append || array_diff( $old_tt_ids, $tt_ids ) || array_diff($tt_ids, $old_tt_ids) ) {
     146                    if ( $append || array_diff( $old_tt_ids, $tt_ids ) || array_diff( $tt_ids, $old_tt_ids ) ) {
    147147                        lift_queue_field_update( $post_id, 'taxonomy_' . $taxonomy, 'post' );
    148148                    }
Note: See TracChangeset for help on using the changeset viewer.