Adding Import CSV for Social Media
authorSteve Sutton <steve@gaslightmedia.com>
Fri, 30 Jun 2017 14:15:47 +0000 (10:15 -0400)
committerSteve Sutton <steve@gaslightmedia.com>
Fri, 30 Jun 2017 14:15:47 +0000 (10:15 -0400)
Creating a new tab in the Import CSV for members. To upload and import a
CSV file for members social media url's.

models/admin/import/social.php [new file with mode: 0644]
setup/adminTabs.php
setup/validActions.php
views/admin/import/social.html [new file with mode: 0644]
views/admin/import/socialProcess.html [new file with mode: 0644]
views/admin/import/socialValidate.html [new file with mode: 0644]

diff --git a/models/admin/import/social.php b/models/admin/import/social.php
new file mode 100644 (file)
index 0000000..fcf3c7c
--- /dev/null
@@ -0,0 +1,451 @@
+<?php
+
+/**
+ * Gaslight Media Members Database
+ * Admin Data Import
+ *
+ * PHP version 5.5
+ *
+ * @category glmWordPressPlugin
+ * @package  glmMembersDatabase
+ * @author   Chuck Scott <cscott@gaslightmedia.com>
+ * @license  http://www.gaslightmedia.com Gaslightmedia
+ * @version  0.1
+ */
+require_once GLM_MEMBERS_PLUGIN_PATH . '/models/admin/import/index.php';
+/*
+ * This class performs the work for the default action of the "Import" menu
+ * option.
+ *
+ */
+class GlmMembersAdmin_import_social extends GlmMembersAdmin_import_index
+{
+
+    const CSV_CHARS_PER_LINE = 6000;
+    /**
+     * WordPress Database Object
+     *
+     * @var $wpdb
+     * @access public
+     */
+    public $wpdb;
+    /**
+     * Plugin Configuration Data
+     *
+     * @var $config
+     * @access public
+     */
+    public $config;
+
+    /**
+     * errors
+     *
+     * @var $errors
+     * @access public
+     */
+    public $errors = array();
+
+    /**
+     * numberProcessed
+     *
+     * @var float
+     * @access public
+     */
+    public $numberProcessed = 0;
+
+    /**
+     * totalSocials
+     *
+     * @var float
+     * @access public
+     */
+    public $totalSocials = 0;
+
+    /**
+     * processingComplete
+     *
+     * @var bool
+     * @access public
+     */
+    public $processingComplete = false;
+
+    /**
+     * Constructor
+     *
+     * This contractor sets up this model. At this time that only includes
+     * storing away the WordPress data object.
+     *
+     * @return object Class object
+     *
+     */
+    public function __construct ($wpdb, $config)
+    {
+
+        // Save WordPress Database object
+        $this->wpdb = $wpdb;
+
+        // Save plugin configuration object
+        $this->config = $config;
+
+    }
+
+    /**
+     * Perform Model Action
+     *
+     * This method does the work for this model and returns any resulting data
+     *
+     * @return array Status and data array
+     *
+     * 'status'
+     *
+     * True if successful and false if there was a fatal failure.
+     *
+     * 'menuItemRedirect'
+     *
+     * If not false, provides a menu item the controller should
+     * execute after this one. Normally if this is used, there would also be a
+     * modelRedirect value supplied as well.
+     *
+     * 'modelRedirect'
+     *
+     * If not false, provides an action the controller should execute after
+     * this one.
+     *
+     * 'view'
+     *
+     * A suggested view name that the controller should use instead of the
+     * default view for this model or false to indicate that the default view
+     * should be used.
+     *
+     * 'data'
+     *
+     * Data that the model is returning for use in merging with the view to
+     * produce output.
+     *
+     */
+    public function modelAction ($actionData = false)
+    {
+        // Set the view file
+        $view        = 'social.html';
+        $failure     = false;
+        $option      = 'social';
+        $clearData   = false;
+        $haveMembers = false;
+        $fileExists  = false;
+        $isValid     = false;
+        // Check to see if they have members
+        $haveMembers = $this->wpdb->get_var(
+            "SELECT count(id)
+               FROM " .  GLM_MEMBERS_PLUGIN_DB_PREFIX . "members"
+        );
+        // $fileData - The main files needed for the member import
+        // - field:    input field name
+        // - name:     file name
+        // - exists:   Does file exists. Set to false at first.
+        // - validate: Validation array. Header line must match this.
+        // - type:     Type of file. Used in the processing function.
+        $fileData = array(
+            'Social' => array(
+                'field'    => 'social_file',
+                'name'     => 'socialData.csv',
+                'exists'   => false,
+                'validate' => array( 'member_id', 'facebook', 'twitter', 'pinterest',
+                    'google_plus', 'digg', 'linkedin', 'instagram', 'youtube', 'flickr',
+                    'blog', 'photobucket', 'rss',),
+                'type'     => 'social',
+            ),
+        );
+        // Setting readyToProcess to false (initialize)
+        $readyToProcess = false;
+
+        // Set the $option if found in $_REQUEST array
+        if (isset($_REQUEST['option']) && $_REQUEST['option'] != '') {
+            $option = $_REQUEST['option'];
+        }
+
+        // Set the $option2 if found in $_REQUEST array
+        if (isset($_REQUEST['option2']) && $_REQUEST['option2'] != '') {
+            $option2 = $_REQUEST['option2'];
+        }
+
+        // Set variable for the upload directory
+        $wpUploadDir = wp_get_upload_dir();
+
+        // Set the $uploadPath for import files
+        $uploadPath = $wpUploadDir['basedir'] . '/' . 'glm-member-import';
+
+        // If the folder for the upload import files doesn't exists create one.
+        if ( !is_dir( $uploadPath ) ) {
+            // Get old umask
+            $oldMask = umask(0);
+            // Set folder permission
+            mkdir( $uploadPath, 0770 );
+            // reset old umask
+            umask( $oldMask );
+        }
+
+        switch( $option ) {
+
+        case 'socialValidate';
+            $validFiles = 0;
+            // Set the view file
+            $view       = 'socialValidate.html';
+            $fileCount  = count( $fileData );
+            // Move any files uploaded
+            //echo '<pre>$_FILES: ' . print_r( $_FILES, true ) . '</pre>';
+            if ( isset( $_FILES ) ) {
+                foreach ( $fileData as $fileHeader => $file ) {
+                    if ( !$_FILES[$file['field']]['error'] ) {
+                        move_uploaded_file( $_FILES[$file['field']]['tmp_name'], $uploadPath . '/'. $file['name'] );
+                    }
+                }
+            }
+            // Check that each file exists
+            foreach ( $fileData as $fileHeader => $file ) {
+                if ( is_file( $uploadPath . '/' . $file['name'] ) ) {
+                    $fileData[$fileHeader]['exists']  = true;
+                    $fData = $this->readCSVFileHeaders( $uploadPath . '/' . $file['name'] );
+                    $isValid = ( $file['validate'] == $fData );
+                    if ( $isValid ) {
+                        $validFiles++;
+                    }
+                    $fileData[$fileHeader]['data']    = $fData;
+                    $fileData[$fileHeader]['isValid'] = $isValid;
+                }
+            }
+            $readyToProcess = ( $validFiles == $fileCount );
+            $clearData = ( filter_var( $_REQUEST['clear_data'], FILTER_VALIDATE_BOOLEAN ) );
+            break;
+
+        case 'socialProcess':
+            $clearData = ( filter_var( $_REQUEST['clear_data'], FILTER_VALIDATE_BOOLEAN ) );
+            if ( $clearData ) {
+                // Empty the tables for the member data.
+                // Not including the management options.
+                $this->wpdb->query('DELETE FROM ' . GLM_MEMBERS_SOCIAL_PLUGIN_DB_PREFIX . 'social_urls');
+            }
+            $dataTable  = GLM_MEMBERS_SOCIAL_PLUGIN_DB_PREFIX . 'social_urls';
+            $dataFormat = array( '%s', '%d', '%d', '%d' );
+            // Loop through the $fileData array.
+            // This will setup the wordpress options for each file.
+            foreach ( $fileData as $fileHeader => $file ) {
+                if ( is_file( $uploadPath . '/' . $file['name'] ) ) {
+                    $fData = $this->readCSVFile( $uploadPath . '/' . $file['name'] );
+                    $this->totalSocials = count( $fData );
+                    //echo '<pre>$fData: ' . print_r( $fData, true ) . '</pre>';
+                    foreach ( $fData as $member ) {
+                        $this->numberProcessed++;
+                        // Need to first get the member id from the database
+                        // It will match from the old_member_id field
+                        $memberId = $this->wpdb->get_var(
+                            $this->wpdb->prepare(
+                                "SELECT id
+                                   FROM " . GLM_MEMBERS_PLUGIN_DB_PREFIX . "members
+                                  WHERE old_member_id = %d",
+                                $member['member_id']
+                            )
+                        );
+                        if ( $memberId ) {
+                            if ($member['facebook']) {
+                                // add for facebook
+                                $newId = $this->wpdb->insert(
+                                    $dataTable,
+                                    array(
+                                        'url'      => $member['facebook'],
+                                        'ref_type' => $this->config['ref_type_numb']['Member'],
+                                        'ref_dest' => $memberId,
+                                        'social'   => 1
+                                    ),
+                                    $dataFormat
+                                );
+                            }
+                            if ($member['twitter']) {
+                                // add for twitter
+                                $newId = $this->wpdb->insert(
+                                    $dataTable,
+                                    array(
+                                        'url'      => $member['twitter'],
+                                        'ref_type' => $this->config['ref_type_numb']['Member'],
+                                        'ref_dest' => $memberId,
+                                        'social'   => 2
+                                    ),
+                                    $dataFormat
+                                );
+                            }
+                            if ($member['pinterest']) {
+                                // add for pinterest
+                                $newId = $this->wpdb->insert(
+                                    $dataTable,
+                                    array(
+                                        'url'      => $member['pinterest'],
+                                        'ref_type' => $this->config['ref_type_numb']['Member'],
+                                        'ref_dest' => $memberId,
+                                        'social'   => 3
+                                    ),
+                                    $dataFormat
+                                );
+                            }
+                            if ($member['google_plus']) {
+                                // add for google_plus
+                                $newId = $this->wpdb->insert(
+                                    $dataTable,
+                                    array(
+                                        'url'      => $member['google_plus'],
+                                        'ref_type' => $this->config['ref_type_numb']['Member'],
+                                        'ref_dest' => $memberId,
+                                        'social'   => 4
+                                    ),
+                                    $dataFormat
+                                );
+                            }
+                            if ($member['digg']) {
+                                $newId = $this->wpdb->insert(
+                                    $dataTable,
+                                    array(
+                                        'url'      => $member['digg'],
+                                        'ref_type' => $this->config['ref_type_numb']['Member'],
+                                        'ref_dest' => $memberId,
+                                        'social'   => 5
+                                    )
+                                );
+                            }
+                            if ($member['linkedin']) {
+                                // add for linkedin
+                                $newId = $this->wpdb->insert(
+                                    $dataTable,
+                                    array(
+                                        'url'      => $member['linkedin'],
+                                        'ref_type' => $this->config['ref_type_numb']['Member'],
+                                        'ref_dest' => $memberId,
+                                        'social'   => 6
+                                    ),
+                                    $dataFormat
+                                );
+                            }
+                            if ($member['instagram']) {
+                                // add for instagram
+                                $newId = $this->wpdb->insert(
+                                    $dataTable,
+                                    array(
+                                        'url'      => $member['instagram'],
+                                        'ref_type' => $this->config['ref_type_numb']['Member'],
+                                        'ref_dest' => $memberId,
+                                        'social'   => 7
+                                    ),
+                                    $dataFormat
+                                );
+                            }
+                            if ($member['youtube']) {
+                                // add for youtube
+                                $newId = $this->wpdb->insert(
+                                    $dataTable,
+                                    array(
+                                        'url'      => $member['youtube'],
+                                        'ref_type' => $this->config['ref_type_numb']['Member'],
+                                        'ref_dest' => $memberId,
+                                        'social'   => 8
+                                    ),
+                                    $dataFormat
+                                );
+                            }
+                            if ($member['flickr']) {
+                                // add for flickr
+                                $newId = $this->wpdb->insert(
+                                    $dataTable,
+                                    array(
+                                        'url'      => $member['flickr'],
+                                        'ref_type' => $this->config['ref_type_numb']['Member'],
+                                        'ref_dest' => $memberId,
+                                        'social'   => 9
+                                    ),
+                                    $dataFormat
+                                );
+                            }
+                            if ($member['blog']) {
+                                // add for blog
+                                $newId = $this->wpdb->insert(
+                                    $dataTable,
+                                    array(
+                                        'url'      => $member['blog'],
+                                        'ref_type' => $this->config['ref_type_numb']['Member'],
+                                        'ref_dest' => $memberId,
+                                        'social'   => 10
+                                    ),
+                                    $dataFormat
+                                );
+                            }
+                            if ($member['photobucket']) {
+                                $newId = $this->wpdb->insert(
+                                    $dataTable,
+                                    array(
+                                        'url'      => $member['photobucket'],
+                                        'ref_type' => $this->config['ref_type_numb']['Member'],
+                                        'ref_dest' => $memberId,
+                                        'social'   => 11
+                                    ),
+                                    $dataFormat
+                                );
+                            }
+                        }
+                    }
+
+                }
+            }
+            if ( count( $this->errors ) == 0 ) {
+                $readyToProcess = true;
+            }
+            // Here we need to check to see if we processed all members.
+            // Also the counter has to increment the total processed so far.
+            if ( $this->numberProcessed == $this->totalSocials ) {
+                $this->processingComplete = true;
+            }
+            // Set the view file:<
+            $view = 'socialProcess.html';
+            break;
+
+        case 'social':
+        default:
+            // Set the view file
+            $view = 'social.html';
+            // check upload dir to see if they have any files in yet
+            foreach ( $fileData as $fileHeader => $file ) {
+                if ( is_file( $uploadPath . '/' . $file['name'] ) ) {
+                    $fileData[$fileHeader]['exists'] = true;
+                    $fileData[$fileHeader]['mtime']  = filemtime( $uploadPath . '/' . $file['name'] );
+                }
+            }
+
+            break;
+
+        }
+
+        // Setup the template data array
+        $templateData = array(
+            'fileExists'      => $fileExists,
+            'option'          => $option,
+            'errors'          => $this->errors,
+            'numberProcessed' => $this->numberProcessed,
+            'totalSocials'    => $this->totalSocials,
+            'completed'       => $this->processingComplete,
+            'data'            => false,
+            'fileData'        => $fileData,
+            'clearData'       => $clearData,
+            'csvData'         => '<pre>$fileData: ' . print_r( $fileData, true ) . '</pre>',
+            'readyToProcess'  => $readyToProcess,
+            'haveMembers'     => $haveMembers,
+            'isValid'         => $isValid,
+            'sampleFileUrl'   => GLM_MEMBERS_PLUGIN_BASE_URL . '/sample-files/',
+        );
+
+        // Return status, suggested view, and data to controller
+        return array(
+            'status'           => true,
+            'menuItemRedirect' => false,
+            'modelRedirect'    => false,
+            'view'             => 'admin/import/' . $view,
+            'data'             => $templateData,
+        );
+
+    }
+
+}
index 2caf00d..1fc5531 100644 (file)
@@ -76,3 +76,16 @@ add_filter('glm-member-db-add-tab-for-management',
         return $addOnTabs;
     }
 );
