· 9 years ago · Jan 06, 2017, 06:06 AM
1<?php
2
3#ini_set('display_errors', 1);
4
5#ini_set('display_startup_errors', 1);
6
7#error_reporting(E_ALL);
8
9
10
11 require_once('twit_funcs_ddm.php');
12
13 require_once('simple_html_dom.php');
14
15 require_once($_SERVER["DOCUMENT_ROOT"]."/facebook-php-sdk-master/src/facebook.php");
16
17//=-======================================================================================
18
19#Broadcast to FB Page + Twitter.
20
21function doBroadcast()
22
23{
24
25 global $post;
26
27 $startTs = strtotime('6 hours ago');
28
29 $args = array(
30
31 'post_per_page' =>-1,
32
33 'cat'=> array('2'),
34
35 'post_type' => 'post',
36
37 'meta_query' => array(
38
39 array(
40
41 'key' => 'has_been_broadcast',
42
43 'value' => 'yes',
44
45 'compare' => 'NOT LIKE',
46
47 ),
48
49 array(
50
51 'key' => 'timestamp',
52
53 'value' => $startTs,
54
55 'compare' => '>',
56
57 ),
58
59 'relation' => 'AND'
60
61
62
63 ),
64
65 'orderby' => 'timestamp',
66
67 'order' => 'ASC',
68
69 );
70
71 $the_query = new WP_Query( $args );
72
73
74
75 #var_dump($the_query);
76
77 $count=0;
78
79 $broadcastPostID = null;
80
81
82
83 $oNewsObj = null;
84
85 for ($z=0; $z< sizeof($the_query->posts) && ($oNewsObj == null); $z++)
86
87 {
88
89 $themeta = get_post_meta($the_query->posts[$z]->ID);
90
91 if (strlen($themeta['image'][0]) > 0)
92
93 {
94
95 $broadcastPostID = $the_query->posts[$z]->ID;
96
97 $oNewsObj->meta = $themeta;
98
99 $oNewsObj->post = $the_query->posts[$z];
100
101 }
102
103 }
104
105
106
107 if ($oNewsObj !=null)
108
109 {
110
111 $desc=null;
112
113 $url = $oNewsObj->post->guid;
114
115 $title = $oNewsObj->post->post_title;
116
117 $content = $oNewsObj->post->post_content;
118
119 $title = html_entity_decode($title, ENT_QUOTES, 'UTF-8');
120
121 $content = html_entity_decode($content, ENT_QUOTES, 'UTF-8');
122
123 if ($content !=null)
124
125 $desc = $content;
126
127 $img = '';
128
129 if (($oNewsObj->meta['image'][0] !=null ) && ($oNewsObj->meta['image'][0] !='' ) )
130
131 $img = $oNewsObj->meta['image'][0];
132
133 else
134
135 $img = 'http://worldoilgasnews.com/wp-content/uploads/2016/05/worldoilgasnews.png';
136
137 $text = $title.' '.$url.' '.'#oil #energy #gas #oilandgas #news';
138
139 $result = tweetIt($text);
140
141 #postToFBPage($message=$title, $name=$title, $description=$content, $picture=$img, $link=$url, $caption=null);
142
143 update_post_meta($broadcastPostID, 'has_been_broadcast', 'yes');
144
145 }
146
147}
148
149//=-======================================================================================
150
151function postToFBPage($message=null, $name=null, $description=null, $picture=null, $link=null, $caption=null)
152
153{
154
155 return;
156
157
158
159 #POST TO A GROUP OR PAGE
160
161 $facebook = new Facebook(array(
162
163 'appId' => '',
164
165 'secret' => '',
166
167 'cookie' => true,
168
169 ));
170
171
172
173 $fb_group_id= ''; #the group or page
174
175
176
177 $token = "";
178
179 $post = array('access_token' => $token, 'message' =>$message);
180
181
182
183
184
185 if ($name !=null)
186
187 $post['name'] = $name;
188
189 if ($description !=null)
190
191 $post['description'] = $description;
192
193 if ($picture !=null)
194
195 $post['picture'] = $picture;
196
197 if ($link !=null)
198
199 $post['link'] = $link;
200
201 if ($caption !=null)
202
203 $post['caption'] = $caption;
204
205
206
207
208
209 try{
210
211 $res = $facebook->api('/'.$fb_group_id.'/feed','POST',$post);
212
213 } catch (Exception $e){
214
215 echo $e->getMessage();
216
217 }
218
219}
220
221
222
223//=========================================================================================================================
224
225
226
227function getOG($url)
228
229{
230
231
232
233 $curl = curl_init();
234
235 curl_setopt($curl, CURLOPT_URL, $url);
236
237 curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
238
239 curl_setopt($curl, CURLOPT_HEADER, false);
240
241 curl_setopt($curl, CURLOPT_ENCODING ,"");
242
243 $site_html = curl_exec($curl);
244
245 curl_close($curl);
246
247
248
249 #$site_html= @file_get_contents($url);
250
251 if ($site_html == FALSE)
252
253 return null;
254
255
256
257 $ogtags =null; #Extracted Open Graph Tags assoc
258
259 $metatags = array(); #extracted meta data assoc
260
261 $propertytags = array(); #extracted meta data assoc
262
263
264
265 $meta = null;
266
267 preg_match_all('~<\s*meta\s+name="([^"]+)"\s+content="([^"]*)~i', $site_html,$meta);
268
269 for($i=0;$i<count($meta[1]);$i++)
270
271 $metatags[$meta[1][$i]]=$meta[2][$i];
272
273
274
275 $property=null;
276
277 preg_match_all('~<\s*meta\s+property="([^"]+)"\s+content="([^"]*)~i', $site_html,$property);
278
279 for($i=0;$i<count($property[1]);$i++)
280
281 $propertytags[$property[1][$i]]=$property[2][$i];
282
283
284
285 $matches=null;
286
287 preg_match_all('~<\s*meta\s+property="(og:[^"]+)"\s+content="([^"]*)~i', $site_html,$matches);
288
289
290
291 for($i=0;$i<count($matches[1]);$i++)
292
293 $ogtags[$matches[1][$i]]=$matches[2][$i];
294
295
296
297 $aTheData = array('Open Graph Tags'=>$ogtags,'Meta name Tags'=> $metatags, 'Meta Property Tags'=>$propertytags);
298
299
300
301 return ($aTheData);
302
303
304
305}
306
307//=========================================================================================================================
308
309function doNewsNowAutomation()
310
311{
312
313
314 $today = date('d-m-Y');
315
316 $url = 'http://www.newsnow.co.uk/h/Industry+Sectors/Energy/Oil+&+Gas';
317 $aStories=null;
318 $skipUpdate= false;
319
320 $aNewsItems = getNewsNowStoriesFromURL($url);
321
322 for ($i=0; $i<sizeof($aNewsItems); $i++) #Loop thru news items data
323 #for ($i=0; $i<1; $i++) #Loop thru news items data
324 {
325
326 $bPostAlreadyExists = false;
327 global $query;;
328 $my_query = new WP_Query();
329 $my_query->query(array( 'meta_key' => 'newsnow_href', 'meta_value' => $aNewsItems[$i]['newsnow_href']));
330 if ( $my_query->have_posts() ){
331 $bPostAlreadyExists =true;
332 }
333 wp_reset_query();
334
335 if ($bPostAlreadyExists == false)
336 {
337
338 #no - extract the final destination URL + open graph tags - then create post
339/**
340 $str= file_get_contents_curl($aNewsItems[$i]['newsnow_href']);
341 $arr = explode("clickthrough_url = '", $str);
342 $arr2 = explode("'", $arr[1]);
343 $theURL = $arr2[0];
344
345
346 $aNewsItems[$i]['newsnow_href'] = $aNewsItems[$i]['newsnow_href'];
347 $aNewsItems[$i]['href'] = $theURL;
348 $ogData = getOG($theURL);
349 #echo '<pre>'; print_r($ogData); echo '</pre>';
350 $title = $aNewsItems[$i]['title'];
351 $description = '';
352 $img = '';
353 $twitter_site ='';
354
355 if (@$ogData['Meta name Tags']['twitter:site']!=null)
356 $twitter_site= @$ogData['Meta name Tags']['twitter:site'];
357
358 if (@$ogData['Open Graph Tags']['og:image']!=null)
359 $img= @$ogData['Open Graph Tags']['og:image'];
360
361 if (@$ogData['Open Graph Tags']['og:description']!=null)
362 $description = @$ogData['Open Graph Tags']['og:description'];
363 else
364 if (@$ogData['Meta name Tags']['description']!=null)
365 $description = @$ogData['Meta name Tags']['description'];
366
367 #echo $title.' - '.$description.'-<img src="'.$img.'" />';
368
369 if ($img != '')
370 $aNewsItems[$i]['image']= $img;
371
372 $aNewsItems[$i]['description']= $description;
373
374 if ($twitter_site != '')
375 $aNewsItems[$i]['twitter_id']= $twitter_site;
376
377
378 //Insert post into WP database in the news category
379 $postdate = date('Y-m-d H:i:s', $aNewsItems[$i]['timestamp']);
380 $my_post = array(
381 'post_title' => $aNewsItems[$i]['title'],
382 'post_date' => $postdate,
383 'post_content' => $aNewsItems[$i]['description'],
384 'post_status' => 'publish',
385 'post_type' => 'post',
386 'post_category' => array(3)
387
388 );
389 $post_id = wp_insert_post( $my_post );
390
391 if ($post_id)
392 {
393 #echo "POST CREATED";
394 update_post_meta( $post_id, 'image', $img);
395 update_post_meta( $post_id, 'twitterID', $twitter_site);
396 update_post_meta( $post_id, 'href', $aNewsItems[$i]['href']);
397 update_post_meta( $post_id, 'newsnow_href', $aNewsItems[$i]['newsnow_href']);
398 update_post_meta( $post_id, 'timestamp', $aNewsItems[$i]['timestamp']);
399 update_post_meta( $post_id, 'countrycode', $aNewsItems[$i]['countrycode']);
400 update_post_meta( $post_id, 'src', $aNewsItems[$i]['src']);
401 update_post_meta( $post_id, 'has_been_broadcast', 'no');
402 }
403 }
404 else
405 {
406 #echo "Post: ".$aNewsItems[$i]['title']." Already exists in database - skipping<br/>";
407 }
408 }
409
410
411}
412
413
414
415//=========================================================================================================================
416
417function getNewsNowStoriesFromURL($url, $findURLs = false)
418
419 {
420
421
422 $bannedKWs = array('food', 'golf', 'tennis', 'football', 'rugby', 'moto gp','le mans'); #MUST BE LOWERCASE
423 $bannedSources = array('Investment Week', 'ATPWorldTour.com', 'Sport 360','The Daily Dot', 'Daily Times', 'thewashingtonpost.com'); #Must be exact match
424
425 #echo "Retrieving content from: ".$url."<br/>";
426
427 $htmlstr= file_get_contents_curl($url);
428 $html = @str_get_html($htmlstr);
429
430 if ($html == null)
431 {
432 echo "Error Reading Page";
433 return null;
434 }
435
436 $aRows = array();
437 $count=0;
438 foreach($html->find('div.hl') as $row)
439 {
440 $skip_row = false;
441 $count++;
442 #if ($count > 1)
443 # continue;
444 $aCurrentRow = array();
445 foreach($row->find('a') as $element)
446 {
447 $ahref= explode("-",$element->href);
448 if (strpos( $ahref[0], '/A/') === FALSE)
449 $skip_row=true;
450
451 # $aCurrentRow['href'] = 'http://www.newsnow.co.uk'.$ahref[0];
452 $aCurrentRow['newsnow_href'] = 'http:'.$ahref[0];
453 if ($findURLs)
454 {
455 if (!$skip_row)
456 {
457 $str= file_get_contents_curl($aCurrentRow['newsnow_href']);
458 $arr = explode("clickthrough_url = '", $str);
459 if (isset($arr[1]))
460 {
461 $arr2 = explode("'", $arr[1]);
462 $aCurrentRow['href'] = $arr2[0];
463 }
464 else
465 $skip_row=true;
466
467 }
468 $aCurrentRow['title'] = $element->innertext;
469 }
470
471 foreach($row->find('span.src') as $element)
472 $aCurrentRow['src'] = str_replace('<span class="darw"></span>', '', $element->innertext);
473
474 foreach($row->find('span.f') as $element)
475 {
476 $dataSrc='c';
477 $aCurrentRow['countrycode'] = $element->$dataSrc;
478 }
479
480 foreach($row->find('span.time') as $element)
481 {
482 $aCurrentRow['timestamp_text'] = $element->innertext;
483 $dataSrc='data-time';
484 $aCurrentRow['timestamp'] = $element->$dataSrc;
485 }
486
487
488
489 if (strposarr(strtolower($aCurrentRow['title']), $bannedKWs) !== FALSE)
490 $skip_row = true;
491
492 if (strposarr($aCurrentRow['src'], $bannedSources) !== FALSE)
493 $skip_row = true;
494
495 #var_dump($aCurrentRow);
496 if ($skip_row == false)
497 $aRows[]= $aCurrentRow;
498 }
499
500 sort_array_of_array($aRows, 'timestamp');
501 $aRows = array_reverse($aRows);
502 return ($aRows);
503
504
505
506 }
507
508
509
510//=========================================================================================================================
511
512function get_string_between($string, $start, $end){
513
514 $string = " ".$string;
515
516 $ini = strpos($string,$start);
517
518 if ($ini == 0) return "";
519
520 $ini += strlen($start);
521
522 $len = strpos($string,$end,$ini) - $ini;
523
524 return substr($string,$ini,$len);
525
526}
527
528//=========================================================================================================================
529
530function file_get_contents_curl($url)
531
532{
533
534 $ch = curl_init();
535
536 $timeout = 5;
537
538 curl_setopt($ch, CURLOPT_URL, $url);
539
540 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
541
542 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
543
544 $data = curl_exec($ch);
545
546 curl_close($ch);
547
548 return $data;
549
550}
551
552
553
554//=========================================================================================================================
555
556function sort_array_of_array(&$array, $subfield)
557
558{
559
560 $sortarray = array();
561
562 foreach ($array as $key => $row)
563
564 {
565
566 $sortarray[$key] = $row[$subfield];
567
568 }
569
570
571
572 array_multisort($sortarray, SORT_ASC, $array);
573
574}
575
576
577
578//=========================================================================================================================
579
580 function make_bitly_url($url,$login="",$appkey="",$format = 'json',$version = '2.0.1')
581
582{
583
584 //create the URL
585
586 $bitly = 'http://api.bit.ly/shorten?version='.$version.'&longUrl='.urlencode($url).'&login='.$login.'&apiKey='.$appkey.'&format='.$format;
587
588
589
590 //get the url
591
592 //could also use cURL here
593
594 $response = file_get_contents($bitly);
595
596
597
598 //parse depending on desired format
599
600 if(strtolower($format) == 'json')
601
602 {
603
604 $json = @json_decode($response,true);
605
606 return $json['results'][$url]['shortUrl'];
607
608 }
609
610 else //xml
611
612 {
613
614 $xml = simplexml_load_string($response);
615
616 return 'http://bit.ly/'.$xml->results->nodeKeyVal->hash;
617
618 }
619
620}
621
622
623
624//=========================================================================================================================
625
626function wp_exist_post_by_title($title_str)
627
628{
629
630 global $wpdb;
631
632 return $wpdb->get_row("SELECT * FROM wp_posts WHERE post_title = '" . $title_str . "'", 'ARRAY_A');
633
634}
635
636//=========================================================================================================================
637
638
639
640
641
642function my_cron_schedules($schedules){
643
644
645
646 if(!isset($schedules["30min"])){
647
648 $schedules["30min"] = array(
649
650 'interval' => 30*60,
651
652 'display' => __('Once every 30 minutes'));
653
654 }
655
656
657
658 return $schedules;
659
660}
661
662add_filter('cron_schedules','my_cron_schedules');
663
664
665
666
667
668add_action('my_hourly_event', 'do_this_hourly');
669
670
671
672function my_activation() {
673
674 if ( !wp_next_scheduled( 'my_hourly_event' ) ) {
675
676 #wp_schedule_event( current_time( 'timestamp' ), 'hourly', 'my_hourly_event');
677
678 wp_schedule_event( current_time( 'timestamp' ), '30min', 'my_hourly_event');
679
680 }
681
682}
683
684add_action('wp_loaded', 'my_activation');
685
686
687
688function do_this_hourly() {
689
690 doNewsNowAutomation();
691
692 doBroadcast();
693
694}
695
696
697
698//=========================================================================================================================
699
700//Take care of pulling in sportive calendar and race calendar data, once daily
701
702
703
704add_action('my_daily_event', 'do_this_daily');
705
706
707
708function my_daily_activation() {
709
710 if ( !wp_next_scheduled( 'my_daily_event' ) ) {
711
712 wp_schedule_event( current_time( 'timestamp' ), 'daily', 'my_daily_event');
713
714 }
715
716}
717
718add_action('wp_loaded', 'my_daily_activation');
719
720
721
722function do_this_daily() {
723
724 getRaceCalendarData();
725
726 getSportiveCalendarData();
727
728}
729
730
731
732//=========================================================================================================================
733
734
735
736function strposarr($haystack, $needles=array(), $offset=0)
737
738{
739
740 $chr = array();
741
742 foreach($needles as $key => $needle)
743
744 {
745
746 $res = strpos($haystack, $needle);
747
748 if ($res !== false)
749
750 $chr[] = $needle;
751
752 }
753
754 if(count($chr) > 0)
755
756 {
757
758 return json_encode($chr);
759
760 }
761
762 else
763
764 {
765
766 return false;
767
768 }
769
770}
771
772
773
774//=========================================================================================================================
775
776
777
778 #http://wordpress.stackexchange.com/questions/4557/make-all-subcategories-use-the-template-of-its-category-parent
779
780
781
782// make category use parent category template
783
784function load_cat_parent_template($template) {
785
786
787
788 $cat_ID = absint( get_query_var('cat') );
789
790 $category = get_category( $cat_ID );
791
792
793
794 $templates = array();
795
796
797
798 if ( !is_wp_error($category) )
799
800 $templates[] = "category-{$category->slug}.php";
801
802
803
804 $templates[] = "category-$cat_ID.php";
805
806
807
808 // trace back the parent hierarchy and locate a template
809
810 if ( !is_wp_error($category) ) {
811
812 $category = $category->parent ? get_category($category->parent) : '';
813
814
815
816 if( !empty($category) ) {
817
818 if ( !is_wp_error($category) )
819
820 $templates[] = "category-{$category->slug}.php";
821
822
823
824 $templates[] = "category-{$category->term_id}.php";
825
826 }
827
828 }
829
830
831
832 $templates[] = "category.php";
833
834 $template = locate_template($templates);
835
836
837
838 return $template;
839
840}
841
842add_action('category_template', 'load_cat_parent_template');
843
844
845
846
847
848
849
850
851
852/**
853
854 * Truncates the given string at the specified length.
855
856 *
857
858 * @param string $str The input string.
859
860 * @param int $width The number of chars at which the string will be truncated.
861
862 * @return string
863
864 */
865
866function truncate($str, $width) {
867
868 return strtok(wordwrap($str, $width, "...\n"), "\n");
869
870}
871
872
873
874function doCalendar()
875
876{
877
878 #getRaceCalendarData();
879 $aResults = json_decode(get_option('races'), $assoc=true);
880
881
882
883/**
884
885 echo '<pre>';
886
887 print_r($aResults);
888
889 echo '</pre>';
890
891**/
892
893?>
894
895
896
897 <table data-role="table" data-mode="columntoggle" class="ui-responsive" id="myTable">
898
899 <thead>
900
901 <tr>
902
903 <th data-priority="1" style="min-width:100px;">Date</th>
904
905 <th data-priority="2">Event</th>
906
907 <th data-priority="3">Location</th>
908
909 <!-- <th data-priority="4">UCI Code</th> -->
910
911 </tr>
912
913 </thead>
914
915 <tbody>
916
917 <?php
918
919 foreach ($aResults as $event)
920
921 {
922
923 #echo '<tr> <td>'.$event['date'].'</td> <td>'.$event['name'].'</td> <td>'.$event['location'].'</td> <td>'.$event['uci_code'].'</td> </tr>';
924
925 echo '<tr> <td>'.$event['date'].'</td> <td>'.$event['name'].'</td> <td>'.$event['location'].'</td> <td> </tr>';
926
927 }
928
929 ?>
930
931 </rbody>
932
933 </table>
934
935
936
937<?php
938
939}
940
941
942
943#Cron This 24h
944
945function getRaceCalendarData()
946
947{
948
949}
950
951
952
953#Cron This 24h
954
955function getSportiveCalendarData()
956
957{
958
959
960
961}
962
963
964
965function doSportiveCalendar()
966
967{
968
969
970
971
972}
973
974
975
976//=====================
977
978
979
980function getDataJson()
981
982{
983
984
985
986 global $post;
987
988
989
990 $aOutput = array();
991
992 $args = array(
993
994 'posts_per_page' => -1,
995
996 'cat' => array(2),
997
998 'post_status' =>'publish',
999
1000 'date_query' => array(
1001
1002 array(
1003
1004 'after' => '-1 days'
1005
1006 )
1007
1008 ),
1009
1010 'orderby' => 'date',
1011
1012 'order' => 'desc'
1013
1014
1015
1016 );
1017
1018
1019
1020 query_posts($args);
1021
1022 while (have_posts()) : the_post();
1023
1024 #print_r($post);
1025
1026 $meta= get_post_meta($post->ID);
1027
1028
1029
1030 $result = array();
1031
1032 $result['title']= $post->post_title;
1033
1034 $result['link']= $post->guid;
1035
1036 $result['source']= $meta['src'][0];
1037
1038 #$result['description']= $post->post_title;
1039
1040 $result['countrycode']= $meta['countrycode'][0];
1041
1042 $result['timestamp']= $meta['timestamp'][0];
1043
1044 #print_r($result);
1045
1046 $aOutput[]=$result;
1047
1048 endwhile;
1049
1050 wp_reset_query();
1051
1052 #print_r($aOutput);
1053
1054 return json_encode($aOutput);
1055
1056}
1057
1058//=====================
1059
1060?>