-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathApp.php
1481 lines (1238 loc) · 53.3 KB
/
App.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
class App {
// Mixpanel
private $mp;
private $mailer;
private $redis;
private $eTags = array();
private $mixpanel_token = '';
private $api_root = 'https://api.github.com';
public $access_token;
function __construct($token = null){
$this->mp = null;
$this->mailer = null;
$this->redis = new Redis();
$this->redis->pconnect('127.0.0.1');
$this->redis->auth('YbHfwSaldpEILOKmsZaGp8PAtVYMVYHsie');//*/
$this->eTags = $_SESSION['eTags'];
if ($token)
$this->access_token = $token;
$this->template_replace = array(
'|#name|',
'|#email|',
'|#gravatar|',
);
$this->template_pattern = array(
$_SESSION['gh']['name'],
$_SESSION['gh']['email'],
$this->gravatar($_SESSION['gh']['email'], 120)
);
// Db
global $mysqli;
$this->db = &$mysqli;
}
function __destruct() {
// Save to session
$_SESSION['eTags'] = $this->eTags;
}
private function initMxPanel() {
if ($this->mp)
return;
require_once dirname(__FILE__).'/lib/mixpanel/Mixpanel.php';
$this->mp = Mixpanel::getInstance($this->mixpanel_token, array(
'use_ssl' => false
));
}
// Auth
function checkLogged() {
if (!$_SESSION['gh']['username']) {
header('location:login');
exit;
}
}
function resetAccessToken(){
$this->access_token = null;
}
function getAccessToken($code = null) {
if ($this->access_token)
return $this->access_token;
$data = array(
'client_id' => CLIENT_ID,
'client_secret' => CLIENT_SECRET,
'code' => $code
);
$response = $this->http(ACCESS_TOKEN_URL, $data, 'POST');
$json = json_decode($response[1]);
if (!$json->access_token)
return false;
$this->access_token = $json->access_token;
return $json->access_token;
}
// Posts
function getPosts($page = 1, $start = null) {
$page = (int) $page;
$count = $page * 5;
if (!isset($start))
$start = $count - 5;
$start = (int) $start;
$posts = array();
//return $posts;
$endpoint = $this->api_root.'/repos/'.$_SESSION['gh']['username'].'/'.$_SESSION['gh']['default_repo'].'/contents/_posts';
// tmp
$response[1] = $this->redis->get($endpoint);
// Force refresh
if ($start == 0 || !$response[1]) {
// Get send laters here
$q = "select id, title, path, send_at_raw, date from schedule where user='{$_SESSION['gh']['id']}' order by date desc";
//echo $q;
$r = $this->db->query($q);
while($row = $r->fetch_array(MYSQLI_ASSOC)) {
$row['send_at'] = $row['send_at_raw'];
$row['later'] = true;
$row['sha'] = '';
$row['url'] = '';
$row['draft'] = false;
$row['date'] = date('M d, Y', strtotime($row['date']));
//$data = json_decode(base64_decode($row['data']), true);
unset($row['send_at_raw']);
$posts[] = $row;
}
// tmp
//return $posts;
// delete etag
unset($this->eTags[$endpoint]);
$response = $this->http($endpoint);
if ($response[0] == 304) {
// Get from cache
$response[1] = $this->redis->get($endpoint);
}
else if ($response[0] == 200) {
// cache (1 day)
$this->redis->setex($endpoint, 60*60*24, $response[1]);
}
else
return $posts;
}
$json = array_reverse(json_decode($response[1], true));
foreach ($json as $k => $v) {
if ($k < $start)
continue;
// Get post
if ($k == $count)
break;
$post_endpoint = $this->api_root.'/repos/'.$_SESSION['gh']['username'].'/'.$_SESSION['gh']['default_repo'].'/contents/'.$v['path'];
// Only check github if there is no cached value
$body[1] = $this->redis->get($post_endpoint);
if (!$body[1]) {
$body = $this->http($post_endpoint, null, 'GET', array('Accept' => 'application/vnd.github.VERSION.raw'));
if ($body[0] == 304) {
// Get from cache
$body[1] = $this->redis->get($post_endpoint);
}
else if ($body[0] == 200) {
// cache (1 day)
$this->redis->setex($post_endpoint, 60*60*24, $body[1]);
}
else // fail
continue;
}
$formatted_post = $this->format($body[1]);
list($date, $url) = $this->getTitleAndDate($v['name'], $formatted_post['permalink'], $formatted_post['categories']);
$posts[] = array(
'id' => $v['sha'],
'title' => $formatted_post['title'],
'date' => $date,
'sha' => $v['sha'],
'path' => $v['path'],
'url' => $url,
'draft' => $formatted_post['published'] == 'true' ? false : true
);
}
// Get CNAME
if (!$_SESSION['gotten_configs']) {
$cname = $this->api_root.'/repos/'.$_SESSION['gh']['username'].'/'.$_SESSION['gh']['default_repo'].'/contents/CNAME';
unset($this->eTags[$cname]);
$body = $this->http($cname, null, 'GET');
if ($body[0] == 200) {
// Has a CNAME, save it
$json = json_decode($body[1], true);
$_SESSION['cname'] = base64_decode($json['content']);
$_SESSION['cname_sha'] = $json['sha'];
}
// Configs
$config = $this->api_root.'/repos/'.$_SESSION['gh']['username'].'/'.$_SESSION['gh']['default_repo'].'/contents/_config.yml';
unset($this->eTags[$config]);
$body = $this->http($config, null, 'GET');
if ($body[0] == 200) {
$json = json_decode($body[1], true);
$body = base64_decode($json['content']);
$_yaml = preg_split('/\n|\r/', $body, -1, PREG_SPLIT_NO_EMPTY);
foreach ($_yaml as $line) {
if (preg_match('/^#/', $line)) continue;
list($k, $v) = preg_split('/:\s?/', $line, 2);
$k = trim($k);
$v = trim($v);
if ($k == 'markdown') {
$_SESSION['markdown_editor'] = $v;
}
else if ($k == 'permalink') {
// permalink
$_SESSION['default_permalink'] = $v;
}
}
}
$_SESSION['gotten_configs'] = true;
}
return $posts;
}
function getPost($path, $scheduled){
// Scheduled post?
if ($scheduled) {
$path = $this->escape($path);
$q = "select * from schedule where user='{$_SESSION['gh']['id']}' and path='{$path}'";
//echo $q;
$r = $this->db->query($q);
$row = $r->fetch_array(MYSQLI_ASSOC);
$data = json_decode(base64_decode($row['data']), true);
//print_r($data);
$formatted_post = $this->format(base64_decode($data['content']));
return array(
'title' => $row['title'],
'date' => $row['date'],
'path' => $path,
'url' => '',
'schedule_id' => $row['id'],
'body' => $formatted_post['body'],
'tags' => $formatted_post['tags'],
'categories' => $formatted_post['categories'],
'permalink' => $formatted_post['permalink'],
'draft' => false,
'later' => true,
'send_at' => $row['send_at_raw']
);
}
// No, not scheduled post
$post_endpoint = $this->api_root.'/repos/'.$_SESSION['gh']['username'].'/'.$_SESSION['gh']['default_repo'].'/contents/'.$path;
//$body[1] = $this->redis->get($post_endpoint);
//if (!$body[1]) {
$body = $this->http($post_endpoint, null, 'GET', array('Accept' => 'application/vnd.github.VERSION.raw'));
if ($body[0] == 304) {
// Get from cache
$body[1] = $this->redis->get($post_endpoint);
}
else if ($body[0] == 200) {
// cache (1 day)
$this->redis->setex($post_endpoint, 60*60*24, $body[1]);
}
else // fail
return false;
//}
$formatted_post = $this->format($body[1]);
list($date) = $this->getTitleAndDate($post_endpoint);
return array(
'title' => $formatted_post['title'],
'date' => $date,
'path' => $path,
'url' => preg_replace('|.*/|', '', $path),
'body' => $formatted_post['body'],
'tags' => $formatted_post['tags'],
'categories' => $formatted_post['categories'],
'permalink' => $formatted_post['permalink'],
'draft' => $formatted_post['published'] == 'true' ? false : true
);
}
function deleteScheduled($schedule_id, $user_id){
$schedule_id = (int) $schedule_id;
$q = "delete from schedule where user='{$user_id}' and id='{$schedule_id}'";
$this->db->query($q);
return $this->db->affected_rows;
}
function delete($title, $path, $sha, $schedule){
if ($schedule) {
$q = "delete from schedule where user='{$_SESSION['gh']['id']}' and path='$path'";
$this->db->query($q);
return $this->db->affected_rows;
}
$endpoint = $this->api_root.'/repos/'.$_SESSION['gh']['username'].'/'.$_SESSION['gh']['default_repo'].'/contents/'.$path;
$this->http($endpoint, array(
'path' => $path,
'sha' => $sha,
'message' => 'Post deleted: '.$title,
), 'DELETE');
}
function getTitleAndDate($name, $permalink = null, $_categories = null) {
preg_match('/([0-9]{4})\-([0-9]{2})\-([0-9]{2})\-(.*)/', $name, $match);
$year = $match[1];
$month = $match[2];
$day = $match[3];
//$title = preg_replace('|\.[^\.]*$|', '.html', $match[4]);
$title = preg_replace('|\.[^\.]*$|', '', $match[4]);
$strtotime = strtotime("$year-$month-$day");
$date = date('M d, Y', $strtotime);
if ($_categories) {
$categories = implode('/', explode(', ', $_categories));
}
if ($permalink) {
$url = $permalink;
}
else {
switch ($_SESSION['default_permalink']) {
case 'none':
$url = "$categories/{$title}.html";
break;
case 'pretty':
$url = "$categories/$year/$month/$day/$title/";
break;
case 'date':
default:
if (empty($_SESSION['default_permalink'])) {
$url = "$categories/$year/$month/$day/{$title}.html";
}
else {
// custom format
$pattern = array(
'/:month/',
'/:i_month/',
'/:year/',
'/:day/',
'/:i_day/',
'/:short_year/',
'/:title/',
'/:categories/'
);
$replacement = array(
$month,
(int) $month,
$year,
$day,
(int) $day,
date('y', $strtotime),
$title,
$categories
);
$url = preg_replace($pattern, $replacement, $_SESSION['default_permalink']);
}
break;
}
}
$url = ltrim($url, '/');
return array($date, $url);
}
function saveDraft($_data) {
$title = $this->escape($_data['title']);
$body = $this->escape($_data['body']);
$id = (int) $_data['id'];
if (!$title && !$body)
return false;
if ($id) {
$q = "update drafts set title='$title', body='$body', date=now() where user='{$_SESSION['gh']['username']}' and id='$id'";
//echo $q;
$r = $this->db->query($q);
return array('id' => $id);
}
else {
$q = "insert into drafts (title, body, date, user) values ('$title', '$body', now(), '{$_SESSION['gh']['username']}')";
$r = $this->db->query($q);
return array('id' => $this->db->insert_id);
}
}
function getDrafts() {
$q = "select id, title, body, date from drafts where user='{$_SESSION['gh']['username']}' order by date desc";
$r = $this->db->query($q);
$results = array();
while($row = $r->fetch_array(MYSQLI_ASSOC)) {
$row['date'] = date('M d, Y', strtotime($row['date']));
$results[] = $row;
}
return $results;
}
function deleteDraft($id) {
$id = (int) $id;
$q = "delete from drafts where user='{$_SESSION['gh']['username']}' and id='$id'";
$this->db->query($q);
return $this->db->affected_rows;
}
function getUser() {
if ($_SESSION['gh']['username'])
return $_SESSION['gh']['username'];
$response = $this->http($this->api_root.'/user');
$json = json_decode($response[1]);
$this->initMxPanel();
if (!$json->login) {
// Track failed login
$this->mp->track('Failed login');
return false;
}
$_SESSION['gh']['id'] = $_SESSION['gh']['main_id'] = $json->id;
$_SESSION['gh']['email'] = $_SESSION['gh']['main_email'] = $json->email;
$_SESSION['gh']['name'] = $_SESSION['gh']['main_name'] = $json->name ? $json->name : $json->login;
$_SESSION['gh']['username'] = $_SESSION['gh']['main_username'] = $json->login;
$_SESSION['gh']['avatar'] = $_SESSION['gh']['main_avatar'] = $json->avatar_url;
// Get subscription plans here
$this->getSubscription();
// Get orgs
$response = $this->http($this->api_root.'/users/'.$_SESSION['gh']['username'].'/orgs');
if ($response[0] == 200) {
$orgs = json_decode($response[1], true);
foreach($orgs as $org) {
$_SESSION['gh']['orgs'][] = array(
'id' => $org['id'],
'username' => $org['login'],
'avatar' => $org['avatar_url']
);
}
}
// Track login
$this->mp->people->set($_SESSION['gh']['id'], array(
'username' => $json->login,
'$name' => $json->name
));
$this->mp->identify($_SESSION['gh']['id']);
$this->mp->track('Login');
return $json->login;
}
function getSubscription() {
$r = $this->db->query("select plan_ends, paid, trial, auto_renewal from profiles where id='{$_SESSION['gh']['main_id']}'");
if ($r->num_rows > 0) {
list($plan_ends, $_SESSION['paid'], $_SESSION['trial'], $_SESSION['auto_renewal']) = $r->fetch_array(MYSQLI_NUM);
$plan_ends = strtotime($plan_ends);
}
else {
$plan_ends = mktime(0, 0, 0, date("m")+1, date("d"), date("Y"));
$_SESSION['paid'] = 0;
$_SESSION['trial'] = 1;
$_SESSION['auto_renewal'] = 1;
}
$_SESSION['plan_ends'] = date('M d, Y', $plan_ends);
}
function setOrg($sel) {
unset($_SESSION['gh']['page_repos']);
unset($_SESSION['gh']['org_repo']);
// Get configs again
unset($_SESSION['gotten_configs']);
// If main account was selected
if ($sel == $_SESSION['gh']['main_username']) {
$_SESSION['gh']['id'] = $_SESSION['gh']['main_id'];
$_SESSION['gh']['email'] = $_SESSION['gh']['main_email'];
$_SESSION['gh']['name'] = $_SESSION['gh']['main_name'];
$_SESSION['gh']['username'] = $_SESSION['gh']['main_username'];
$_SESSION['gh']['avatar'] = $_SESSION['gh']['main_avatar'];
return;
}
// else
foreach($_SESSION['gh']['orgs'] as $org) {
if ($org['username'] == $sel) {
$_SESSION['gh']['id'] = $org['id'];
$_SESSION['gh']['name'] = $org['username'];
$_SESSION['gh']['username'] = $org['username'];
$_SESSION['gh']['avatar'] = $org['avatar'];
$_SESSION['gh']['org_repo'] = true;
break;
}
}
}
function getPagesRepo() {
if ($_SESSION['gh']['page_repos'])
return $_SESSION['gh']['page_repos'];
$response = $this->http($this->api_root.'/search/repositories?q='.$_SESSION['gh']['username'].'.github.+in:name+user:'.$_SESSION['gh']['username']);
$json = json_decode($response[1], true);
$this->initMxPanel();
if (!$json['items']) {
// Track no repo
$this->mp->identify($_SESSION['gh']['id']);
$this->mp->track('No repo');
return;
}
$_SESSION['gh']['page_repos'] = array();
foreach ($json['items'] as $repos) {
$_SESSION['gh']['page_repos'][] = $repos['name'];
}
$this->updateToken();
}
function updateToken() {
// save token
$post_email = $this->getPostEmail();
$this->db->query("insert into profiles (id, username, token, name, post_email, repo, plan_ends) values ('{$_SESSION['gh']['id']}', '{$_SESSION['gh']['username']}', '{$_SESSION['token']}', '{$_SESSION['gh']['name']}', '{$post_email}', '{$_SESSION['gh']['page_repos'][0]}', DATE_ADD(now(), INTERVAL 30 DAY)) on duplicate key update token='{$_SESSION['token']}', repo='{$_SESSION['gh']['page_repos'][0]}'");
// Update email if any
if ($_SESSION['gh']['email'])
$this->db->query("update profiles set email='{$_SESSION['gh']['email']}' where id='{$_SESSION['gh']['id']}' and email_confirmed='0'");
// Get post email
$r = $this->db->query("select email, post_email, tz, tz_country from profiles where id='{$_SESSION['gh']['id']}'");
list($email, $post_email, $tz, $tz_country) = $r->fetch_array(MYSQLI_NUM);
$_SESSION['post_email'] = $post_email;
$_SESSION['email'] = $email;
$_SESSION['tz'] = (int) $tz;
$_SESSION['tz_country'] = $tz_country;
$this->getSubscription();
}
function upgrade($_data){
$token = $_data['token'];
require_once 'lib/Stripe.php';
Stripe::setApiKey(STRIPE_SK);
try {
// Create customer
$customer = Stripe_Customer::create(array(
"card" => $token,
"plan" => 'annual',
"email" => $_SESSION['email'],
"description" => $_SESSION['gh']['username']
)
);
}
catch(Stripe_CardError $e) {
$body = $e->getJsonBody();
$_SESSION['error'] = $body['error']['message'];
return false;
}
catch(Stripe_InvalidRequestError $r) {
$body = $r->getJsonBody();
$_SESSION['error'] = $body['error']['message'];
return false;
}
//print_r($customer);
// Update db
$this->db->query("update profiles set plan_ends=DATE_ADD(now(), INTERVAL 1 YEAR), paid='1', trial='0', auto_renewal=1, stripe_customer_id='{$customer->id}', stripe_plan_id='{$customer->subscriptions->data[0]->id}' where id='{$_SESSION['gh']['main_id']}'");
$_SESSION['paid'] = 1;
$_SESSION['trial'] = false;
$_SESSION['plan_ends'] = date('M d, Y', mktime(0, 0, 0, date("m"), date("d"), date("Y")+1));
return $_SESSION['plan_ends'];
}
// mail to post
function mailToPost($_params) {
$to = $this->escape($_params['recipient']);
$email_from = $this->escape($_params['sender']);
$from = $this->escape($_params['from']);
// get token
$r = $this->db->query("select id, username, token, repo from profiles where post_email='$to'");
if ($r->num_rows < 1) {
// 404 mail
if (!preg_match('|post\.tinypress\.co|i', $email_from)) {
$txt = 'Your post could not be posted. No user with the email '.$to.' found.'."\r\n\r\n";
$txt .= 'Love, Tinypress <https://tinypress.co>';
$this->mail('Email not posted', $email_from, $txt);
}
return false;
}
list($id, $username, $token, $repo) = $r->fetch_array(MYSQLI_NUM);
$subject = $this->escape($_params['subject']);
$text = $this->escape($_params['body-plain']);
$this->access_token = $token;
$_SESSION['gh']['id'] = $id;
$_SESSION['gh']['username'] = $username;
$_SESSION['gh']['default_repo'] = $repo;
$args = array(
'title' => $subject,
'body' => $text,
);
$this->post($args);
// log mail dump
$this->db->query("insert into mail_dump (username, frm, subject, data) values ('{$_SESSION['gh']['username']}', '{$from}', '{$subject}', '".$this->db->real_escape_string(serialize($_params))."')");
// send success email
if (!preg_match('|post\.tinypress\.co|i', $email_from)) {
$txt = 'Your post has been sent and should be available on your blog shortly.'."\r\n\r\n";
$txt .= 'Love, Tinypress <https://tinypress.co>';
$this->mail('Post successful', $email_from, $txt);
}
// track
$this->mp->identify($_SESSION['gh']['id']);
$this->mp->people->increment($_SESSION['gh']['id'], 'Posts', 1);
$this->mp->people->increment($_SESSION['gh']['id'], 'via Mail', 1);
$this->mp->track('Post');
$_SESSION = array();
}
function updateCname($_post){
// remove http(s)
$cname = $this->escape(strtolower($_post['cname']));
$cname = preg_replace('|^https?://|', '', $cname);
$_SESSION['cname'] = $cname;
$data = array(
'path' => 'CNAME',
'message' => 'Custom domain',
'content' => base64_encode($cname),
);
if ($_SESSION['cname_sha'])
$data['sha'] = $_SESSION['cname_sha'];
$endpoint = $this->api_root.'/repos/'.$_SESSION['gh']['username'].'/'.$_SESSION['gh']['default_repo'].'/contents/CNAME';
$response = $this->http($endpoint, $data, 'PUT');
if ($response[0] == 200 || $response[0] == 201) {
return true;
}
$json = json_decode($response[1]);
$_SESSION['error'] = $json->message;
return false;
}
function updateTZ($_post){
$tz = (int) $_post['tz'];
list($country) = explode(',', $_post['country']);
$this->db->query("update profiles set tz='$tz', tz_country='$country' where id='{$_SESSION['gh']['main_id']}'");
$_SESSION['tz'] = $tz;
$_SESSION['tz_country'] = $country;
return true;
}
function updateEmail($_post){
$email = $this->escape(strtolower($_post['email']));
if (!$this->validate_email($email)) {
$_SESSION['error'] = 'Invalid email. Kindly confirm and try again.';
return false;
}
$this->db->query("update profiles set email='$email', email_confirmed=1 where id='{$_SESSION['gh']['main_id']}'");
$_SESSION['email'] = $email;
return true;
}
function cancelRenewal(){
$this->db->query("update profiles set auto_renewal=0 where id='{$_SESSION['gh']['main_id']}'");
$r = $this->db->query("select stripe_customer_id, stripe_plan_id from profiles where id='{$_SESSION['gh']['main_id']}'");
list($cus_id, $pay_id) = $r->fetch_array(MYSQLI_NUM);
require_once('lib/Stripe.php');
Stripe::setApiKey(STRIPE_SK);
$cu = Stripe_Customer::retrieve($cus_id);
$cu->subscriptions->retrieve($pay_id)->cancel(array('at_period_end' => true));
return true;
}
function preview($text, $parser = 'kramdown'){
$data = array(
'markdown' => $text
);
$parser = strtolower($parser);
$parsers = array('kramdown','maruku','rdiscount','redcarpet');
if (!in_array($parser, $parsers))
$parser = 'kramdown';
$data['parser'] = $parser;
$ch = curl_init();
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_URL, "http://tinypress.co:81/");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$response = curl_exec($ch);
//$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return $response;
}
function onPro(){
/*$diff = strtotime(date('Y-m-d')) - strtotime($_SESSION['plan_ends']);
if ($diff > 0)
return false;*/
return true;
}
// send to github
function post($args) {
/*if (!$this->onPro()) {
$_SESSION['error'] = 'Kindly upgrade your account to be able to post.';
return false;
}*/
// title
$title = $args['title'];
if (!$title) {
$_SESSION['error'] = 'You missed the post title.';
return false;
}
// Send later at?
if ($args['action'] == 'schedule') {
// replace unneeded prepositions
$_rep = array(
'| at |i',
'| by |i',
'| on |i'
);
$args['at'] = preg_replace($_rep, ' ', $args['at']);
$time = strtotime($args['at']);
if (!$time) {
$_SESSION['error'] = 'Schedule time, '.$args['at'].', not understood. Try a different date/time format.';
return false;
}
// Convert time based on timezone
if ($args['timezone']) {
// Update tz here
$this->updateTz($args);
}
$send_time = $time - $_SESSION['tz'];
// Passed?
if ($send_time <= time()) {
$_SESSION['error'] = 'Kindly select a time in the future.';
return false;
}
$send_at = date('Y-m-d H:i', $send_time);
$send_at_raw = date('Y-m-d H:i', $time);
}
// url
$url = $args['url'];
if (!$url) {
$url = ($args['action'] == 'schedule') ? $this->urlfy($title, date('Y-m-d', $send_time)) :
$this->urlfy($title);
}
$yaml['published'] = $args['action'] == 'draft' ? 'false' : 'true';
$yaml['title'] = $title;
$yaml['layout'] = 'post';
// tags
$tags = $args['tags'];
if ($tags) {
$tags = preg_split("/[\s,]+/", $tags);
$yaml['tags'] = '['.implode(', ', $tags).']';
}
// categories
$categories = $args['categories'];
if ($categories) {
$categories = preg_split("/[\s,]+/", $categories);
$yaml['categories'] = '['.implode(', ', $categories).']';
}
// Permalink
$perma = $args['permalink'];
if ($perma)
$yaml['permalink'] = $perma;
// commit
$commit = $args['commit'];
if (!$commit) {
$commit = $args['sha'] ? 'Post update: ' : 'New post: ';
$commit .= $title;
}
// body
$body = "---\r\n";
foreach ($yaml as $k => $v) {
$body .= "$k: $v\r\n";
}
$body .= "---\r\n".$args['body'];
$data = array(
'path' => '_posts/'.$url,
'message' => $commit,
'content' => base64_encode($body),
);
// Updating post
if ($args['sha'])
$data['sha'] = $args['sha'];
$endpoint = $this->api_root.'/repos/'.$_SESSION['gh']['username'].'/'.$_SESSION['gh']['default_repo'].'/contents/_posts/'.$url;
if ($args['action'] == 'schedule') {
// Is there a schedule id? Update
if ($args['schedule_id']) {
$id = (int) $args['schedule_id'];
$this->db->query("update schedule set endpoint='$endpoint', path='_posts/{$url}', title='$title', data='".base64_encode(json_encode($data))."', send_at='$send_at', send_at_raw='$send_at_raw', locked=0, date=now() where user='{$_SESSION['gh']['id']}' and id='$id'");
$_SESSION['status'] = 'Post updated';
}
else {
// Else new
$this->db->query("insert into schedule (user, endpoint, path, title, data, send_at, send_at_raw, date) values ('{$_SESSION['gh']['id']}', '$endpoint', '_posts/{$url}', '$title', '".base64_encode(json_encode($data))."', '$send_at', '$send_at_raw', now())");
$_SESSION['status'] = 'Your post has been scheduled for '.$send_at_raw.'.';
}
// delete draft
$this->deleteDraft($args['save_id']);
return $send_at_raw;
}
else {
$response = $this->http($endpoint, $data, 'PUT');
$this->initMxPanel();
if ($response[0] == 200 || $response[0] == 201) {
// Successful
$_SESSION['status'] = isset($args['draft']) ? 'Your post has been saved as draft and committed.' : 'Your post has been committed. It should be live on your blog shortly.';
// delete draft
$this->deleteDraft($args['save_id']);
// If schedule, delete
if ($args['schedule_id'])
$this->deleteScheduled($args['schedule_id'], $_SESSION['gh']['id']);
// Track successful post
$this->mp->identify($_SESSION['gh']['id']);
$this->mp->people->increment($_SESSION['gh']['id'], 'Posts', 1);
$this->mp->track('Post');
return true;
}
}
// Track failed post
// raw log the session
$this->db->query("insert into log (user, log) values ('{$_SESSION['gh']['username']}', '".$this->db->real_escape_string(serialize($_SESSION))."')");
$this->mp->identify($_SESSION['gh']['id']);
$this->mp->track('Failed post');
$json = json_decode($response[1]);
$_SESSION['error'] = $json->message;
return false;
}
// send due post
function sendDue() {
$q = "select s.id, s.user, p.email, p.token, s.endpoint, s.path, s.title, s.data, s.attempts from schedule s, profiles p where s.send_at <= now() and s.locked=0 and s.user=p.id";
$r = $this->db->query($q);
while(list($id, $user_id, $email, $token, $endpoint, $path, $title, $data, $attempts) = $r->fetch_array(MYSQLI_NUM)) {
$this->db->query("update schedule set locked=1 where id='$id'");
$_data = json_decode(base64_decode($data), true);
$data = array(
'path' => $path,
'message' => $_data['message'],
'content' => $_data['content']
);
$this->access_token = $token;
$response = $this->http($endpoint, $data, 'PUT');
$this->initMxPanel();
if ($response[0] == 200 || $response[0] == 201) {
// Successful
// Mail
$txt = 'Your scheduled post has been sent and should be available on your blog shortly.'."\r\n\r\n";
$txt .= 'Love, Tinypress <https://tinypress.co>';
$this->mail('Scheduled post sent', $email, $txt);
// If schedule, delete
$this->deleteScheduled($id, $user_id);
// Track successful post
$this->mp->identify($user_id);
$this->mp->people->increment($user_id, 'Posts', 1);
$this->mp->track('Post');
}
else {
// If tried trice, give up
if ($attempts > 1) {
$this->mp->identify($user_id);
$this->mp->track('Failed post');
$json = json_decode($response[1]);
$txt = 'Your scheduled post could not be sent at this time. Github sent an additional error:.'."\r\n\r\n";
$txt .= $json->message."\r\n\r\n";
$txt .= "Kindly check everything is rightly set and try again later.\r\n\r\n";
$txt .= 'Love, Tinypress <https://tinypress.co>';
$this->mail('Scheduled post failed', $email, $txt);
}
else {
// Update attempt and schedule + next 5 mins
$this->db->query("update schedule set locked=0, attempts=attempts+1, send_at=DATE_ADD(send_at, INTERVAL 5 MINUTE) where id='$id'");
}
}
}
}
private function http($url, $data = null, $method = 'GET', $_headers = array()) {
//return array(304, '');
//echo $url;
//print_r($data);
$ch = curl_init();
$headers = array(
'User-Agent' => 'Tinypress',
'Content-Type' => 'application/json',
'Accept' => 'application/json'
);
$_headers = array_merge($headers, $_headers);
unset($headers);
//print_r($_headers);
foreach ($_headers as $key => $value) {
$headers[] = "$key: $value";
}
// Oauth 2 access token
if ($this->access_token)
$headers[] = 'Authorization: token '.$this->access_token;
if ($this->eTags[$url])
$headers[] = 'If-None-Match: '.$this->eTags[$url];
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
#curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_ENCODING, "gzip");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
if ($data)
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
$response = curl_exec($ch);
list($header, $body) = explode("\r\n\r\n", $response, 2);
$headers = explode("\r\n", $header);
//print_r($headers);
foreach ($headers as $header) {
list($key, $value) = preg_split('/:\s/', $header);
if (strtolower($key) == 'etag') {
$this->eTags[$url] = $value;
$_SESSION['eTags'][$url] = $value;
break;
}
}
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
//echo $response;