-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathadd_and_send.php
126 lines (62 loc) · 2.37 KB
/
add_and_send.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
<?php
session_start();
require_once __DIR__ . '/db_connect.php';
$db = new DB_CONNECT();
function alert($msg){
echo '<script type="text/javascript">alert("' . $msg . '");window.location = "send_notification.php"; </script>';
}
function prepareGCMAndSend($title,$message,$type){
$jsonMessage = array();
$jsonMessage["title"]=$title;
$jsonMessage["message"]=$message;
$jsonMessage["type"]=$type;
$registrationIDs = array();
$sql = "SELECT * FROM gcm_users;";
$ref = mysql_query($sql);
if (mysql_num_rows($ref) > 0){
while($row = mysql_fetch_assoc($ref))
$registrationIDs[]=$row["gcm_regid"];
}
return sendNotification($jsonMessage,$registrationIDs);
}
function sendNotification($jsonMessage,$registrationIDs){
$apiKey = "AIzaSyC2pnmkewPVU5CCU0O8jHVOGrGvdYgFOhY";
$url = 'https://android.googleapis.com/gcm/send';
$result = "";
$splittedArray = array_chunk($registrationIDs, 1000);
foreach($splittedArray as $ids){
$fields = array(
'registration_ids' => $ids,
'data' => $jsonMessage,
);
$headers = array(
'Authorization: key=' . $apiKey,
'Content-Type: application/json'
);
$ch = curl_init();
curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt( $ch, CURLOPT_POST, true );
curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode( $fields ) );
$result .= "\n".curl_exec($ch);
curl_close($ch);
}
return $result;
}
if (!isset($_SESSION["admin"]))
Header("Location: index.php");
else if(isset($_POST["title"])&&isset($_POST["message"])&&isset($_POST["type"])){
$title=mysql_real_escape_string($_POST["title"]);
$message=mysql_real_escape_string($_POST["message"]);
$type=mysql_real_escape_string($_POST["type"]);
$result = mysql_query("INSERT INTO notifications(title,message,type)VALUES('$title','$message','$type')");
if($result){
$response=prepareGCMAndSend($_POST["title"],$_POST["message"],$_POST["type"]);
echo $response;
alert("Notification send");
}else
alert("Fail to send notification");
}else
Header("Location: add_notification.php");
?>