/**
 * Handles the upload and import of the user CSV file.
 * @param Object $page The page object to show messages.
 */
function WPCW_users_importUsersFromFile($page)
{
    set_time_limit(0);
    $page->showMessage(__('Import started...', 'wp_courseware'));
    flush();
    if (isset($_FILES['import_course_csv']['name'])) {
        // See what type of file we're tring to upload
        $type = strtolower($_FILES['import_course_csv']['type']);
        $fileTypes = array('text/csv', 'text/plain', 'application/csv', 'text/comma-separated-values', 'application/excel', 'application/vnd.ms-excel', 'application/vnd.msexcel', 'text/anytext', 'application/octet-stream', 'application/txt');
        if (!in_array($type, $fileTypes)) {
            $page->showMessage(__('Unfortunately, you tried to upload a file that isn\'t a CSV file.', 'wp_courseware'), true);
            return false;
        }
        // Filetype is fine, carry on
        $errornum = $_FILES['import_course_csv']['error'] + 0;
        $tempfile = $_FILES['import_course_csv']['tmp_name'];
        // File uploaded successfully?
        if ($errornum == 0) {
            // Try the import, return error/success here
            if (($csvHandle = fopen($tempfile, "r")) !== FALSE) {
                $assocData = array();
                $rowCounter = 0;
                // Extract the user details from the CSV file into an array for importing.
                while (($rowData = fgetcsv($csvHandle, 0, ",")) !== FALSE) {
                    if (0 === $rowCounter) {
                        $headerRecord = $rowData;
                    } else {
                        foreach ($rowData as $key => $value) {
                            $assocData[$rowCounter - 1][$headerRecord[$key]] = $value;
                        }
                        $assocData[$rowCounter - 1]['row_num'] = $rowCounter + 1;
                    }
                    $rowCounter++;
                }
                // Check we have users to process before continuing.
                if (count($assocData) < 1) {
                    $page->showMessage(__('No data was found in the CSV file, so there is nothing to do.', 'wp_courseware'), true);
                    return;
                }
                // Get a list of all courses that we can add a user too.
                $courseList = WPCW_courses_getCourseList(false);
                // Statistics for update.
                $count_newUser = 0;
                $count_skippedButUpdated = 0;
                $count_aborted = 0;
                // By now, $assocData contains a list of user details in an array.
                // So now we try to insert all of these users into the system, and validate them all.
                $skippedList = array();
                foreach ($assocData as $userRowData) {
                    // #### 1 - See if we have a username that we can use. If not, abort.
                    $firstName = trim($userRowData['first_name']);
                    $lastName = trim($userRowData['last_name']);
                    $userNameToCreate = $firstName . $lastName;
                    if (!$userNameToCreate) {
                        $skippedList[] = array('id' => $userRowData, 'row_num' => $userRowData['row_num'], 'aborted' => true, 'reason' => __('Cannot create a user with no name.', 'wp_courseware'));
                        $count_aborted++;
                        continue;
                    }
                    // username check
                    // // #### 2 - Email address of user already exists.
                    if ($userID = email_exists($userRowData['email_address'])) {
                        $skippedList[] = array('id' => $userRowData, 'row_num' => $userRowData['row_num'], 'aborted' => false, 'reason' => __('Email address already exists.', 'wp_courseware'));
                        $count_skippedButUpdated++;
                    } else {
                        // #### 3A - Try and create a unique Username
                        $userlogin = $userNameToCreate;
                        while (username_exists($userlogin)) {
                            $userlogin = $userNameToCreate . rand(10, 999);
                        }
                        // #### 3B - Create a new password
                        $newPassword = wp_generate_password(15);
                        // #### 3C - Try to create the new user
                        $userDetailsToAdd = array('user_login' => $userlogin, 'user_email' => $userRowData['email_address'], 'first_name' => $firstName, 'last_name' => $lastName, 'display_name' => trim($firstName . ' ' . $lastName), 'user_pass' => $newPassword);
                        // #### 3D - Check for error when creating
                        $result = wp_insert_user($userDetailsToAdd);
                        if (is_wp_error($result)) {
                            $skippedList[] = array('id' => $userRowData, 'row_num' => $userRowData['row_num'], 'aborted' => true, 'reason' => $result->get_error_message());
                            $count_aborted++;
                            continue;
                        }
                        // #### 3E - User now exists at this point, copy ID
                        // to user ID variable.
                        $userID = $result;
                        // #### 3F - Notify user of their new password.
                        wp_new_user_notification($userID, $newPassword);
                        flush();
                        $message = sprintf(__('Username: %s'), $user->user_login) . "\r\n\r\n";
                        $message .= __('To set your password, visit the following address:') . "\r\n\r\n";
                        $message .= '<' . network_site_url("wp-login.php?action=rp&key={$key}&login="******">\r\n\r\n";
                        $message .= wp_login_url() . "\r\n\r\n";
                        $message .= sprintf(__('If you have any problems, please contact us at %s.'), get_option('admin_email')) . "\r\n\r\n";
                        $message .= __('Adios!') . "\r\n\r\n";
                        wp_mail($user->user_email, sprintf(__('[%s] Your username and password info'), $blogname), $message);
                        $count_newUser++;
                    }
                    // #### 4 - Break list of courses into an array, and then add that user to those courses
                    $coursesToAdd = explode(',', $userRowData['courses_to_add_to']);
                    if ($coursesToAdd && count($coursesToAdd) > 0) {
                        WPCW_courses_syncUserAccess($userID, $coursesToAdd);
                    }
                }
                // Summary import.
                $page->showMessage(__('Import complete!', 'wp_courseware') . ' ' . sprintf(__('%d users were registered, %d users were updated, and %d user entries could not be processed.', 'wp_courseware'), $count_newUser, $count_skippedButUpdated, $count_aborted));
                // Show any skipped users
                if (!empty($skippedList)) {
                    printf('<div id="wpcw_user_import_skipped">');
                    printf('<b>' . __('The following %d users were not imported:', 'wp_courseware') . '</b>', count($skippedList));
                    printf('<table class="widefat">');
                    printf('<thead>');
                    printf('<tr>');
                    printf('<th>%s</th>', __('Line #', 'wp_courseware'));
                    printf('<th>%s</th>', __('User Email Address', 'wp_courseware'));
                    printf('<th>%s</th>', __('Reason why not imported', 'wp_courseware'));
                    printf('<th>%s</th>', __('Updated Anyway?', 'wp_courseware'));
                    printf('</tr>');
                    printf('</thead>');
                    $odd = false;
                    foreach ($skippedList as $skipItem) {
                        printf('<tr class="%s %s">', $odd ? 'alternate' : '', $skipItem['aborted'] ? 'wpcw_error' : 'wpcw_ok');
                        printf('<td>%s</td>', $skipItem['row_num']);
                        printf('<td>%s</td>', $skipItem['id']['email_address']);
                        printf('<td>%s</td>', $skipItem['reason']);
                        printf('<td>%s</td>', $skipItem['aborted'] ? __('No, Aborted', 'wp_courseware') : __('Yes', 'wp_courseware'));
                        printf('</tr>');
                        $odd = !$odd;
                    }
                    printf('</table>');
                    printf('</div>');
                }
                // All done
                fclose($csvHandle);
            } else {
                $page->showMessage(__('Unfortunately, the temporary CSV file could not be opened for processing.', 'wp_courseware'), true);
                return;
            }
        } else {
            switch ($errornum) {
                case UPLOAD_ERR_FORM_SIZE:
                case UPLOAD_ERR_INI_SIZE:
                    $page->showMessage(__("Unfortunately the file you've uploaded is too large for the system.", 'wp_courseware'), true);
                    break;
                case UPLOAD_ERR_PARTIAL:
                case UPLOAD_ERR_NO_FILE:
                    $page->showMessage(__("For some reason, the file you've uploaded didn't transfer correctly to the server. Please try again.", 'wp_courseware'), true);
                    break;
                case UPLOAD_ERR_NO_TMP_DIR:
                case UPLOAD_ERR_CANT_WRITE:
                    $page->showMessage(__("There appears to be an issue with your server, as the import file could not be stored in the temporary directory.", 'wp_courseware'), true);
                    break;
                case UPLOAD_ERR_EXTENSION:
                    $page->showMessage(__('Unfortunately, you tried to upload a file that isn\'t a CSV file.', 'wp_courseware'), true);
                    break;
            }
        }
    }
    // end of if (isset($_FILES['import_course_csv']['name']))
}
/** 
 * Page where the site owner can choose which courses a user is allowed to access.
 */
function WPCW_showPage_UserCourseAccess_load()
{
    global $wpcwdb, $wpdb;
    $wpdb->show_errors();
    $page = new PageBuilder(false);
    $page->showPageHeader(__('Update User Course Access Permissions', 'wp_courseware'), '75%', WPCW_icon_getPageIconURL());
    // Check passed user ID is valid
    $userID = WPCW_arrays_getValue($_GET, 'user_id');
    $userDetails = get_userdata($userID);
    if (!$userDetails) {
        $page->showMessage(__('Sorry, but that user could not be found.', 'wp_courseware'), true);
        $page->showPageFooter();
        return false;
    }
    printf(__('<p>Here you can change which courses the user <b>%s</b> (Username: <b>%s</b>) can access.</p>', 'wp_courseware'), $userDetails->data->display_name, $userDetails->data->user_login);
    // Check to see if anything has been submitted?
    if (isset($_POST['wpcw_course_user_access'])) {
        $subUserID = WPCW_arrays_getValue($_POST, 'user_id') + 0;
        $userSubDetails = get_userdata($subUserID);
        // Check that user ID is valid, and that it matches user we're editing.
        if (!$userSubDetails || $subUserID != $userID) {
            $page->showMessage(__('Sorry, but that user could not be found. The changes were not saved.', 'wp_courseware'), true);
        } else {
            // Get list of courses that user is allowed to access from the submitted values.
            $courseAccessIDs = array();
            foreach ($_POST as $key => $value) {
                // Check for course ID selection
                if (preg_match('/^wpcw_course_(\\d+)$/', $key, $matches)) {
                    $courseAccessIDs[] = $matches[1];
                }
            }
            // Sync courses that the user is allowed to access
            WPCW_courses_syncUserAccess($subUserID, $courseAccessIDs, 'sync');
            // Final success message
            $message = sprintf(__('The courses for user <em>%s</em> have now been updated.', 'wp_courseware'), $userDetails->data->display_name);
            $page->showMessage($message, false);
        }
    }
    $SQL = "SELECT * \n\t\t\tFROM {$wpcwdb->courses}\n\t\t\tORDER BY course_title ASC \n\t\t\t";
    $courses = $wpdb->get_results($SQL);
    if ($courses) {
        $tbl = new TableBuilder();
        $tbl->attributes = array('id' => 'wpcw_tbl_course_access_summary', 'class' => 'widefat wpcw_tbl');
        $tblCol = new TableColumn(__('Allowed Access', 'wp_courseware'), 'allowed_access');
        $tblCol->cellClass = "allowed_access";
        $tbl->addColumn($tblCol);
        $tblCol = new TableColumn(__('Course Title', 'wp_courseware'), 'course_title');
        $tblCol->cellClass = "course_title";
        $tbl->addColumn($tblCol);
        $tblCol = new TableColumn(__('Description', 'wp_courseware'), 'course_desc');
        $tblCol->cellClass = "course_desc";
        $tbl->addColumn($tblCol);
        // Format row data and show it.
        $odd = false;
        foreach ($courses as $course) {
            $data = array();
            // Basic details
            $data['course_desc'] = $course->course_desc;
            $editURL = admin_url('admin.php?page=WPCW_showPage_ModifyCourse&course_id=' . $course->course_id);
            $data['course_title'] = sprintf('<a href="%s">%s</a>', $editURL, $course->course_title);
            // Checkbox if enabled or not
            $userAccess = WPCW_courses_canUserAccessCourse($course->course_id, $userID);
            $checkedHTML = $userAccess ? 'checked="checked"' : '';
            $data['allowed_access'] = sprintf('<input type="checkbox" name="wpcw_course_%d" %s/>', $course->course_id, $checkedHTML);
            // Odd/Even row colouring.
            $odd = !$odd;
            $tbl->addRow($data, $odd ? 'alternate' : '');
        }
        // Create a form so user can update access.
        ?>
		<form action="<?php 
        str_replace('%7E', '~', $_SERVER['REQUEST_URI']);
        ?>
" method="post">
			<?php 
        // Finally show table
        echo $tbl->toString();
        ?>
			<input type="hidden" name="user_id" value="<?php 
        echo $userID;
        ?>
"> 
			<input type="submit" class="button-primary" name="wpcw_course_user_access" value="<?php 
        _e('Save Changes', 'wp_courseware');
        ?>
" />
		</form>
		<?php 
    } else {
        printf('<p>%s</p>', __('There are currently no courses to show. Why not create one?', 'wp_courseware'));
    }
    $page->showPageFooter();
}
Beispiel #3
0
/**
 * Action called when a new user is created in WordPress. Used to check if we need to 
 * automatically add access for this user to access a training course.
 * 
 * @param Integer $user_id The ID of the user that's just been added.
 */
function WPCW_actions_users_newUserCreated($user_id)
{
    // See if an extension is taking over the checking of access control. If a function is
    // defined to return true, then this section of code is ignored.
    $ignoreOnNewUser = apply_filters('wpcw_extensions_ignore_new_user', false);
    if ($ignoreOnNewUser) {
        return;
    }
    global $wpdb, $wpcwdb;
    $wpdb->show_errors();
    // Get a list of all courses that want users added automatically.
    $courses = $wpdb->get_col("\n    \tSELECT * \n    \tFROM {$wpcwdb->courses}\n    \tWHERE course_opt_user_access = 'default_show'\n    ");
    // None found
    if (!$courses || count($courses) < 1) {
        return;
    }
    // Add access for this user to all courses we're associated with.
    WPCW_courses_syncUserAccess($user_id, $courses, 'sync');
}
Beispiel #4
0
 /**
  * Function called when updating a user for their course access.
  */
 public function handle_courseSync($userID, $levelList)
 {
     global $wpdb, $wpcwdb;
     $wpdb->show_errors();
     $courseIDList = array();
     // Might not have any levels to process
     if ($levelList && count($levelList) > 0) {
         // Assume that there might be multiple levels per user.
         foreach ($levelList as $aLevelID) {
             // Got courses for this level
             $courses = $this->getCourseAccessListForLevel($aLevelID);
             if ($courses) {
                 foreach ($courses as $courseIDToKeep => $levelID) {
                     // Use array index to build a list of valid course IDs
                     // $levelID not needed, just used to assign something interesting. It's
                     // the $courseIDToKeep that's the valuable bit.
                     $courseIDList[$courseIDToKeep] = $levelID;
                 }
             }
         }
         // end foreach
     }
     // end if ($levelList && count($levelList) > 0)
     // By this point, $courseIDList may or may not contain a list of courses.
     WPCW_courses_syncUserAccess($userID, array_keys($courseIDList), 'sync');
 }