Project

General

Profile

Feature #9801 » cac-import-courses.php

Boone Gorges, 2018-11-02 01:58 PM

 
1
<?php
2

    
3
global $wpdb, $bp;
4

    
5
$raws = array_map( 'str_getcsv', file( $args[0] ) );
6
//var_dump( $raws );
7

    
8
foreach ( $raws as $index => $raw ) {
9
	// Skip first row.
10
	if ( 0 === $index ) {
11
		continue;
12
	}
13

    
14
	$course_name = $raw[0];
15
	$site_url    = $raw[1];
16
	$group_url   = $raw[2];
17
	$year        = $raw[5];
18
	$semester    = $raw[6];
19

    
20
	$instructors_raw = trim( $raw[3] );
21
	$instructors     = $instructors_raw ? array_map( 'trim', explode( ',', $instructors_raw ) ) : [];
22

    
23
	$campuses_raw = trim( $raw[4] );
24
	$campuses     = $campuses_raw ? array_map( 'trim', explode( ',', $campuses_raw ) ) : [];
25

    
26
	$group_id = null;
27
	if ( $group_url ) {
28
		$group_url  = rtrim( $group_url, '/' );
29
		$group_slug = substr( $group_url, strrpos( $group_url, '/' ) + 1 );
30

    
31
		$group_id = groups_get_id( $group_slug );
32
	}
33

    
34
	$site_id = null;
35
	if ( $site_url ) {
36
		$site_url_host = parse_url( $site_url, PHP_URL_HOST );
37
		$site_url_slug = array_shift( explode( '.', $site_url_host ) );
38

    
39
		$site_id = get_id_from_blogname( $site_url_slug );
40
	}
41

    
42
	// instructor fallback
43
	if ( empty( $instructors ) ) {
44
		if ( $group_id ) {
45
			$group = groups_get_group( $group_id );
46
			foreach ( $group->admins as $admin ) {
47
				$instructors[] = $admin->user_login;
48
			}
49
		} elseif ( $site_id ) {
50
			$site_admin = get_blog_option( $site_id, 'admin_email' );
51
			$admin_user = get_user_by( 'email', $site_admin );
52
			$instructors[] = $admin_user->user_login;
53
		}
54
	}
55

    
56
	$post_arr = [
57
		'post_type'   => 'cac_course',
58
		'post_status' => 'publish',
59
		'post_title'  => $course_name,
60
	];
61

    
62
	$post_id = wp_insert_post( $post_arr );
63

    
64
	$instructor_ids = array_map(
65
		function( $instructor_login ) {
66
			$user = get_user_by( 'login', $instructor_login );
67
			return $user->ID;
68
		},
69
		$instructors
70
	);
71
	add_post_meta( $post_id, 'instructor-ids', json_encode( $instructor_ids ) );
72

    
73
	add_post_meta( $post_id, 'campus-slugs', json_encode( $campuses ) );
74

    
75
	if ( $group_id ) {
76
		add_post_meta( $post_id, 'course-group-ids', json_encode( [ $group_id ] ) );
77
	}
78

    
79
	if ( $site_id ) {
80
		add_post_meta( $post_id, 'course-site-ids', json_encode( [ $site_id ] ) );
81
	}
82
}
(16-16/17)