Advertisement
Guest User

Untitled

a guest
Jan 25th, 2018
166
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 4.89 KB | None | 0 0
  1. function start_next_ical_update() {
  2.   //fetch ical scheduled imports and get the ones that have not been manually imported for at least a day
  3.   $args = array(
  4.     'post_type' => 'tribe-ea-record',
  5.     'post_status' => 'tribe-ea-schedule',
  6.     'ping_status' => 'schedule',
  7.     'post_mime_type' => 'ea/ical',
  8.     'posts_per_page' => -1,
  9.     'meta_query' => array(
  10.         'relation' => 'OR',
  11.         array(
  12.             'key' => '_tribe_ics_hack',
  13.             'value' => time()-86400,
  14.             'compare' => ' '_tribe_ics_hack',
  15.           'compare' => 'NOT EXISTS'
  16.        )  ),
  17.    'orderby' => '_tribe_ics_hack',
  18.    'order' => 'ASC');
  19.  $query = new WP_Query( $args );
  20.  
  21.  //start the update for the one that has not been updated the longest
  22.  if($query->have_posts()) {
  23.    $item = $query->posts[0];
  24.    $meta = get_post_meta($item->ID);
  25.    $url = $meta['_tribe_aggregator_source'][0];
  26.    error_log('started '.$url);
  27.    update_ical_events($url);
  28.    update_post_meta( $item->ID, '_tribe_ics_hack', time());
  29.  }  
  30. }
  31.  
  32. //use the tribe cron every 15 minutes to start the update function
  33. add_action('tribe_aggregator_cron', 'start_next_ical_update', 10, 0);
  34.  
  35. //during debugging use the json api to start the update manually
  36. //use curl http://your-domain.com/wp-json/pd/v1/updateevents
  37. /*add_action( 'rest_api_init', function () {
  38.  register_rest_route( 'pd/v1', '/updateevents', array(
  39.    'methods' => 'GET',
  40.    'callback' => 'start_next_ical_update',
  41.  ) );
  42. } );*/
  43.  
  44. function update_ical_events($url) {
  45.  //get ics contents from url
  46.  ini_set('user_agent','Mozilla/4.0 (compatible; MSIE 6.0)');
  47.  
  48.  try {
  49.    $ics = get_file_contents($url);
  50.    
  51.    if ($ics === false) {
  52.      return new WP_Error( 'import_error', 'File was empty.');
  53.    }
  54.  } catch (Exception $e) {
  55.    return new WP_Error( 'import_error', 'URL could not be reached.');
  56.  }
  57.  
  58.  //get wp upload dir and a filename for our ics
  59.  $upload_dir = wp_upload_dir();
  60.  /*preg_match('/[A-Za-z0-9]+\.?[A-Za-z0-9]*$/', $url, $name); */
  61.  $basename = wp_unique_filename($upload_dir['path'], 'manual.ics');
  62.  
  63.  $file_abs = $upload_dir['path'].'/'.$basename;
  64.  $file_url = $upload_dir['url'] . '/' . $basename;
  65.  
  66.  //save the ics content to a local file
  67.  $f = fopen($file_abs, "w") or die("Unable to open file!");
  68.  if ( !$f ) {
  69.    return new WP_Error( 'import_error', 'File could not be written.');
  70.  }  
  71.  fwrite($f, $ics);
  72.  fclose($f);
  73.  
  74.  //set permissions
  75.  $stat = stat( dirname( $file_abs ));
  76.  $perms = $stat['mode'] & 0000666;
  77.  chmod( $file_abs, $perms );
  78.  
  79.  //and add attachement metadata to the file to get it into wp media
  80.  $type = wp_check_filetype( basename( $basename ), null );
  81.  $attachment = array(
  82.    'guid'           => $file_url,
  83.    'post_mime_type' => $type['type'],
  84.    'post_title'     => preg_replace( '/\.[^.]+$/', '', $basename ),
  85.    'post_content'   => '',
  86.    'post_status'    => 'inherit',
  87.    'post_author'    => 1
  88.  );
  89.  $id = wp_insert_attachment( $attachment, $file_abs);
  90.  require_once( ABSPATH . 'wp-admin/includes/image.php' );
  91.  
  92.  // Generate the metadata for the attachment, and update the database record.
  93.  $attach_data = wp_generate_attachment_metadata( $id, $file_url );
  94.  wp_update_attachment_metadata( $id, $attach_data );
  95.  
  96.  //prepare settings for event aggregator
  97.  $meta = Array(
  98.    'origin' => 'ics',
  99.    'file' => $id,
  100.    'type' => 'manual',
  101.    'limit_type' => 'no_limit'
  102.  );
  103.  $args = array_merge($meta, Array(
  104.    'allow_multiple_organizers' => true,
  105.    'preview' => true
  106.  ));
  107.  
  108.  //create new events aggregator import and get the data from the aggregator service
  109.  $import = new Tribe__Events__Aggregator__API__Import();
  110.  $response = $import->create($args);
  111.  $response_data = $response->data;
  112.  $meta['import_id'] = $response_data->import_id;
  113.  
  114.  //create and save new aggregator record
  115.  $record = Tribe__Events__Aggregator__Records::instance()->get_by_origin( $meta['origin'] );
  116.  $post = $record->create($meta['type'], $args, $meta);
  117.  
  118.  $record->set_status_as_pending();
  119.  $record->update_meta( 'category', null);
  120.  $record->update_meta( 'post_status', 'publish' );
  121.     $record->finalize();
  122.  
  123.  //seems to be necessary for larger ics files, gets down failure rate
  124.  sleep(5);
  125.  
  126.  //process the events and add them
  127.  $result = $record->process_posts();
  128.  $result->record = $record;
  129.  
  130.  return new WP_REST_Response( $result );
  131. }
  132.  
  133. function get_file_contents($url, $post = null) {
  134.    $ch = curl_init();
  135.    curl_setopt($ch, CURLOPT_URL, $url);
  136.    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  137.    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
  138.    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  139.    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
  140.    if(!empty($post)) {
  141.        curl_setopt($ch, CURLOPT_POST, true);
  142.        curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
  143.    }
  144.    $result = curl_exec($ch);
  145.    curl_close($ch);
  146.    return $result;
  147. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement