Working on an import for Event Manager plugin
authorSteve Sutton <steve@gaslightmedia.com>
Fri, 26 Jan 2018 19:58:19 +0000 (14:58 -0500)
committerSteve Sutton <steve@gaslightmedia.com>
Fri, 26 Jan 2018 20:02:09 +0000 (15:02 -0500)
This imports all events from the plugin Event Manager.

models/admin/management/events.php
views/admin/management/events.html

index 2d7983c..7c536d5 100644 (file)
@@ -209,6 +209,16 @@ class GlmMembersAdmin_management_events extends GlmDataEventsManagement
                 $import_result = $this->importFromTimely();
                 break;
 
+            case 'eventsManagerImport':
+                $import = false;
+                if (isset($_REQUEST['import'])) {
+                    $import = filter_var( $_REQUEST['import'], FILTER_VALIDATE_BOOLEAN );
+                }
+                $import_result = $this->importFromEventsManager();
+                //$categories = get_terms( 'event-categories' );
+                //echo '<pre>$categories: ' . print_r( $categories, true ) . '</pre>';
+                break;
+
             case 'icalfeed':
                 if ( isset( $_REQUEST['option2'] ) ) {
                     $option2 = filter_var( $_REQUEST['option2'], FILTER_SANITIZE_STRING );
@@ -581,6 +591,41 @@ class GlmMembersAdmin_management_events extends GlmDataEventsManagement
         update_option( 'glm-member-event-old-cat-map', serialize( $this->oldCatMap ) );
         return "<p>Adding $category_counter Categories</p>";
     }
+    public function addEventManagerCategories() {
+        $category_counter = 0;
+        $categories = get_terms( 'event-categories' );
+        foreach ( $categories as $category ) {
+            ++$category_counter;
+            // first check to see if the category is already there
+            $sql = "
+            SELECT id
+              FROM " . GLM_MEMBERS_EVENTS_PLUGIN_DB_PREFIX . "categories
+             WHERE name = '" . esc_sql( trim($category->name) ) . "'";
+            $found   = $this->wpdb->get_row($sql, ARRAY_A);
+            if ( !isset($found) ) {
+                $this->wpdb->insert(
+                    GLM_MEMBERS_EVENTS_PLUGIN_DB_PREFIX . 'categories',
+                    array(
+                        'name'     => trim($category->name),
+                        'parent' => $category->parent
+                    ),
+                    array(
+                        '%s',
+                        '%d'
+                    )
+                );
+                $catid = $this->wpdb->insert_id;
+                $this->categories[$catid] = trim($category->name);
+                $this->oldCatMap[$category->term_id] = $catid;
+            } else {
+                $this->categories[$found['id']] = trim($category->name);
+                $this->oldCatMap[$category->term_id] = $found['id'];
+            }
+        }
+        // Store the oldCatMap for the next pages.
+        update_option( 'glm-member-event-old-cat-map', serialize( $this->oldCatMap ) );
+        return "<p>Adding $category_counter Categories</p>";
+    }
     public function getOldCatMap()
     {
         return unserialize( get_option('glm-member-event-old-cat-map') );
@@ -1696,6 +1741,396 @@ class GlmMembersAdmin_management_events extends GlmDataEventsManagement
             . "&start=$start\">Next</a></p>";
         return $return_string;
     }
+    public function importFromEventsManager() {
+        $limit = 100;
+        $debug = false;
+        if ( isset( $_REQUEST['start'] ) ) {
+            $start = filter_var( $_REQUEST['start'], FILTER_VALIDATE_INT );
+        } else {
+            $start = 0;
+        }
+        if ( $start === 0 ) {
+            // clear the events tables first.
+            $this->clearData();
+            // Add the Categories from Time.ly.
+            $return_string = $this->addEventManagerCategories();
+        } else {
+            $this->oldCatMap = $this->getOldCatMap();
+        }
+
+        $yearly_events =
+        $daily_events =
+        $weekly_events =
+        $interval_events =
+        $monthly_events =
+        $custom_date_events = 0;
+
+        $Recurrences = new GlmDataEventsRecurrences($this->wpdb, $this->config);
+        require_once GLM_MEMBERS_PLUGIN_PATH.'/models/admin/ajax/imageUpload.php';
+        $image_upload = new GlmMembersAdmin_ajax_imageUpload($this->wpdb, $this->config);
+
+        $sql = "
+        SELECT *
+          FROM " . $this->wpdb->prefix . "posts
+         WHERE post_type = 'event'
+           AND post_status = 'publish'
+           AND ID IN (
+               SELECT distinct post_id
+                 FROM " . $this->wpdb->prefix . "em_events
+                -- WHERE event_end_date >= '2017-06-01'
+                WHERE event_end_date >= '2018-01-26'
+                )";
+        $sql .= " LIMIT $limit OFFSET $start";
+        $results = $this->wpdb->get_results( $sql, ARRAY_A );
+        //'<pre>$results: ' . print_r( $results, true ) . '</pre>';
+
+        $event_counter = 0;
+
+        if ( !empty( $results ) ) {
+            foreach ( $results as $post ) {
+                // Initialize some variables
+                $serialized_custom_times = null;
+                if ( $debug ) {
+                    echo '<div style="border:1px solid green;">';
+                }
+                ++$event_counter;
+                $sql = "
+                SELECT *
+                  FROM " . $this->wpdb->prefix . "em_events
+                 WHERE post_id = {$post['ID']}";
+                $event_data = $this->wpdb->get_row( $sql, ARRAY_A );
+                // echo '<pre>$event_data: ' . print_r( $event_data, true ) . '</pre>';
+                $att_data   = unserialize( $event_data['event_attributes'] );
+                $cost       = $att_data['Event Cost'];
+
+                // use the posts table data
+                $image = wp_get_attachment_image_src( $thumbnail_id, 'large' );
+                if ( $image ) {
+                    //echo '<pre>$thumb_src: ' . print_r($thumb_src, true) . '</pre>';
+                    $res = $image_upload->storeImage($thumb_src[0]);
+                    //echo '<pre>$res: ' . print_r($res, true) . '</pre>';
+                    if ( $res['newFileName'] ) {
+                        $image = $res['newFileName'];
+                    }
+                }
+
+                // Need the user data for admin and contact name phone and email
+                $user     = get_user_by( 'id', $event_data['event_owner'] );
+                // echo '<pre>$user: ' . print_r( $user, true ) . '</pre>';
+
+                $ref_dest = null;
+                // See if the user has a member then use this for ref_dest
+                if ( $user->data->user_login ) {
+                    $ref_dest = $this->wpdb->get_var(
+                        $this->wpdb->prepare(
+                            "SELECT id
+                               FROM " . GLM_MEMBERS_PLUGIN_DB_PREFIX . "members
+                              WHERE old_member_id = %s",
+                            $user->data->user_login
+                        )
+                    );
+                }
+
+                // Insert the event data
+                $event_import_data = array(
+                    'status'              => $this->config['status_numb']['Active'],
+                    'created'             => $post['post_date'],
+                    'updated'             => $post['post_modified'],
+                    'approved'            => $post['post_modified'],
+                    'name'                => $post['post_title'],
+                    'name_slug'           => $post['post_name'],
+                    'intro'               => mb_substr( strip_tags( $post['post_content'] ), 0, 80 ),
+                    'descr'               => $post['post_content'],
+                    'image'               => $image,
+                    'file1'               => null,
+                    'file1_descr'         => null,
+                    'cost'                => $cost,
+                    'free'                => 0,
+                    'url'                 => '',
+                    'old_event_id'        => $post['ID'],
+                    'ref_type'            => 10,
+                    'ref_dest'            => $ref_dest,
+                    'admin_name'          => $user->data->display_name,
+                    'admin_org'           => null,
+                    'admin_email'         => $user->data->user_email,
+                    'admin_phone'         => '',
+                    'contact_email'       => $user->data->user_email,
+                    'contact_name'        => $user->data->display_name,
+                    'contact_phone'       => '',
+                    'notes'               => null,
+                    'hide_address'        => null,
+                    'use_member_location' => 0,
+                );
+                $event_data_format = array(
+                    '%d', // Status
+                    '%s', // Created
+                    '%s', // Updated
+                    '%s', // Approved
+                    '%s', // Name
+                    '%s', // Name Slug
+                    '%s', // Intro
+                    '%s', // Descr
+                    '%s', // Image
+                    '%s', // File1
+                    '%s', // File1 Desc
+                    '%s', // Cost
+                    '%s', // Free
+                    '%s', // Url
+                    '%s', // Old_event_id
+                    '%s', // Ref Type
+                    '%s', // Ref Dest
+                    '%s', // Admin Name
+                    '%s', // Admin Org
+                    '%s', // Admin Email
+                    '%s', // Admin Phone
+                    '%s', // Contact Email
+                    '%s', // Contact Name
+                    '%s', // Contact Phone
+                    '%s', // Notes
+                    '%s', // Hide Address
+                    '%s', // Use Member Location
+                );
+                $is_insert = $this->wpdb->insert(
+                    GLM_MEMBERS_EVENTS_PLUGIN_DB_PREFIX . 'events',
+                    $event_import_data,
+                    $event_data_format
+                );
+                if ( $debug ) {
+                    var_dump( $is_insert );
+                }
+                $event_id  = $this->wpdb->insert_id;
+                if ( $debug ) {
+                    var_dump( $event_id );
+                }
+                if ( !$event_id ) {
+                    $this->wpdb->print_error();
+                    echo '<pre>$event_import_data: ' . print_r($event_import_data, true) . '</pre>';
+                    echo '<pre>SQL Error: ' . $this->wpdb->last_error . '</pre>';
+                    echo '<pre>SQL Error: ' . $this->wpdb->print_error() . '</pre>';
+                    die('something is wrong no event_id');
+                }
+                // get the post categories
+                $categories = array();
+                $post_terms = wp_get_post_terms( $post['ID'], 'event-categories', 'term_id' );
+                foreach ( $post_terms as $term ) {
+                    $this->wpdb->insert(
+                        GLM_MEMBERS_EVENTS_PLUGIN_DB_PREFIX . 'event_categories',
+                        array(
+                            'event'    => $event_id,
+                            'category' => $this->oldCatMap[$term->term_id]
+                        ),
+                        array(
+                            '%d',
+                            '%d'
+                        )
+                    );
+                }
+                if ( $debug ) {
+                    echo '<pre>$event_data: ' . print_r($event_data, true) . '</pre>';
+                    echo '<pre>$categories: ' . print_r($categories, true) . '</pre>';
+                }
+
+                // Stop processing this event
+                // return false;
+                // continue;
+
+                $by_day_of_month =
+                $last_day_of_month = null;
+
+                $recurring_event =
+                $start_time_only =
+                $recurring_event = 0;
+
+                $weekly =
+                $daily  = false;
+
+                $day_of_week   = 127;
+                $month_of_year = 4095;
+                $week_of_month = 63;
+
+                $custom_times = array();
+                $curZone = date_default_timezone_get();
+                if ( $debug ) {
+                    echo '<pre>$curZone: ' . print_r($curZone, true) . '</pre>';
+                }
+                // if ( $event_data['timezone_name'] ) {
+                //     date_default_timezone_set( $event_data['timezone_name'] );
+                // }
+                $curZone = date_default_timezone_get();
+                if ( $debug ) {
+                    echo '<pre>$curZone: ' . print_r($curZone, true) . '</pre>';
+                }
+
+                $from_date = $event_data['event_start_date'];
+                if ( $debug ) {
+                    echo '<pre>$from_date: ' . print_r($from_date, true) . '</pre>';
+                }
+                $to_date   = $event_data['event_end_date'];
+                // check if the $to_date has 0 hr
+                // if ( date( 'H', $event_data['event_end_date'] ) === '00' ) {
+                //     $ending_datetime = new DateTime( $to_date );
+                //     $ending_datetime->modify('- 1 day');
+                //     $to_date = $ending_datetime->format( 'Y-m-d' );
+                // }
+                if ( $debug ) {
+                    echo '<pre>$to_date: ' . print_r($to_date, true) . '</pre>';
+                }
+                $btime = $event_data['event_start_time'];
+                if ( $debug ) {
+                    echo '<pre>$btime: ' . print_r($btime, true) . '</pre>';
+                }
+                $etime = $event_data['event_end_time'];
+                if ( $debug ) {
+                    echo '<pre>$etime: ' . print_r($etime, true) . '</pre>';
+                }
+
+
+                if ($recurring_event && $from_date == $to_date && empty( $custom_times ) ) {
+                    // Add two years to the recurring event if dates match
+                    $starting_datetime = new DateTime( $from_date );
+                    $ending_date       = $starting_datetime->modify('2 years');
+                    $to_date           = $ending_date->format( 'Y-m-d' );
+                }
+                $all_day = $event_data['event_all_day'];
+
+                if ( $btime == $etime ) {
+                    $start_time_only = true;
+                }
+
+                // for the recurrences part
+                $recur_data = array(
+                    'event'                => $event_id,
+                    'name'                 => 'Imported',
+                    'start_time'           => $btime,
+                    'end_time'             => $etime,
+                    'start_time_only'      => $start_time_only,
+                    'from_date'            => $from_date,
+                    'to_date'              => $to_date,
+                    'all_day'              => $all_day,
+                    'recurring'            => $recurring_event,
+                    'month_of_year'        => $month_of_year,
+                    'week_of_month'        => $week_of_month,
+                    'day_of_week'          => $day_of_week,
+                    'day_of_month'         => $day_of_month,
+                    'by_day_of_month'      => $by_day_of_month,
+                    'last_day_of_month'    => $last_day_of_month,
+                    'specific_dates'       => $serialized_custom_times
+                );
+                if ( $debug ) {
+                    echo '<pre>$recur_data: ' . print_r($recur_data, true) . '</pre>';
+                }
+                $this->wpdb->insert(
+                    GLM_MEMBERS_EVENTS_PLUGIN_DB_PREFIX . 'recurrences',
+                    $recur_data,
+                    array(
+                         '%d',
+                         '%s',
+                         '%s',
+                         '%s',
+                         '%s',
+                         '%s',
+                         '%s',
+                         '%d',
+                         '%d',
+                         '%d',
+                         '%d',
+                         '%d',
+                         '%d',
+                         '%d',
+                         '%d',
+                         '%s'
+                    )
+                );
+                $recurr_id    = $this->wpdb->insert_id;
+                $Recurrences->createRecurrenceTimesEntries( $recurr_id, true, true );
+                // location for the event
+                $has_location = $event_data['location_id'];
+                $location_data = $location_format = array();
+                if ( $has_location ) {
+                    // Get the record for location
+                    $location = $this->wpdb->get_row(
+                        $this->wpdb->prepare(
+                            "SELECT *
+                               FROM " . $this->wpdb->prefix . "em_locations
+                              WHERE location_id = %d",
+                              $has_location
+                        ),
+                        ARRAY_A
+                    );
+                    // echo '<pre>$location: ' . print_r( $location, true ) . '</pre>';
+                    $location_data['event'] = $event_id;
+                    $location_format[] = '%d';
+                    if ($location['location_name']) {
+                        $location_data['name'] = $location['location_name'];
+                        $location_format[] = '%s';
+                    }
+                    if ($location['location_address']) {
+                        $location_data['address'] = $location['location_address'];
+                        $location_format[] = '%s';
+                    }
+                    if ($location['location_town']) {
+                        $location_data['city'] = $this->getCityId( $location['location_town'] );
+                        $location_format[] = '%s';
+                    }
+                    if ($location['location_state']) {
+                        // need to lookup the state abbreviation
+                        $state_abbr = array_search( $location['location_state'], $this->config['states'] );
+                        if ( $state_abbr !== false ) {
+                            $location_data['state'] = $state_abbr;
+                            $location_format[] = '%s';
+                        }
+                    } else {
+                        $location_data['state'] = 'MI';
+                        $location_format[] = '%s';
+                    }
+                    if ($location['location_postalcode']) {
+                        $location_data['zip'] = $location['location_postalcode'];
+                        $location_format[] = '%s';
+                    }
+                    if ($location['location_country']) {
+                        $location_data['country'] = $location['location_country'];
+                        $location_format[] = '%s';
+                    }
+                    if ($location['location_latitude']) {
+                        $location_data['lat'] = $location['location_latitude'];
+                        $location_format[] = '%s';
+                    }
+                    if ($location['location_longitude']) {
+                        $location_data['lon'] = $location['location_longitude'];
+                        $location_format[] = '%s';
+                    }
+                    // echo '<pre>$location_data: ' . print_r( $location_data, true ) . '</pre>';
+                    // echo '<pre>$location_format: ' . print_r( $location_format, true ) . '</pre>';
+                    $this->wpdb->insert(
+                        GLM_MEMBERS_EVENTS_PLUGIN_DB_PREFIX . 'locations',
+                        $location_data,
+                        $location_format
+                    );
+                    $location_id = $this->wpdb->insert_id;
+                    if ( !$location_id ) {
+                        if ( $debug ) {
+                            echo '<pre>$location_data: ' . print_r($location_data, true) . '</pre>';
+                        }
+                        die('no return id for location');
+                    }
+                }
+                if ( $debug ) {
+                    echo '</div>';
+                }
+            }
+            $return_string .= "<p>Adding $event_counter Events</p>";
+        }
+        echo $this->config['states'];
+        $return_string .= "<pre>
+            Start: $start
+        </pre>";
+        $start += $limit;
+        $return_string .= "<p><a href=\""
+            . GLM_MEMBERS_PLUGIN_CURRENT_URL
+            . "?page=glm-members-admin-menu-management&glm_action=events&option=eventsManagerImport&import=true"
+            . "&start=$start\">Next</a></p>";
+        return $return_string;
+    }
 }
 
 ?>