+add_filter('glm-member-db-add-tab-for-import',
+    function($addOnTabs) {
+        $newTabs = array(
+            array(
+                'text'   => 'Social Media',
+                'menu'   => 'import',
+                'action' => 'social',
+            )
+        );
+        $addOnTabs = array_merge($addOnTabs, $newTabs);
+        return $addOnTabs;
+    }
+);
index 0c5e3ee..224f043 100644 (file)
@@ -53,8 +53,11 @@ $glmMembersSocialAddOnValidActions = array(
             'index' => GLM_MEMBERS_SOCIAL_PLUGIN_SLUG,
         ),
         'management' => array(
-            'social' => GLM_MEMBERS_SOCIAL_PLUGIN_SLUG
-        )
+            'social' => GLM_MEMBERS_SOCIAL_PLUGIN_SLUG,
+        ),
+        'import' => array(
+            'social' => GLM_MEMBERS_SOCIAL_PLUGIN_SLUG,
+        ),
     ),
     'frontActions' => array(
         'social' => array(
diff --git a/views/admin/import/social.html b/views/admin/import/social.html
new file mode 100644 (file)
index 0000000..46bb3c7
--- /dev/null
@@ -0,0 +1,52 @@
+{include file='admin/import/header.html'}
+
+    <h2>Social Data Import Step 1: Upload file</h2>
+
+    <form action="{$thisUrl}?page={$thisPage}" method="post" enctype="multipart/form-data">
+        <input type="hidden" name="glm_action" value="social" />
+        <input type="hidden" name="option" value="socialValidate" />
+
+        <table class="glm-admin-table" border="0" cellspacing="5" cellpadding="10">
+            <tr>
+                <th>File Type</th>
+                <th>New File</th>
+                <th>Current File</th>
+                <th>Updated</th>
+            </tr>
+            {$count = 0}
+            {foreach $fileData as $fileHeader => $file}
+            <tr{if $count%2 == 0} class="alternate"{/if}>
+                <td class="glm-import-td">
+                    {$fileHeader}
+                </td>
+                <td class="glm-import-td">
+                    <input type="file" name="{$file.field}">
+                    <a href="{$sampleFileUrl}{$file.name}">Sample {$fileHeader} File</a>
+                </td>
+                <td class="glm-import-td">
+                    {if $file.exists}
+                        {$fileHeader} File
+                    {/if}
+                </td>
+                <td class="glm-import-td">
+                    {if $file.exists}
+                        {$file.mtime|date_format:"%D %I:%M %p"}
+                    {/if}
+                </td>
+            </tr>
+            {$count = $count + 1}
+            {/foreach}
+            <tr>
+                <td>Clear Data</td>
+                <td colspan="4">
+                    <input type="hidden" name="clear_data" value="0">
+                    <input type="checkbox" name="clear_data" value="1" checked>
+                </td>
+            </tr>
+        </table>
+
+        <input type="submit" value="Continue" class="button button-primary submit-import">
+
+    </form>
+
+{include file='admin/footer.html'}
diff --git a/views/admin/import/socialProcess.html b/views/admin/import/socialProcess.html
new file mode 100644 (file)
index 0000000..33fb875
--- /dev/null
@@ -0,0 +1,24 @@
+{include file='admin/import/header.html'}
+
+    <h2>Data Import Step 3: Process Social File</h2>
+    <table class="glm-admin-table">
+        <tr>
+            <th>Total Records</th>
+            <td>{$totalSocials}</td>
+        </tr>
+        <tr>
+            <th>Processed Records</th>
+            <td>{$numberProcessed}</td>
+        </tr>
+
+        {if $errors}
+            {foreach $errors as $error}
+                {$error}
+            {/foreach}
+        {else}
+            Done
+        {/if}
+
+    </table>
+
+{include file='admin/footer.html'}
diff --git a/views/admin/import/socialValidate.html b/views/admin/import/socialValidate.html
new file mode 100644 (file)
index 0000000..468ae53
--- /dev/null
@@ -0,0 +1,54 @@
+{include file='admin/import/header.html'}
+
+    <h2>Secial Import Step 2: Validate social file</h2>
+
+    <table class="glm-admin-table">
+        {foreach $fileData as $fileHeader => $file}
+        <tr>
+            <td>
+                {if $file.exists}
+                    {$fileHeader} File
+                {/if}
+            </td>
+            <td>
+                {if $file.isValid}
+                    Is Valid
+                {else}
+                    Not Valid
+                {/if}
+            </td>
+        </tr>
+        {/foreach}
+
+        {if $clearData}
+        <tr>
+            <td colspan="2">
+                All Member Social Data will be cleared before importing any files.
+            </td>
+        </tr>
+        {else}
+        <tr>
+            <td colspan="2">
+                No Member Social Data will not be cleared before importing any files. No attempts will be made to prevent duplication of members.
+            </td>
+        </tr>
+        {/if}
+
+        {if $readyToProcess}
+        <tr>
+            <td colspan="2">
+                <a href="{$thisUrl}?page={$thisPage}&glm_action=social&option=socialProcess{if $clearData}&clear_data=1{/if}" class="button">Process Files</a>
+            </td>
+        </tr>
+        {else}
+        <tr>
+            <td colspan="2">
+                <p>One or more of your files are not the correct csv format. Please go back and try again.</p>
+                <a href="{$thisUrl}?page={$thisPage}&glm_action=social" class="button">Go Back</a>
+            </td>
+        </tr>
+        {/if}
+
+    </table>
+
+{include file='admin/footer.html'}