index a8c3bc3..509e52c 100644 (file)
@@ -5,6 +5,7 @@
         <a id="glm-icalfeed" data-show-table="glm-table-icalfeed" class="glm-settings-tab nav-tab{if $option=='icalfeed'} nav-tab-active{/if}">iCal Feeds</a>
         <a id="glm-eventimport" data-show-table="glm-table-eventimport" class="glm-settings-tab nav-tab{if $option=='eventimport'} nav-tab-active{/if}">Import</a>
         <a id="glm-timelyimport" data-show-table="glm-table-timelyimport" class="glm-settings-tab nav-tab{if $option=='timelyimport'} nav-tab-active{/if}">Timely Import</a>
+        <a id="glm-eventmanagerimport" data-show-table="glm-table-eventmanagerimport" class="glm-settings-tab nav-tab{if $option=='eventsManagerImport'} nav-tab-active{/if}">Events Manager Import</a>
     </h2>
 
     <!-- Management Settings -->
   {/if}
 
     </table>
+
     <table id="glm-table-timelyimport" class="glm-admin-table glm-settings-table{if $option!='timelyImport'} glm-hidden{/if}">
   {if $importResult}
         <tr><td><a href="{$thisUrl}?page={$thisPage}&glm_action=events&option=timelyImport">Return to Time.ly Import</a></td></tr>
             </td>
         </tr>
   {/if}
+    </table>
 
+    <table id="glm-table-eventmanagerimport" class="glm-admin-table glm-settings-table{if $option!='eventsManagerImport'} glm-hidden{/if}">
+  {if $importResult}
+        <tr><td><a href="{$thisUrl}?page={$thisPage}&glm_action=events&option=eventsManagerImport">Return to Events Manager Import</a></td></tr>
+        <tr>
+            <td colspan="2">
+                {$importResult}
+            </td>
+        </tr>
+  {else}
+        <tr>
+            <td colspan="2"><h1>Import Event Manager Events</h1></td>
+        </tr>
+        <tr>
+            <td colspan="2">
+                <form action="{$thisUrl}">
+                    <input type="hidden" name="page" value="{$thisPage}" />
+                    <input type="hidden" name="glm_action" value="events" />
+                    <input type="hidden" name="option" value="eventsManagerImport" />
+                    <input type="hidden" name="import" value="true" />
+                    <div style="float:left;width: 200px;">
+                        <input type="submit" value="Import Events" />
+                    </div>
+                </form>
+            </td>
+        </tr>
+  {/if}
+    </table>
 
-    <script type="text/javascript">
+<script type="text/javascript">
 
-        jQuery(document).ready(function($) {
+    jQuery(document).ready(function($) {
 
-            /*
-             * Edit area tabs
-             */
-            $('.glm-settings-tab').click( function() {
+        /*
+         * Edit area tabs
+         */
+        $('.glm-settings-tab').click( function() {
 
-                // Clear tabl highlights and hide all tables
-                $('.glm-settings-tab').removeClass('nav-tab-active');
-                $('.glm-settings-table').addClass('glm-hidden');
+            // Clear tabl highlights and hide all tables
+            $('.glm-settings-tab').removeClass('nav-tab-active');
+            $('.glm-settings-table').addClass('glm-hidden');
 
-                // Highlight selected tab
-                $(this).addClass('nav-tab-active');
+            // Highlight selected tab
+            $(this).addClass('nav-tab-active');
 
-                // Show selected table
-                var table = $(this).attr('data-show-table');
-                $('#' + table).removeClass('glm-hidden');
+            // Show selected table
+            var table = $(this).attr('data-show-table');
+            $('#' + table).removeClass('glm-hidden');
 
-            });
+        });
 
-            // Flash certain elements for a short time after display
-            $(".glm-flash-updated").fadeOut(500).fadeIn(500).fadeOut(500).fadeIn(500).fadeOut(500).fadeIn(500).fadeOut(500).fadeIn(500).fadeOut(500).fadeIn(500).fadeOut(500);
+        // Flash certain elements for a short time after display
+        $(".glm-flash-updated").fadeOut(500).fadeIn(500).fadeOut(500).fadeIn(500).fadeOut(500).fadeIn(500).fadeOut(500).fadeIn(500).fadeOut(500).fadeIn(500).fadeOut(500);
 
-                if('{$eventsSettings.fieldData.calendar_view}'){
-                    $("#calendar-view").val('{$eventsSettings.fieldData.calendar_view}');
-                } else {
-                    $("#calendar-view").val("agenda");
-                }
-        });
-    </script>
+        if('{$eventsSettings.fieldData.calendar_view}'){
+            $("#calendar-view").val('{$eventsSettings.fieldData.calendar_view}');
+        } else {
+            $("#calendar-view").val("agenda");
+        }
+    });
+</script>