public function index()
 {
     $post = $this->input->post();
     if ($post) {
         $this->form_validation->set_rules('push_message', 'Message', 'trim|required');
         if ($this->form_validation->run()) {
             $deviceids = $this->common_model->selectData(DEVICE, '*', array("status" => 'Active'));
             $pushMessage = $post['push_message'];
             $msg = array('message' => $pushMessage, 'title' => 'Gujjubazar', 'subtitle' => 'No. 1 Classified site', 'type' => 'message', 'msgcnt' => 3, 'vibrate' => 1, 'sound' => 1);
             $macids[] = array();
             if (!empty($deviceids)) {
                 foreach ($deviceids as $key => $value) {
                     $macids[] = $value->macid;
                 }
             }
             if (count($macids) != 0) {
                 sendNotification($macids, $msg);
             }
             redirect('admin/dashboard');
         } else {
             $flash_arr = array('flash_type' => 'error', 'flash_msg' => 'Blank Push notification not allowed.');
         }
     }
     $data['view'] = "index";
     $data['flash_arr'] = $flash_arr;
     $this->load->view('admin/content', $data);
 }
Exemplo n.º 2
0
function pushNotificationsIOS($messageIOS)
{
    $sqlTD = @mysql_query("select distinct token from notificaciones where estatus = 1");
    $numberRows = mysql_num_rows($sqlTD);
    if ($numberRows > 0) {
        while ($row = mysql_fetch_array($sqlTD)) {
            sendNotification($row[token], "HOLA ArMoving");
            echo $row[token];
        }
    }
}
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);
}
Exemplo n.º 4
0
 public static function on_transition_post_status($new_status, $old_status, $post)
 {
     if (empty($post) || $new_status !== "publish") {
         return;
     }
     $title_option = get_option('webpush_title');
     update_option('webpush_payload', array('title' => $title_option === 'blog_title' ? get_bloginfo('name') : $title_option, 'body' => get_the_title($post->ID), 'url' => get_permalink($post->ID)));
     $subscriptions = WebPush_DB::get_subscriptions();
     foreach ($subscriptions as $subscription) {
         if (!sendNotification($subscription->endpoint)) {
             // If there's an error while sending the push notification,
             // the subscription is no longer valid, hence we remove it.
             WebPush_DB::remove_subscription($subscription->endpoint);
         }
     }
 }
 public function messagedetail()
 {
     $uid = $this->user_session['uid'];
     $allMessages = array();
     $get = $this->input->get();
     $post = $this->input->post();
     if ($post) {
         if (trim($post['message']) != '' && trim($get['user']) != '') {
             $data = array('clad_id' => trim($get['ad']), 'ad_msg_from' => $uid, 'ad_msg_to' => trim($get['user']), 'ad_message' => trim($post['message']), 'ad_msg_read_flag' => 0);
             $ret = $this->common_model->insertData(MESSAGE, $data);
             /*** User notification ***/
             $macids = array();
             $macid = $this->common_model->getMacids(trim($get['user']));
             foreach ($macid as $val) {
                 $macids[] = $val->macid;
             }
             ## get ad title
             $adDetail = $this->common_model->selectData(CLASSIFIEDAD, 'clad_title', array("clad_id" => $get['ad']));
             $pushMsg = "You have new message on Ad " . $adDetail[0]->clad_title . " - " . trim($post['message']);
             $msg = array('message' => $pushMsg, 'title' => 'Gujjubazar', 'subtitle' => 'No. 1 Classified site', 'type' => 'message', 'msgcnt' => 3, 'vibrate' => 1, 'sound' => 1);
             if (count($macids) != 0) {
                 sendNotification($macids, $msg);
             }
             $this->manageCache($get['ad']);
         }
     }
     if ($get['user'] != 0) {
         $messages = $this->common_model->getallmessage($get['ad'], $uid, $get['user']);
     } else {
         $messages = $this->common_model->selectData(ADREPLY, '*', array("clad_id" => $get['ad']), 'ad_reply_created_date', 'asc');
     }
     $where = 'ad_msg_to = ' . $uid . " AND clad_id =" . $get['ad'] . " AND ad_msg_from =" . $get['user'];
     $update = $this->common_model->updateData(MESSAGE, array('ad_msg_read_flag' => 1), $where);
     $where = "clad_id =" . $get['ad'];
     $update = $this->common_model->updateData(ADREPLY, array('ad_reply_status' => 1), $where);
     ## update notification cache
     $this->filecachemodel->processUpdateCache($uid, $get['ad']);
     ## Get ad detail by id
     $res = $this->common_model->selectData(CLASSIFIEDAD, 'clad_id,clad_title', array("clad_id" => $get['ad']));
     $data['ad_detail'] = $res;
     $data['allmessage'] = $messages;
     $data['uid'] = $uid;
     $data['fuid'] = $get['user'];
     $data['view'] = 'messagedetail';
     $this->load->view('content', $data);
 }
Exemplo n.º 6
0
}
// don't have and decline to answer
$test = array('execic' => 'a0HV0000002aEse', 'senioric' => 'a0HV0000002aEsg', 'promorate' => 'a0HV0000002aEss');
// check to see if they have changed between entries
$testFlag = false;
foreach ($test as $key => $val) {
    $f1 = $entry->getResponseByQuestion($val);
    $f2 = $prior->getResponseByQuestion($val);
    if ($f1 != $f2) {
        writeLog("{$key} status has changed");
        $testFlag = true;
    }
}
// if so, send a notification
if ($testFlag) {
    $url = Sforce::getInstance()->serverURL . $entry->Account__c;
    $subject = 'Top Company Promotion Rate and/or Position Verification';
    $msg = "The Top Company application for {$user->company} has inconsistent position information and should be reviewed. ";
    $msg .= "You may access the entry at {$url}.";
    sendNotification($msg, $subject);
}
try {
    $result = $entry->save();
} catch (Exception $e) {
    $message = "Please type your comment directly or copy and paste only plain text into the comment box.";
}
if ($result != "Saved") {
    echo "Please type your comment directly or copy and paste only plain text into the comment box.";
} else {
    echo "Saved";
}
Exemplo n.º 7
0
    $mail->Host = 'smtp.gmail.com';
    $mail->Port = 587;
    $mail->SMTPSecure = 'tls';
    $mail->SMTPAuth = true;
    $mail->Username = "******";
    $mail->Password = getenv('PWD_GMAIL_TIMGROUP');
    $mail->setFrom('*****@*****.**', 'Timgroup ETH');
    $mail->addAddress($to, '');
    $mail->Subject = 'Online Experiment Notification';
    $mail->msgHTML("<p>Dear participant,<br><br>Your next session of the online experiment is now ready!<br><br>Best regards,<br>The Timgroup notification bot");
    $mail->send();
}
for ($i = 0; $i < sizeof($notifList); $i++) {
    $row = explode("\t", $notifList[$i]);
    $done = $row[0];
    if ($done == '1') {
        continue;
    }
    $t1 = strtotime($row[1]);
    if ($t1 > $t0) {
        continue;
    }
    $mailTo = $row[2];
    if ($mailTo == '') {
        continue;
    }
    sendNotification($mailTo);
    $row[0] = '1';
    $notifList[$i] = implode("\t", $row);
}
file_put_contents($notifFile, implode("\n", $notifList));
    echo '<li><a href="' . ABSOLUTE_URL . 'test/notification?action=privatenone&id=' . $plid . '">Private without sender</a> (<strong>notification</strong>)</li>';
    echo '<li><a href="' . ABSOLUTE_URL . 'test/notification?action=publicsender&id=' . $plid . '">Public with sender</a> (<strong>news</strong>)</li>';
    echo '<li><a href="' . ABSOLUTE_URL . 'test/notification?action=publicnone&id=' . $plid . '">Public without sender</a> (<strong>news</strong>)</li>';
    echo '</ul>';
    switch ($action) {
        case 'privatesender':
            sendNotification($player->getId(), true, false);
            break;
        case 'privatenone':
            sendNotification($player->getId(), false, false);
            break;
        case 'publicsender':
            sendNotification($player->getId(), true, true);
            break;
        case 'publicnone':
            sendNotification($player->getId(), false, true);
            break;
    }
} else {
    echo '<p style="color: red;">User not found! Append id=USER_ID to the URL.</p>';
}
function sendNotification($id, $sender, $public)
{
    echo '<h1>';
    echo $sender ? 'With sender' : 'Without sender';
    echo ' and ';
    echo $public ? 'public' : 'private';
    echo '</h1>';
    $player = Dolumar_Players_Player::getFromId($id);
    $other = Dolumar_Players_Player::getFromId(Neuron_Core_Tools::getInput('_GET', 'from', 'int', 1));
    if ($sender) {
function ajax_saveItemGroupData_afterSave($SubjectKey,$StudyEventOID,$StudyEventRepeatKey,$FormOID,$FormRepeatKey,$ItemGroupOID,$ItemGroupRepeatKey,$hasModif,$ajax){
  //Send AE notification
  $ajax->addLog(__FUNCTION__ . "($SubjectKey,$StudyEventOID,$StudyEventRepeatKey,$FormOID,$FormRepeatKey,$ItemGroupOID,$ItemGroupRepeatKey,\$ajax)",INFO);
  if($StudyEventOID=="AE" && $FormOID=="FORM.AE" && $hasModif ){
    //Template
    $template = dirname(__FILE__)."/templates/AE.htm";
    if(!file_exists($template)){
      $str = "Template not found '$template'.";
      $ajax->addLog($str,ERROR);
    }
    $handle = fopen($template, "r");
    $htmlContent = fread($handle, filesize($template));
    fclose($handle);
    //Values
    $values = $ajax->m_ctrl->bocdiscoo()->getDecodedValues($SubjectKey,"1","0","FORM.ENROL","0","ENROL","0");
    $values += $ajax->m_ctrl->bocdiscoo()->getDecodedValues($SubjectKey,"1","0","FORM.IC","0","DS","0");    
    $values += $ajax->m_ctrl->bocdiscoo()->getDecodedValues($SubjectKey,"1","0","FORM.IC","0","DM","0");    
    $values += $ajax->m_ctrl->bocdiscoo()->getDecodedValues($SubjectKey,$StudyEventOID,$StudyEventRepeatKey,$FormOID,$FormRepeatKey,$ItemGroupOID,$ItemGroupRepeatKey);

    $code = array("{SITENAME}", "{SITEID}", "{INVID}", "{SUBJID}", "{BRTHDT}", "{SEX}", "{AERK}", "{DIAG}", "{STDT}", "{AESEV}", "{AECONTR}", "{AEACN}", "{AEOUT}", "{AEENDTC}", "{AESER}", "{AECOM}");
    $value = array($values['ENROL.SITENAME']
                  ,$values['ENROL.SITEID']
                  ,$values['DS.INVNAM']
                  ,$SubjectKey
                  ,$values['DM.BRTHDTC']
                  ,$values['DM.SEX']
                  ,$FormRepeatKey
                  ,utf8_decode($values['AE.AETERM'])
                  ,$values['AE.AESTDTC']
                  ,$values['AE.AESEV']
                  ,$values['AE.AECONTR']
                  ,$values['AE.AEACN']
                  ,$values['AE.AEOUT']
                  ,$values['AE.AEENDTC']
                  ,$values['AE.AESER']
                  ,$values['AE.AECOM']);
        
    $htmlContent = str_replace($code, $value, $htmlContent);
    
    $filename = $ajax->m_tblConfig["APP_NAME"].'_Adverse_Event_-_Patient_'. $SubjectKey .'_Site_'.$values['ENROL.SITEID'].'.pdf';
    
    $mailSubject = $ajax->m_tblConfig["APP_NAME"].' - Adverse Event - Patient '. $SubjectKey .', Site '.$values['ENROL.SITEID'];
    
    $bodyMessage = "
    Please find enclosed a notice of adverse event.
    
    The patient profile can be downloaded here: http://". $GLOBALS['egw']->accounts->config['hostname'] . $GLOBALS['egw']->accounts->config['webserver_url'] ."/index.php?menuaction=alixedc.uietude.subjectPDF&mode=profile&SubjectKey=". $SubjectKey ."";
            
    //Description qui figurera en en-tête de la page de notification
    $description = "Adverse Event";
    
    $recipients = $ajax->m_ctrl->bocdiscoo()->getValue($SubjectKey,$StudyEventOID,$StudyEventRepeatKey,$FormOID,$FormRepeatKey,$ItemGroupOID,$ItemGroupRepeatKey,"AE.PVEMAIL");

    sendNotification($htmlContent, $mailSubject, $recipients, $filename, $bodyMessage,$ajax);

  }
}
function notifyUser($userid, $prizeid, $winEmailTemplate, $winNotTemplate)
{
    $claimURL = URL_CANVAS . "?p=redeem&id={$prizeid}";
    $claimLink = "<a href='" . $claimURL . "'>" . $claimURL . "</a>";
    $message .= "Prize {$prizeid} awarded to user {$userid}. ";
    $message .= "User needs to use following link to claim their prize: " . $claimLink;
    //////////////////////////
    // set up data to notify user
    require_once PATH_CORE . '/classes/user.class.php';
    $ut = new UserTable($db);
    $uit = new UserInfoTable($db);
    $user = $ut->getRowObject();
    $user->load($userid);
    require_once PATH_CORE . '/classes/prizes.class.php';
    $pt = new PrizeTable($db);
    $prize = $pt->getRowObject();
    $prize->load($prizeid);
    $nameWords = explode(" ", $user->name);
    require_once PATH_CORE . '/classes/template.class.php';
    $templateObj = new template($db);
    $columns['prizeTitle'] = $prize->title;
    $columns['claimURL'] = $claimURL;
    $columns['firstName'] = $nameWords[0];
    $callbacks = array();
    $winEmail = clone $winEmailTemplate;
    // i hate php
    $winNot = clone $winNotTemplate;
    // construct an email for this specific user
    $winEmail->email = $user->email;
    $winEmail->subject = $templateObj->processRow($columns, $winEmailTemplate->subject, $callbacks);
    $winEmail->body = $templateObj->processRow($columns, $winEmailTemplate->body, $callbacks);
    // construct notification info
    $winNot->body = $templateObj->processRow($columns, $winNotTemplate->body, $callbacks);
    $fbIds = $uit->getFbIdsForUsers(array($user->userid));
    $winNot->fbId = $fbIds[0];
    //$mailtoText = "mailto:$winEmail->email?subject=$winEmail->subject&body=$winEmail->body";
    // do send notifications
    echo "Mailing {$winEmail->email}...";
    sendEmail($winEmail);
    echo "Notifying {$winNot->fbId}...";
    sendNotification($winNot);
}
Exemplo n.º 11
0
 function addMember($user, $notify)
 {
     global $sql;
     global $time;
     $div_id = $this->fields['DivisionID'];
     $game_id = $this->fields['Game'];
     $q = "SELECT " . TBL_USERS . ".*" . " FROM " . TBL_USERS . " WHERE (" . TBL_USERS . ".user_id = '{$user}')";
     $result = $sql->db_Query($q);
     $Name = mysql_result($result, 0, TBL_USERS . ".user_name");
     $UniqueGameID = "";
     $gamerID = updateGamer($user, $game_id, $Name, $UniqueGameID);
     $q = " INSERT INTO " . TBL_MEMBERS . "(Division,User,timestamp)\r\n\t\tVALUES ({$div_id},{$user},{$time})";
     $sql->db_Query($q);
     // User will automatically be signed up to all current events this division participates in
     $q_2 = "SELECT " . TBL_TEAMS . ".*, " . TBL_EVENTS . ".*" . " FROM " . TBL_TEAMS . ", " . TBL_EVENTS . " WHERE (" . TBL_TEAMS . ".Division = '{$div_id}')" . " AND (" . TBL_TEAMS . ".Event = " . TBL_EVENTS . ".EventID)" . " AND (" . TBL_EVENTS . ".Status != 'finished')";
     $result_2 = $sql->db_Query($q_2);
     $num_rows_2 = mysql_numrows($result_2);
     if ($num_rows_2 > 0) {
         for ($j = 0; $j < $num_rows_2; $j++) {
             $event_id = mysql_result($result_2, $j, TBL_EVENTS . ".EventID");
             $event = new Event($event_id);
             $team_id = mysql_result($result_2, $j, TBL_TEAMS . ".TeamID");
             $team_banned = mysql_result($result_2, $j, TBL_TEAMS . ".Banned");
             // Verify there is no other player for that user/event/team
             $q = "SELECT COUNT(*) as NbrPlayers" . " FROM " . TBL_PLAYERS . " WHERE (Event = '{$event_id}')" . " AND (Team = '{$team_id}')" . " AND (User = "******")";
             $result = $sql->db_Query($q);
             $row = mysql_fetch_array($result);
             $nbrplayers = $row['NbrPlayers'];
             if ($nbrplayers == 0) {
                 $q = " INSERT INTO " . TBL_PLAYERS . "(Event,Gamer,Team,ELORanking,TS_mu,TS_sigma,G2_r,G2_RD,G2_sigma,Joined,Banned)\r\n\t\t\t\t\tVALUES ({$event_id}, {$gamerID}, {$team_id}, " . $event->getField('ELO_default') . ", " . $event->getField('TS_default_mu') . ", " . $event->getField('TS_default_sigma') . "," . $event->fields['G2_default_r'] . "," . $event->fields['G2_default_RD'] . "," . $event->fields['G2_default_sigma'] . ",{$time}, {$team_banned})";
                 $sql->db_Query($q);
                 $event->setFieldDB('IsChanged', 1);
             }
         }
     }
     if ($notify) {
         list($cname, $ctag, $cid) = $this->getClanInfo();
         $sendto = $user;
         $subject = SITENAME . " " . $cname;
         $message = EB_CLANM_L39 . $username . EB_CLANM_L40 . $cname . EB_CLANM_L41 . EB_CLANM_L43;
         sendNotification($sendto, $subject, $message, $fromid = 0);
         // Send email
         $message = EB_CLANM_L39 . $username . EB_CLANM_L39 . $cname . EB_CLANM_L42 . SITEURLBASE . e_PLUGIN_ABS . "ebattles/claninfo.php?clanid=" . $cid . EB_CLANM_L43;
         require_once e_HANDLER . "mail.php";
         sendemail($useremail, $subject, $message);
     }
 }
Exemplo n.º 12
0
         case 'Teams':
             $q_Players = "SELECT DISTINCT " . TBL_USERS . ".*" . " FROM " . TBL_MATCHS . ", " . TBL_SCORES . ", " . TBL_TEAMS . ", " . TBL_PLAYERS . ", " . TBL_GAMERS . ", " . TBL_USERS . " WHERE (" . TBL_MATCHS . ".MatchID = '{$match_id}')" . " AND (" . TBL_SCORES . ".MatchID = " . TBL_MATCHS . ".MatchID)" . " AND (" . TBL_TEAMS . ".TeamID = " . TBL_SCORES . ".Team)" . " AND (" . TBL_PLAYERS . ".Team = " . TBL_TEAMS . ".TeamID)" . " AND (" . TBL_PLAYERS . ".Gamer = " . TBL_GAMERS . ".GamerID)" . " AND (" . TBL_GAMERS . ".User = "******".user_id)";
             $result_Players = $sql->db_Query($q_Players);
             $nbr_players = mysql_numrows($result_Players);
             break;
         default:
     }
     if ($nbr_players > 0) {
         for ($j = 0; $j < $nbr_players; $j++) {
             $pname = mysql_result($result_Players, $j, TBL_USERS . ".user_name");
             $pemail = mysql_result($result_Players, $j, TBL_USERS . ".user_email");
             $message = EB_MATCHR_L53 . $pname . EB_MATCHR_L54 . EB_MATCHR_L55 . $event->getField('Name') . EB_MATCHR_L56;
             $sendto = mysql_result($result_Players, $j, TBL_USERS . ".user_id");
             $sendtoemail = mysql_result($result_Players, $j, TBL_USERS . ".user_email");
             if (check_class($pref['eb_pm_notifications_class'])) {
                 sendNotification($sendto, $subject, $message, $fromid);
             }
             if (check_class($pref['eb_email_notifications_class'])) {
                 // Send email
                 require_once e_HANDLER . "mail.php";
                 sendemail($sendtoemail, $subject, $message);
             }
         }
     }
     //header("Location: eventinfo.php?eventid=$event_id");
 } else {
     $match->match_scores_update();
     // Automatically Update Players stats only if Match Approval is Disabled
     if ($event->getField('MatchesApproval') == eb_UC_NONE) {
         switch ($event->getMatchPlayersType()) {
             case 'Players':
Exemplo n.º 13
0
function SubmitTeamChallenge($event_id, $challengerpuid, $challengedtid)
{
    global $sql;
    global $text;
    global $tp;
    global $time;
    global $pref;
    $event = new Event($event_id);
    // Challenger Info
    // Attention here, we use user_id, so there has to be 1 user for 1 player
    $q = "SELECT " . TBL_PLAYERS . ".*, " . TBL_USERS . ".*" . " FROM " . TBL_PLAYERS . ", " . TBL_GAMERS . ", " . TBL_USERS . " WHERE (" . TBL_PLAYERS . ".Event = '{$event_id}')" . "   AND (" . TBL_PLAYERS . ".Gamer = " . TBL_GAMERS . ".GamerID)" . "   AND (" . TBL_USERS . ".user_id = " . TBL_GAMERS . ".User)" . "   AND (" . TBL_USERS . ".user_id = '{$challengerpuid}')";
    $result = $sql->db_Query($q);
    $challengerpid = mysql_result($result, 0, TBL_PLAYERS . ".PlayerID");
    $challengertid = mysql_result($result, 0, TBL_PLAYERS . ".Team");
    list($challengertclan, $challengertclantag, $challengertclanid) = getClanInfo($challengertid);
    // Challenged Info
    // Nothing needed here
    // ...
    $challenge_times = '';
    for ($date = 1; $date <= $event->getField('MaxDatesPerChallenge'); $date++) {
        $challenge_date = $_POST['date' . $date];
        $challenge_time_local = strtotime($challenge_date);
        $challenge_time_local = $challenge_time_local - TIMEOFFSET;
        // Convert to GMT time
        if ($date > 1) {
            $challenge_times .= ',';
        }
        $challenge_times .= $challenge_time_local;
    }
    // comments
    //----------------------------------
    $comments = $tp->toDB($_POST['challenge_comments']);
    $time_reported = $time;
    // Create Challenge ------------------------------------------
    $q = "INSERT INTO " . TBL_CHALLENGES . "(Event,ChallengerTeam,ChallengedTeam,ReportedBy,TimeReported,Comments,Status,MatchDates)\r\n\tVALUES (\r\n\t'{$event_id}',\r\n\t'{$challengertid}',\r\n\t'{$challengedtid}',\r\n\t'{$challengerpuid}',\r\n\t'{$time_reported}',\r\n\t'{$comments}',\r\n\t'requested',\r\n\t'{$challenge_times}'\r\n\t)";
    $result = $sql->db_Query($q);
    // Send PM
    $fromid = 0;
    $subject = SITENAME . " " . EB_CHALLENGE_L23;
    // All members of the challenged division will receive the PM
    $q = "SELECT " . TBL_TEAMS . ".*, " . TBL_MEMBERS . ".*, " . TBL_USERS . ".*" . " FROM " . TBL_TEAMS . ", " . TBL_USERS . ", " . TBL_MEMBERS . " WHERE (" . TBL_TEAMS . ".TeamID = '{$challengedtid}')" . " AND (" . TBL_MEMBERS . ".Division = " . TBL_TEAMS . ".Division)" . " AND (" . TBL_USERS . ".user_id = " . TBL_MEMBERS . ".User)";
    $result = $sql->db_Query($q);
    $num_rows = mysql_numrows($result);
    if ($num_rows > 0) {
        for ($j = 0; $j < $num_rows; $j++) {
            $challengedpname = mysql_result($result, $j, TBL_USERS . ".user_name");
            $challengedpemail = mysql_result($result, $j, TBL_USERS . ".user_email");
            $message = EB_CHALLENGE_L24 . $challengedpname . EB_CHALLENGE_L25 . $challengertclan . EB_CHALLENGE_L26 . $event->getField('Name') . EB_CHALLENGE_L27;
            if (check_class($pref['eb_pm_notifications_class'])) {
                $sendto = mysql_result($result, $j, TBL_USERS . ".user_id");
                sendNotification($sendto, $subject, $message, $fromid);
            }
            if (check_class($pref['eb_email_notifications_class'])) {
                // Send email
                require_once e_HANDLER . "mail.php";
                sendemail($challengedpemail, $subject, $message);
            }
        }
    }
}
Exemplo n.º 14
0
/**
 *		CONTINIOUS TRACKING
 *		Tracking:
 *		- User status changes to track if a user is online/offline
 *			- User lastseen (privacy options) (attached to online/offline status)
 *		- User profile pictures (and changes)
 *     - User status message (and changes)
 */
function track()
{
    global $DBH, $wa, $tracking_ticks, $tracking_numbers, $whatsspyNotificatons, $crawl_time, $whatsappAuth, $pollCount, $lastseenCount, $statusMsgCount, $picCount, $request_error_queue, $continue_tracker_session, $whatsspyPerformanceMode;
    $crawl_time = time();
    setupWhatsappHandler();
    retrieveTrackingUsers();
    tracker_log('[init] Started tracking with phonenumber ' . $whatsappAuth['number']);
    if ($continue_tracker_session == false) {
        startTrackerHistory();
        sendNotification($DBH, null, $whatsspyNotificatons, 'tracker', ['title' => 'WhatsSpy Public has started tracking!', 'description' => 'tracker has started tracking ' . count($tracking_numbers) . ' users.', 'event-type' => 'start']);
    } else {
        $continue_tracker_session = false;
    }
    while (true) {
        $crawl_time = time();
        // Socket read
        $tick_start = microtime(true);
        if ($whatsspyPerformanceMode === true) {
            while (microtime(true) - $tick_start < 1.0 && $wa->pollMessage() === true) {
                echo microtime(true) - $tick_start . "\r\n";
                tracker_debug('Socket read called with poll time: ' . microtime(true) - $tick_start);
            }
        } else {
            $wa->pollMessage();
        }
        $tick_end = microtime(true);
        $poll_took = number_format($tick_end - $tick_start, 4);
        // Check if database set is up to date
        if (count($tracking_numbers) > base64_decode('NzAw')) {
            tracker_log(base64_decode("UEiQOiBGYXRhbCBFcnJvcjogVHJhY2tpbmcgdG9vIG1hbnkgY29udGFjdHMsIGFib3J0aW5nIHRyYWNraW5nLg=="), true, true);
            exit;
        }
        list($usec, $sec) = explode(' ', microtime());
        // split the microtime on space with two tokens $usec and $sec.
        $usec = str_replace("0.", ".", number_format($usec, 4));
        // remove the leading '0.' from usec
        tracker_log("[poll #{$pollCount}] Tracking " . count($tracking_numbers) . " users (poll took {$poll_took})", true, false);
        //	1) STATUS MESSAGE (and privacy)
        //
        // Check status message
        if ($pollCount % calculateTick($tracking_ticks['statusmsg']) == 0) {
            tracker_log('[status-msg #' . $statusMsgCount . '] Checking ' . count($tracking_numbers) . ' users.');
            if (count($tracking_numbers) > 0) {
                $wa->sendGetStatuses($tracking_numbers);
            }
            $statusMsgCount++;
        }
        //	2) PROFILE PICTURE (and privacy)
        //
        // Check profile picture
        if ($pollCount % calculateTick($tracking_ticks['profile-pic']) == 0) {
            tracker_log('[profile-pic #' . $picCount . '] Checking ' . count($tracking_numbers) . ' users.');
            foreach ($tracking_numbers as $number) {
                $wa->sendGetProfilePicture($number, true);
            }
            $picCount++;
        }
        //	3) DATABASE ACCOUNT REFRESH
        //
        // Check user database and refresh user set every hour but with a offset of 80 seconds.
        if ($pollCount % calculateTick($tracking_ticks['refresh-db']) == calculateTick($tracking_ticks['refresh-db'] - 80)) {
            retrieveTrackingUsers(true);
        }
        //  4) SOCKET RESET AND LOGIN
        //
        // Disconnect and reconnect with whatsapp to prevent dead tracker
        if ($pollCount % calculateTick($tracking_ticks['reset-socket']) == calculateTick($tracking_ticks['reset-socket'] - 40)) {
            resetSocket();
            retrieveTrackingUsers(false);
        }
        //	5) DATABASE ACCOUNT VERIFY CHECK
        //
        // Verify any freshly inserted accounts and check if there really whatsapp users.
        // Check everey 5 minutes.
        // When the user is verified the number is automaticly added to the tracker running DB.
        if ($pollCount % calculateTick($tracking_ticks['verify-check']) == 0) {
            verifyTrackingUsers();
        }
        //	6) WHATSAPP PING
        //
        // Keep connection alive (<300s)
        if ($pollCount % calculateTick($tracking_ticks['keep-alive']) == 0) {
            tracker_log('[keep-alive] Ping sent.', true, false);
            $wa->sendPing();
        }
        // usage of 39512f5ea29c597f25483697471ac0b00cbb8088359c219e98fa8bdaf7e079fa
        $pollCount++;
        // Sleep if no more messages could be processed.
        if ($poll_took < 1.0) {
            $sleeping = 1.0 - $poll_took;
            usleep($sleeping * 1000000);
        }
    }
}
Exemplo n.º 15
0
/**
 * The following function will send a GCM notification using curl.
 * 
 * @param $apiKey		[string] The Browser API key string for your GCM account
 * @param $registrationIdsArray [array]  An array of registration ids to send this notification to
 * @param $messageData		[array]	 An named array of data to send as the notification payload
 */
function sendNotification($apiKey, $registrationIdsArray, $messageData)
{
    $headers = array("Content-Type:" . "application/json", "Authorization:" . "key=" . $apiKey);
    $data = array('data' => $messageData, 'registration_ids' => $registrationIdsArray);
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_URL, "https://android.googleapis.com/gcm/send");
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    $response = curl_exec($ch);
    curl_close($ch);
    return $response;
}
// Message to send
$message = "nope";
$tickerText = "ticker text message";
$contentTitle = "content title";
$contentText = "content body";
$registrationId = 'APA91bGTD_ZnC3Az_3p9u7Ov9FrSEdG4C5uuQHQh-iRgUdf9TY_jfU_lPPLjIDarcttH0SVyy-JADevaPqerlC8ombtqUC8OPZba5ADtmH-NgJm75LP68liCHbbUo0EOhKyM6PWlBuIf';
$apiKey = "AIzaSyAX2VW606eEkviCQwAFzRpppY5XqujyJpQ";
$response = sendNotification($apiKey, array($registrationId), array('message' => $message, 'tickerText' => $tickerText, 'contentTitle' => $contentTitle, "contentText" => $contentText));
echo $response;
<?php

function sendNotification($apiKey, $registrationIdsArray, $messageData)
{
    $headers = array("Content-Type:" . "application/json", "Authorization:" . "key=" . $apiKey);
    $data = array('data' => $messageData, 'registration_ids' => $registrationIdsArray);
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_URL, "https://android.googleapis.com/gcm/send");
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    $response = curl_exec($ch);
    curl_close($ch);
    return $response;
}
// MENSAGEM
$message = 'Mensagem';
$title = "Testando";
$exemploParam = "Exemplo como passar parametro.";
//CODIGO GERADO PELO GOOGLE PARA O DEVICE - O IDEAL É GUARDAR ESSE CÓDIGO NO BANCO E GERAR UM LOOP AQUI PARA O ENVIO.
// PARA PROJETOS GRANDES ACONSELHO UTILIZAR UM CRON PARA AGENDAMENTO DOS ENVIOS
$registrationId = "REGISTRO DO DEVICE GERADO PELO APLICATIVO";
//API KEY GERADA PELO GOOGLE
$apiKey = "API KEY AQUI";
$response = sendNotification($apiKey, array($registrationId), array('message' => $message, 'exemploParam' => $exemploParam, 'title' => $title));
Exemplo n.º 17
0
     $getKey = mysql_fetch_array($selectKey);
     $key = $getKey["android_key"];
     $messageText = "A self-made workout has been added/edited in fitness4.me";
     if ($key != "") {
         sentandroid($key, $messageText, $level = "");
     }
     //get iphone device key
     $selectIphoneKey = mysql_query("select devicetoken from apple_devices where user_id='" . $userid . "'");
     $getIphoneKey = mysql_fetch_array($selectIphoneKey);
     $iphonekey = $getIphoneKey["devicetoken"];
     //get user plan
     $selectPlan = mysql_query("select plan from fitness_user_general where user_id='" . $userid . "'");
     $getPlan = mysql_fetch_array($selectPlan);
     $plan = $getPlan["plan"];
     if ($iphonekey != "") {
         sendNotification($messageText, $iphonekey, $sender = "", $level = "", $plan);
     }
     if ($workoutid == "null") {
         $query = "insert into fitness_selfmade_workouts(`userid`,`workout_name`,`workout_equipment`,`workout_focus`,`collection`,`duration`,`date_created`) values('" . $userid . "','" . $workoutName . "','" . $equipments . "','" . $muscles . "','" . $products . "','" . $time . "','" . $date . "')";
         mysql_query($query);
         $sql = 'SELECT id FROM fitness_selfmade_workouts order by id DESC limit 0,1';
         $query_execute = mysql_query($sql);
         $result = mysql_fetch_array($query_execute);
         $lastID = $result['id'];
     } else {
         $query = "update fitness_selfmade_workouts set workout_name='" . $workoutName . "',workout_equipment='" . $equipments . "',workout_focus='" . $muscles . "',collection='" . $products . "',duration='" . $time . "' where id='" . $workoutid . "' and userid='" . $userid . "'";
         mysql_query($query);
         $lastID = $workoutid;
     }
     echo $lastID;
 } else {
Exemplo n.º 18
0
    $mail->Port = 587;
    $mail->SMTPSecure = 'tls';
    $mail->SMTPAuth = true;
    $mail->Username = "******";
    $mail->Password = getenv('PWD_GMAIL_TIMGROUP');
    $mail->setFrom('*****@*****.**', 'Timgroup Experiment');
    $mail->addAddress($to, '');
    $mail->Subject = 'Online Experiment Notification';
    $mail->msgHTML("<p>Dear participant,<br><br>Your next session of the online experiment is now ready!<br><br>Best regards,<br>The Timgroup notification bot");
    if (!$mail->send()) {
        echo "Mailer Error: " . $mail->ErrorInfo;
    } else {
        echo "Message sent!";
    }
}
sendNotification('*****@*****.**');
//
// for($i=0;$i<sizeof($notifList);$i++){
//   $row = explode("\t",$notifList[$i]);
//   $done = $row[0];
//   if($done=='1'){
//     continue;
//   };
//   $t1 = strtotime($row[1]);
//   if($t1>$t0){
//     continue;
//   };
//   $mailTo = $row[2];
//   if($mailTo==''){
//     continue;
//   };
Exemplo n.º 19
0
<?php

require "conectar.php";
// Put your device token here (without spaces):
$sqlTD = @mysql_query("select token from notificaciones where estatus = 1");
$numberRows = mysql_num_rows($sqlTD);
if ($numberRows > 0) {
    while ($row = mysql_fetch_array($sqlTD)) {
        sendNotification($row[token], "HOLA ArMoving");
    }
}
//sendNotification("87D4477B81A7F8F7BA80B3F5F043D83DEC3C9B0940C708D24F803EF67600966F","HOLA ArMoving")
function sendNotification($tokenOrg, $messageOrg)
{
    $deviceToken = $tokenOrg;
    // Put your private key's passphrase here:
    $passphrase = 'pushchat';
    // Put your alert message here:
    $message = $messageOrg;
    ////////////////////////////////////////////////////////////////////////////////
    $ctx = stream_context_create();
    stream_context_set_option($ctx, 'ssl', 'local_cert', 'ck.pem');
    stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase);
    // Open a connection to the APNS server
    $fp = stream_socket_client('ssl://gateway.sandbox.push.apple.com:2195', $err, $errstr, 60, STREAM_CLIENT_CONNECT | STREAM_CLIENT_PERSISTENT, $ctx);
    if (!$fp) {
        exit("Failed to connect: {$err} {$errstr}" . PHP_EOL);
    }
    echo 'Connected to APNS' . PHP_EOL;
    // Create the payload body
    $body['aps'] = array('alert' => $message, 'sound' => 'default');
Exemplo n.º 20
0
 function challengeDecline()
 {
     global $sql;
     global $tp;
     global $time;
     global $pref;
     // Get info about the challenge
     $q = "SELECT DISTINCT " . TBL_CHALLENGES . ".*, " . TBL_USERS . ".*, " . TBL_EVENTS . ".*, " . TBL_GAMES . ".*" . " FROM " . TBL_CHALLENGES . ", " . TBL_USERS . ", " . TBL_EVENTS . ", " . TBL_GAMES . " WHERE (" . TBL_CHALLENGES . ".ChallengeID = '" . $this->fields['ChallengeID'] . "')" . " AND (" . TBL_USERS . ".user_id = " . TBL_CHALLENGES . ".ReportedBy)" . " AND (" . TBL_CHALLENGES . ".Event = " . TBL_EVENTS . ".EventID)" . " AND (" . TBL_EVENTS . ".Game = " . TBL_GAMES . ".GameID)";
     $result = $sql->db_Query($q);
     $numChallenges = mysql_numrows($result);
     if ($numChallenges > 0) {
         $cReportedBy = mysql_result($result, 0, TBL_USERS . ".user_id");
         $cReportedByNickName = mysql_result($result, 0, TBL_USERS . ".user_name");
         $cReportedByEmail = mysql_result($result, 0, TBL_USERS . ".user_email");
         $event_id = mysql_result($result, 0, TBL_EVENTS . ".EventID");
         $event = new Event($event_id);
         $subject = SITENAME . " " . EB_CHALLENGE_L29;
         $message = EB_CHALLENGE_L30 . $cReportedByNickName . EB_CHALLENGE_L31 . USERNAME . EB_CHALLENGE_L32 . $event->getField('Name') . EB_CHALLENGE_L33;
         $fromid = 0;
         $sendto = $cReportedBy;
         $sendtoemail = $cReportedByEmail;
         if (check_class($pref['eb_pm_notifications_class'])) {
             // Send PM
             sendNotification($sendto, $subject, $message, $fromid);
         }
         if (check_class($pref['eb_email_notifications_class'])) {
             // Send email
             require_once e_HANDLER . "mail.php";
             sendemail($sendtoemail, $subject, $message);
         }
     }
     $this->deleteChallenge();
 }
@set_include_path(implode(PATH_SEPARATOR, array(dirname(__FILE__) . "/../", dirname(__FILE__) . "/../core", dirname(__FILE__) . "/../core/includes", dirname(__FILE__) . "/../core/library", get_include_path())));
/**
 * Include the Entrada init code.
 */
require_once "init.inc.php";
/*
 * Fetch the unconfirmed observerships whose preceptors have not been notified. 
 */
$query = "\tSELECT *\n\t\t\tFROM `student_observerships` \n\t\t\tWHERE ((FROM_UNIXTIME(`start`) <= NOW() AND FROM_UNIXTIME(`end`) <= NOW()) OR (FROM_UNIXTIME(`start`) <= NOW() AND `end` IS NULL))\n\t\t\t\tAND (`notice_sent` = '0' OR `notice_sent` IS NULL OR DATEDIFF(NOW(), FROM_UNIXTIME(`notice_sent`)) >= '7')\n\t\t\t\tAND `status` = 'approved'\n\t\t\t\tAND (`reflection_id` IS NOT NULL AND `reflection_id` <> 0)";
$results = $db->GetAll($query);
if ($results) {
    foreach ($results as $result) {
        /*
         * Create the observership object, send the notification, and update it with the new time.
         */
        sendNotification($result);
    }
}
function sendNotification($result)
{
    global $AGENT_CONTACTS, $db;
    if ($result["preceptor_proxy_id"] != 0) {
        $query = "SELECT `prefix`, `firstname`, `lastname`, `email` FROM `" . AUTH_DATABASE . "`.`user_data` WHERE `id` = " . $db->qstr($result["preceptor_proxy_id"]);
        $preceptor = $db->GetRow($query);
        $preceptor_email = $preceptor["email"];
        $preceptor_name = (!empty($preceptor["prefix"]) ? $preceptor["prefix"] . " " : "") . $preceptor["firstname"] . " " . $preceptor["lastname"];
    } else {
        $preceptor_email = $result["preceptor_email"];
        $preceptor_name = $result["preceptor_firstname"] . " " . $result["preceptor_lastname"];
    }
    if ($preceptor_email) {
Exemplo n.º 22
0
 function addTicket($id)
 {
     error_log('addTicket\\n', 3, '/var/tmp/php.log');
     $request = Slim::getInstance()->request();
     $ticket = json_decode($request->getBody());
     //echo json_encode($ticket);
     try {
         $sql = "SELECT * FROM ticketstatus WHERE id = :id";
         $db = getConnection();
         $stmt = $db->prepare($sql);
         $stmt->bindParam("id", $ticket->ticketstatus->id);
         $stmt->execute();
         $ticketStatus = $stmt->fetch(PDO::FETCH_ASSOC);
         //echo json_encode($ticketStatus);
         $sql = "INSERT INTO ticket \n\t\t\t\t\t\t\t\t(id, subject, descrip, date, picture, user_id, floor_id, room_area,\n\t\t\t                    user_assigned_id, priority_id, ticketstatus_id, location_id, serviceType_id, date_assigned,\n\t\t\t                    date_respondby, date_due, date_complete, groups_id )\n\t\t\t\t\tVALUES \t\t(:id, :subject, :descrip, :date, :picture, :user_id, :floor_id, :room_area,\n\t\t\t                    :user_assigned_id, :priority_id, :ticketstatus_id, :location_id, :serviceType_id, :date_assigned,\n\t\t\t                    :date_respondby, :date_due, :date_complete, :groups_id )\n\t\t\t\t\tON DUPLICATE KEY UPDATE \n\t\t\t\t\t\t\t\tid=:id, subject=:subject, descrip=:descrip, date=:date, picture=:picture, \n\t\t\t\t\t            user_id=:user_id, floor_id=:floor_id, room_area=:room_area,\n\t\t\t                    user_assigned_id=:user_assigned_id, priority_id=:priority_id, ticketstatus_id=:ticketstatus_id\n\t\t\t                    location_id=:location_id, serviceType_id=:serviceType_id, date_assigned=:date_assigned,\n\t\t\t                    date_respondby=:date_respondby, date_due=:date_due, date_complete=:date_complete, \n\t\t\t                    groups_id=:groups_id";
         $stmt = $db->prepare($sql);
         $stmt->bindParam("id", $id);
         $stmt->bindParam("subject", $ticket->subject);
         $stmt->bindParam("descirp", $ticket->descirp);
         $stmt->bindParam("date", $ticket->date);
         $stmt->bindParam("picture", $ticket->picture);
         $stmt->bindParam("user_id", $ticket->user_id);
         $stmt->bindParam("floor_id", $ticket->floor_id);
         $stmt->bindParam("room_area", $ticket->room_area);
         $stmt->bindParam("user_assigned_id", $ticket->user_assigned_id);
         $stmt->bindParam("priority_id", $ticket->priority_id);
         $stmt->bindParam("ticketstatus_id", $ticket->ticketstatus->id);
         $stmt->bindParam("location_id", $ticket->location_id);
         $stmt->bindParam("serviceType_id", $ticket->serviceType_id);
         $stmt->bindParam("date_assigned", $ticket->date_assigned);
         $stmt->bindParam("date_respondby", $ticket->date_respondby);
         $stmt->bindParam("date_due", $ticket->date_due);
         $stmt->bindParam("date_complete", $ticket->date_complete);
         $stmt->bindParam("groups_id", $ticket->groups_id);
         $stmt->execute();
         $db = null;
         //echo "Finished INSERT";
         // send notifications
         // next, get the location name. We'll include it in the notification message.
         $sql = "SELECT name FROM location WHERE location_id=:id";
         $db = getConnection();
         $stmt = $db->prepare($sql);
         $stmt->bindParam("id", $ticket->location_id);
         $stmt->execute();
         $location = $stmt->fetch(PDO::FETCH_ASSOC);
         $db = null;
         //echo json_encode($location);
         // next, get a list of devices to notify
         $sql = "SELECT pushdevice.token, devicetype.name AS devicetype FROM profile \n\t\t\t\t\tINNER JOIN pushdevice ON pushdevice.profile_id=profile.id\n\t\t\t\t\tINNER JOIN devicetype ON pushdevice.devicetype_id=devicetype.id\n\t\t\t\t\tWHERE groups_id=:group AND location_id=:location";
         $db = getConnection();
         $stmt = $db->prepare($sql);
         $stmt->bindParam("group", $group['id']);
         $stmt->bindParam("location", $ticket->location_id);
         //error_log("QUERY: " . $stmt, 3, '/var/tmp/php.log');
         $stmt->execute();
         $devices = $stmt->fetchAll(PDO::FETCH_ASSOC);
         $db = null;
         //echo json_encode($devices);
         // finally, send push notification to each user.
         //$iospush = IOSPush::getInstance();
         //echo "**1**";
         foreach ($devices as $device) {
             error_log("PUSH TO :" . $e->getMessage() . "\n", 3, '/var/tmp/php.log');
             sendNotification($device['token'], "New Ticket for Location: " . $location['name'], 1);
         }
         echo json_encode($ticket);
     } catch (PDOException $e) {
         error_log("***** PDOException *****" . $e->getMessage() . "\n", 3, '/var/tmp/php.log');
         echo '{"error":{"text":' . $e->getMessage() . '}}';
     } catch (Exception $ex) {
         error_log("***** Exception *****" . $ex->getMessage() . "\n", 3, '/var/tmp/php.log');
         echo '{"error":{"text":' . $ex->getMessage() . '}}';
     }
 }
Exemplo n.º 23
0
/**
 *		CONTINIOUS TRACKING
 *		Tracking:
 *		- User status changes to track if a user is online/offline
 *		- User lastseen (privacy options)
 *		- User profile pictures (and changes)
 *     - User status message (and changes)
 */
function track()
{
    global $DBH, $wa, $tracking_ticks, $tracking_numbers, $whatsspyNotificatons, $crawl_time, $whatsappAuth, $pollCount, $lastseenCount, $statusMsgCount, $picCount, $request_error_queue, $continue_tracker_session;
    $crawl_time = time();
    setupWhatsappHandler();
    retrieveTrackingUsers();
    tracker_log('[init] Started tracking with phonenumber ' . $whatsappAuth['number']);
    if ($continue_tracker_session == false) {
        startTrackerHistory();
        sendNotification($DBH, null, $whatsspyNotificatons, 'tracker', ['title' => 'WhatsSpy Public has started tracking!', 'description' => 'tracker has started tracking ' . count($tracking_numbers) . ' users.', 'event-type' => 'start']);
    } else {
        $continue_tracker_session = false;
    }
    while (true) {
        $crawl_time = time();
        // Socket read
        $tick_start = microtime(true);
        $wa->pollMessage();
        $tick_end = microtime(true);
        tracker_log('[poll #' . $pollCount . '] Tracking ' . count($tracking_numbers) . ' users.       ' . "\r", true, false);
        //	1) LAST SEEN PRIVACY
        //
        // Check lastseen
        if ($pollCount % calculateTick($tracking_ticks['lastseen']) == 0) {
            tracker_log('[lastseen #' . $lastseenCount . '] Checking ' . count($tracking_numbers) . ' users.               ');
            foreach ($tracking_numbers as $number) {
                $wa->sendGetRequestLastSeen($number);
            }
            $lastseenCount++;
        }
        //	2) STATUS MESSAGE (and privacy)
        //
        // Check status message
        if ($pollCount % calculateTick($tracking_ticks['statusmsg']) == 0) {
            tracker_log('[status-msg #' . $statusMsgCount . '] Checking ' . count($tracking_numbers) . ' users.');
            if (count($tracking_numbers) > 0) {
                $wa->sendGetStatuses($tracking_numbers);
            }
            $statusMsgCount++;
        }
        //	3) PROFILE PICTURE (and privacy)
        //
        // Check profile picture
        if ($pollCount % calculateTick($tracking_ticks['profile-pic']) == 0) {
            tracker_log('[profile-pic #' . $picCount . '] Checking ' . count($tracking_numbers) . ' users.');
            foreach ($tracking_numbers as $number) {
                $wa->sendGetProfilePicture($number, true);
            }
            $picCount++;
        }
        //	4) DATABASE ACCOUNT REFRESH
        //
        // Check user database and refresh user set every hour but with a offset of 80 seconds.
        if ($pollCount % calculateTick($tracking_ticks['refresh-db']) == calculateTick($tracking_ticks['refresh-db'] - 80)) {
            retrieveTrackingUsers(true);
        }
        //  5) SOCKET RESET AND LOGIN
        //
        // Disconnect and reconnect with whatsapp to prevent dead tracker
        if ($pollCount % calculateTick($tracking_ticks['reset-socket']) == calculateTick($tracking_ticks['reset-socket'] - 40)) {
            resetSocket();
            retrieveTrackingUsers(false);
        }
        //	6) DATABASE ACCOUNT VERIFY CHECK
        //
        // Verify any freshly inserted accounts and check if there really whatsapp users.
        // Check everey 5 minutes.
        // When the user is verified the number is automaticly added to the tracker running DB.
        if ($pollCount % calculateTick($tracking_ticks['verify-check']) == 0) {
            verifyTrackingUsers();
        }
        //	7) WHATSAPP PING
        //
        // Keep connection alive (<300s)
        if ($pollCount % calculateTick($tracking_ticks['keep-alive']) == 0) {
            tracker_log('[keep-alive] Ping sent.' . "\r", true, false);
            $wa->sendPing();
        }
        // usage of 39512f5ea29c597f25483697471ac0b00cbb8088359c219e98fa8bdaf7e079fa
        $pollCount++;
        // Draw the socket read a draw
        if ($tick_end - $tick_start < 1.0) {
            sleep(1);
        }
    }
}
Exemplo n.º 24
0
    function brackets($scheduleNextMatches = false, $delete_match_id = 0, $style = '')
    {
        global $sql;
        global $time;
        global $pref;
        global $tp;
        global $gold_obj;
        $this->updateFields();
        $type = $this->fields['Type'];
        $competition_type = $this->getCompetitionType();
        $format = $this->fields['Format'];
        $event_id = $this->fields['EventID'];
        $teams = $this->getTeams();
        //var_dump($teams);
        $results = unserialize($this->getFieldHTML('Results'));
        $update_results = false;
        // TODO: check for error (return false)
        $rounds = unserialize($this->getFieldHTML('Rounds'));
        $matchups = $this->getMatchups();
        $nbrRounds = count($matchups);
        $nbrRows = 4 * count($matchups[1]);
        /* */
        $brackets = array();
        $content = array();
        // Initialize grid
        for ($row = 1; $row <= $nbrRows; $row++) {
            for ($column = 1; $column <= $nbrRounds; $column++) {
                $brackets[$row][2 * $column - 1] = '<td class="grid empty"></td>';
                $brackets[$row][2 * $column] = '<td class="grid border-none"></td>';
            }
        }
        $rowspan = 1;
        for ($round = 1; $round <= $nbrRounds; $round++) {
            $nbrMatchups = count($matchups[$round]);
            $rounds[$round]['nbrMatchups'] = 0;
            if ($round < $nbrRounds) {
                for ($matchup = 1; $matchup <= $nbrMatchups; $matchup++) {
                    if (!isset($results[$round][$matchup]['matchs'])) {
                        $results[$round][$matchup]['winner'] = 'not played';
                        $results[$round][$matchup]['bye'] = false;
                    }
                    if (!isset($results[$round][$matchup]['winner'])) {
                        $results[$round][$matchup]['winner'] = 'not played';
                    }
                    if (!isset($results[$round][$matchup]['bye'])) {
                        $results[$round][$matchup]['bye'] = false;
                    }
                    if (!isset($matchups[$round][$matchup]['deleted'])) {
                        $matchups[$round][$matchup]['deleted'] = false;
                    }
                    /* Nbr of matches in the matchup */
                    $nbr_matchs = count($results[$round][$matchup]['matchs']);
                    $matchup_deleted = false;
                    for ($match = 0; $match < 2; $match++) {
                        $matchupString = $matchups[$round][$matchup][$match];
                        $content[$round][$matchup][$match] = $matchupString == '' ? 'E' : $matchupString;
                        if ($matchupString == '') {
                            $row = findRow($round, $matchup, $match, $style);
                            $matchupsRows[$round][$matchup][$match] = $row;
                        } else {
                            if ($matchupString[0] == 'T') {
                                $row = findRow($round, $matchup, $match, $style);
                                $matchupsRows[$round][$matchup][$match] = $row;
                                $team = substr($matchupString, 1);
                                if (empty($teams[$team - 1])) {
                                    $content[$round][$matchup][$match] = 'E';
                                }
                            }
                            if ($matchupString[0] == 'W') {
                                $matchupArray = explode(',', substr($matchupString, 1));
                                $matchupRound = $matchupArray[0];
                                $matchupMatchup = $matchupArray[1];
                                // Get result of matchup
                                $winner = $results[$matchupRound][$matchupMatchup]['winner'];
                                $bye = $results[$matchupRound][$matchupMatchup]['bye'];
                                $deleted = $matchups[$matchupRound][$matchupMatchup]['deleted'];
                                $rowTop = $matchupsRows[$matchupRound][$matchupMatchup][0];
                                $rowBottom = $matchupsRows[$matchupRound][$matchupMatchup][1];
                                $row = ($rowBottom - $rowTop) / 2 + $rowTop;
                                // If result is not a bye, we draw the grid
                                if ($bye != true) {
                                    $brackets[$rowTop][2 * $round - 2] = '<td class="grid border-top"></td>';
                                    $brackets[$rowBottom][2 * $round - 2] = '<td class="grid border-bottom"></td>';
                                    for ($i = $rowTop + 1; $i < $rowBottom; $i++) {
                                        $brackets[$i][2 * $round - 2] = '<td class="grid border-vertical"></td>';
                                    }
                                    for ($i = $rowTop + 2; $i < $rowBottom; $i++) {
                                        $brackets[$i][2 * $round - 3] = '';
                                    }
                                    $brackets[$row][2 * $round - 2] = '<td class="grid border-middle"></td>';
                                }
                                $matchupsRows[$round][$matchup][$match] = $row;
                                if ($winner == 'top') {
                                    $content[$round][$matchup][$match] = $content[$matchupRound][$matchupMatchup][0];
                                } else {
                                    if ($winner == 'bottom') {
                                        $content[$round][$matchup][$match] = $content[$matchupRound][$matchupMatchup][1];
                                    } else {
                                        // Not played
                                        // Detect if match has been previously scheduled and needs to be deleted
                                        if ($nbr_matchs > 0) {
                                            $deleted = true;
                                        }
                                    }
                                }
                                if ($deleted == true) {
                                    $matchup_deleted = true;
                                }
                            }
                            if ($matchupString[0] == 'L' || $matchupString[0] == 'P') {
                                $matchupArray = explode(',', substr($matchupString, 1));
                                $matchupRound = $matchupArray[0];
                                $matchupMatchup = $matchupArray[1];
                                // Get result of matchup
                                $winner = $results[$matchupRound][$matchupMatchup]['winner'];
                                $bye = $results[$matchupRound][$matchupMatchup]['bye'];
                                $deleted = $matchups[$matchupRound][$matchupMatchup]['deleted'];
                                $row = findRow($round, $matchup, $match, $style);
                                $matchupsRows[$round][$matchup][$match] = $row;
                                if ($winner == 'top') {
                                    $loser = $content[$matchupRound][$matchupMatchup][1];
                                    if ($loser[0] == 'T') {
                                        $team = substr($loser, 1);
                                        //echo "M$round,$matchup: L2: $team,".$teams[$team-1]['loss'].'<br>';
                                        if ($teams[$team - 1]['loss'] > 1) {
                                            $content[$round][$matchup][$match] = 'N';
                                        } else {
                                            $content[$round][$matchup][$match] = $loser;
                                        }
                                    } else {
                                        $content[$round][$matchup][$match] = 'E';
                                    }
                                } else {
                                    if ($winner == 'bottom') {
                                        $loser = $content[$matchupRound][$matchupMatchup][0];
                                        if ($loser[0] == 'T') {
                                            $team = substr($loser, 1);
                                            //echo "M$round,$matchup: L2: $team,".$teams[$team-1]['loss'].'<br>';
                                            if ($teams[$team - 1]['loss'] > 1) {
                                                $content[$round][$matchup][$match] = 'N';
                                            } else {
                                                $content[$round][$matchup][$match] = $loser;
                                            }
                                        } else {
                                            $content[$round][$matchup][$match] = 'E';
                                        }
                                    } else {
                                        // Not played
                                        // Detect if match has been previously scheduled and needs to be deleted
                                        if ($nbr_matchs > 0) {
                                            $deleted = true;
                                        }
                                    }
                                }
                                if ($deleted == true) {
                                    $matchup_deleted = true;
                                }
                            }
                        }
                        switch ($content[$round][$matchup][$match]) {
                            case 'E':
                                $results[$round][$matchup]['winner'] = $match == 0 ? 'bottom' : 'top';
                                $results[$round][$matchup]['bye'] = true;
                                break;
                            case 'N':
                                $results[$round][$matchup]['winner'] = $match == 0 ? 'bottom' : 'top';
                                break;
                            case 'F':
                                $results[$round][$matchup]['winner'] = $match == 0 ? 'bottom' : 'top';
                                break;
                        }
                    }
                    // for(match)
                    /* Match deletion*/
                    if ($nbr_matchs > 0) {
                        $match_deleted = false;
                        for ($match = 0; $match < $nbr_matchs; $match++) {
                            if ($results[$round][$matchup]['matchs'][$match]['match_id'] == $delete_match_id || $match_deleted == true || $matchup_deleted == true) {
                                /*
                                var_dump($results[$round][$matchup]);
                                var_dump($delete_match_id);
                                var_dump($match_deleted);
                                var_dump($matchup_deleted);
                                */
                                $update_results = true;
                                $current_match_id = $results[$round][$matchup]['matchs'][$match]['match_id'];
                                echo "match " . $current_match_id . " deleted (M{$round},{$matchup},{$match})<br>";
                                $current_match = new Match($current_match_id);
                                $current_match->deleteMatchScores();
                                $results[$round][$matchup]['winner'] = 'not played';
                                $results[$round][$matchup]['topWins'] = 0;
                                $results[$round][$matchup]['bottomWins'] = 0;
                                $results[$round][$matchup]['winner'] = 'not played';
                                unset($results[$round][$matchup]['matchs'][$match]);
                                $match_deleted = true;
                                if ($this->getField('Status') == 'finished' && $competition_type == 'Tournament') {
                                    // if tournament was finished, we need to remove awards
                                    $this->setFieldDB('Status', 'active');
                                    // Find who got the award for winning the tournament
                                    switch ($type) {
                                        case "One Player Tournament":
                                            $q = "SELECT " . TBL_PLAYERS . ".*, " . TBL_GAMERS . ".*, " . TBL_EVENTS . ".*, " . TBL_AWARDS . ".*" . " FROM " . TBL_PLAYERS . ", " . TBL_GAMERS . ", " . TBL_EVENTS . ", " . TBL_AWARDS . " WHERE (" . TBL_PLAYERS . ".PlayerID = " . TBL_AWARDS . ".Player)" . "   AND (" . TBL_PLAYERS . ".Gamer = " . TBL_GAMERS . ".GamerID)" . "   AND (" . TBL_PLAYERS . ".Event = '{$event_id}')" . "   AND (" . TBL_AWARDS . ".Type = 'PlayerWonTournament')";
                                            $result = $sql->db_Query($q);
                                            $pid = mysql_result($result, 0, TBL_PLAYERS . ".PlayerID");
                                            $uid = mysql_result($result, 0, TBL_GAMERS . ".User");
                                            $aid = mysql_result($result, 0, TBL_AWARDS . ".AwardID");
                                            $q = "DELETE FROM " . TBL_AWARDS . " WHERE (" . TBL_AWARDS . ".AwardID = '{$aid}')";
                                            $result = $sql->db_Query($q);
                                            // gold
                                            if (is_gold_system_active() && $this->getField('GoldWinningEvent') > 0) {
                                                $gold_param['gold_user_id'] = $uid;
                                                $gold_param['gold_who_id'] = 0;
                                                $gold_param['gold_amount'] = $this->getField('GoldWinningEvent');
                                                $gold_param['gold_type'] = EB_L1;
                                                $gold_param['gold_action'] = "debit";
                                                $gold_param['gold_plugin'] = "ebattles";
                                                $gold_param['gold_log'] = EB_GOLD_L8 . ": event=" . $event_id . ", user="******"Clan Tournament":
                                            $q = "SELECT " . TBL_TEAMS . ".*, " . TBL_DIVISIONS . ".*, " . TBL_EVENTS . ".*, " . TBL_AWARDS . ".*" . " FROM " . TBL_TEAMS . ", " . TBL_DIVISIONS . ", " . TBL_EVENTS . ", " . TBL_AWARDS . " WHERE (" . TBL_TEAMS . ".TeamID = " . TBL_AWARDS . ".Team)" . "   AND (" . TBL_TEAMS . ".Division = " . TBL_DIVISIONS . ".DivisionID)" . "   AND (" . TBL_TEAMS . ".Event = '{$event_id}')" . "   AND (" . TBL_AWARDS . ".Type = 'TeamWonTournament')";
                                            $result = $sql->db_Query($q);
                                            $pid = mysql_result($result, 0, TBL_TEAMS . ".TeamID");
                                            $uid = mysql_result($result, 0, TBL_DIVISIONS . ".Captain");
                                            $aid = mysql_result($result, 0, TBL_AWARDS . ".AwardID");
                                            $q = "DELETE FROM " . TBL_AWARDS . " WHERE (" . TBL_AWARDS . ".AwardID = '{$aid}')";
                                            $result = $sql->db_Query($q);
                                            // gold
                                            if (is_gold_system_active() && $this->getField('GoldWinningEvent') > 0) {
                                                $gold_param['gold_user_id'] = $uid;
                                                $gold_param['gold_who_id'] = 0;
                                                $gold_param['gold_amount'] = $this->getField('GoldWinningEvent');
                                                $gold_param['gold_type'] = EB_L1;
                                                $gold_param['gold_action'] = "debit";
                                                $gold_param['gold_plugin'] = "ebattles";
                                                $gold_param['gold_log'] = EB_GOLD_L8 . ": event=" . $event_id . ", user="******"SELECT " . TBL_MATCHS . ".*, " . TBL_SCORES . ".*, " . TBL_PLAYERS . ".*, " . TBL_USERS . ".*" . " FROM " . TBL_MATCHS . ", " . TBL_SCORES . ", " . TBL_PLAYERS . ", " . TBL_GAMERS . ", " . TBL_USERS . " WHERE (" . TBL_MATCHS . ".MatchID = '{$current_match_id}')" . " AND (" . TBL_SCORES . ".MatchID = " . TBL_MATCHS . ".MatchID)" . " AND (" . TBL_PLAYERS . ".PlayerID = " . TBL_SCORES . ".Player)" . " AND (" . TBL_PLAYERS . ".Gamer = " . TBL_GAMERS . ".GamerID)" . " AND (" . TBL_USERS . ".user_id = " . TBL_GAMERS . ".User)" . " ORDER BY " . TBL_SCORES . ".Player_Rank, " . TBL_SCORES . ".Player_MatchTeam";
                                                break;
                                            case 'Teams':
                                                $q = "SELECT " . TBL_MATCHS . ".*, " . TBL_SCORES . ".*, " . TBL_CLANS . ".*, " . TBL_TEAMS . ".*, " . TBL_DIVISIONS . ".*" . " FROM " . TBL_MATCHS . ", " . TBL_SCORES . ", " . TBL_CLANS . ", " . TBL_TEAMS . ", " . TBL_DIVISIONS . " WHERE (" . TBL_MATCHS . ".MatchID = '{$current_match_id}')" . " AND (" . TBL_SCORES . ".MatchID = " . TBL_MATCHS . ".MatchID)" . " AND (" . TBL_TEAMS . ".TeamID = " . TBL_SCORES . ".Team)" . " AND (" . TBL_CLANS . ".ClanID = " . TBL_DIVISIONS . ".Clan)" . " AND (" . TBL_TEAMS . ".Division = " . TBL_DIVISIONS . ".DivisionID)" . " ORDER BY " . TBL_SCORES . ".Player_Rank, " . TBL_SCORES . ".Player_MatchTeam";
                                                break;
                                            default:
                                        }
                                        $result = $sql->db_Query($q);
                                        $numScores = mysql_numrows($result);
                                        if ($numScores > 0) {
                                            for ($i = 0; $i < $numScores; $i++) {
                                                switch ($this->getMatchPlayersType()) {
                                                    case 'Players':
                                                        $pid = mysql_result($result, $i, TBL_PLAYERS . ".PlayerID");
                                                        break;
                                                    case 'Teams':
                                                        $pid = mysql_result($result, $i, TBL_TEAMS . ".TeamID");
                                                        break;
                                                    default:
                                                }
                                                $pscoreid = mysql_result($result, $i, TBL_SCORES . ".ScoreID");
                                                $prank = mysql_result($result, $i, TBL_SCORES . ".Player_Rank");
                                                $pscore = mysql_result($result, $i, TBL_SCORES . ".Player_Score");
                                                $pMatchTeam = mysql_result($result, $i, TBL_SCORES . ".Player_MatchTeam");
                                                $teamTop = substr($content[$round][$matchup][0], 1);
                                                $teamBottom = substr($content[$round][$matchup][1], 1);
                                                $results[$round][$matchup]['matchs'][$match]['scores'][$i] = $pscore;
                                                if ($i == 0) {
                                                    $teamTopID = $teams[$teamTop - 1]['PlayerID'];
                                                    $teamBottomID = $teams[$teamBottom - 1]['PlayerID'];
                                                    if ($teamTopID == $pid) {
                                                        $current_match_winner = 'top';
                                                    } else {
                                                        $current_match_winner = 'bottom';
                                                    }
                                                    $results[$round][$matchup]['matchs'][$match]['winner'] = $current_match_winner;
                                                }
                                            }
                                        }
                                    }
                                }
                                // match not played
                                $matchupWinnerID = 0;
                                if ($current_match_winner == 'top') {
                                    $results[$round][$matchup]['topWins'] += 1;
                                    if ($results[$round][$matchup]['topWins'] == ($rounds[$round]['BestOf'] + 1) / 2) {
                                        $results[$round][$matchup]['winner'] = 'top';
                                        $matchupWinnerID = $teamTopID;
                                        //echo "Match $matchs, top won<br>";
                                    }
                                }
                                // winner==top
                                if ($current_match_winner == 'bottom') {
                                    $results[$round][$matchup]['bottomWins'] += 1;
                                    if ($results[$round][$matchup]['bottomWins'] == ($rounds[$round]['BestOf'] + 1) / 2) {
                                        $results[$round][$matchup]['winner'] = 'bottom';
                                        $matchupWinnerID = $teamBottomID;
                                        //echo "Match $matchs, bottom won<br>";
                                    }
                                }
                                // winner==bottom
                                if ($matchupWinnerID != 0) {
                                    if ($round == $nbrRounds - 1 && $competition_type == 'Tournament') {
                                        // player has won the tournament
                                        $this->setFieldDB('Status', 'finished');
                                        // Award: player wins tournament
                                        switch ($type) {
                                            case "One Player Tournament":
                                                $q_Award = "INSERT INTO " . TBL_AWARDS . "(Player,Type,timestamp)\r\n\t\t\t\t\t\t\t\t\t\t\tVALUES ({$matchupWinnerID},'PlayerWonTournament',{$time})";
                                                $result_Award = $sql->db_Query($q_Award);
                                                // gold
                                                if (is_gold_system_active() && $this->getField('GoldWinningEvent') > 0) {
                                                    // find player's user_id
                                                    $q = "SELECT " . TBL_PLAYERS . ".*, " . TBL_GAMERS . ".*" . " FROM " . TBL_PLAYERS . ", " . TBL_GAMERS . " WHERE (" . TBL_PLAYERS . ".PlayerID = '{$matchupWinnerID}')" . "   AND (" . TBL_PLAYERS . ".Gamer = " . TBL_GAMERS . ".GamerID)";
                                                    $result = $sql->db_Query($q);
                                                    $uid = mysql_result($result, 0, TBL_GAMERS . ".User");
                                                    $gold_param['gold_user_id'] = $uid;
                                                    $gold_param['gold_who_id'] = 0;
                                                    $gold_param['gold_amount'] = $this->getField('GoldWinningEvent');
                                                    $gold_param['gold_type'] = EB_L1;
                                                    $gold_param['gold_action'] = "credit";
                                                    $gold_param['gold_plugin'] = "ebattles";
                                                    $gold_param['gold_log'] = EB_GOLD_L8 . ": event=" . $event_id . ", user="******"Clan Tournament":
                                                $q_Award = "INSERT INTO " . TBL_AWARDS . "(Team,Type,timestamp)\r\n\t\t\t\t\t\t\t\t\t\t\tVALUES ({$matchupWinnerID},'TeamWonTournament',{$time})";
                                                $result_Award = $sql->db_Query($q_Award);
                                                // gold
                                                if (is_gold_system_active() && $this->getField('GoldWinningEvent') > 0) {
                                                    // find team captain
                                                    $q = "SELECT " . TBL_TEAMS . ".*, " . TBL_DIVISIONS . ".*" . " FROM " . TBL_TEAMS . ", " . TBL_DIVISIONS . " WHERE (" . TBL_TEAMS . ".TeamID = '{$matchupWinnerID}')" . "   AND (" . TBL_TEAMS . ".Division = " . TBL_DIVISIONS . ".DivisionID)";
                                                    $result = $sql->db_Query($q);
                                                    $uid = mysql_result($result, 0, TBL_DIVISIONS . ".Captain");
                                                    $gold_param['gold_user_id'] = $uid;
                                                    $gold_param['gold_who_id'] = 0;
                                                    $gold_param['gold_amount'] = $this->getField('GoldWinningEvent');
                                                    $gold_param['gold_type'] = EB_L1;
                                                    $gold_param['gold_action'] = "credit";
                                                    $gold_param['gold_plugin'] = "ebattles";
                                                    $gold_param['gold_log'] = EB_GOLD_L8 . ": event=" . $event_id . ", user="******"M$round,$matchup: L1: $team,".$teams[$team-1]['loss'].'<br>';
                            }
                        } else {
                            if ($results[$round][$matchup]['winner'] == 'bottom') {
                                $brackets[$matchupsRows[$round][$matchup][0]][2 * $round - 1] = html_bracket_team_cell($teams, $content[$round][$matchup][0], $topWins, 'loser');
                                $brackets[$matchupsRows[$round][$matchup][1]][2 * $round - 1] = html_bracket_team_cell($teams, $content[$round][$matchup][1], $bottomWins, 'winner');
                                $loser = $content[$round][$matchup][0];
                                if ($loser[0] == 'T') {
                                    $team = substr($loser, 1);
                                    $teams[$team - 1]['loss'] += 1;
                                    //echo "M$round,$matchup: L1: $team,".$teams[$team-1]['loss'].'<br>';
                                }
                            } else {
                                $brackets[$matchupsRows[$round][$matchup][0]][2 * $round - 1] = html_bracket_team_cell($teams, $content[$round][$matchup][0], $topWins);
                                $brackets[$matchupsRows[$round][$matchup][1]][2 * $round - 1] = html_bracket_team_cell($teams, $content[$round][$matchup][1], $bottomWins);
                            }
                        }
                        $matchup_string = '';
                        if ($nbr_matchs > 0) {
                            $tbl = array();
                            for ($match = 0; $match < $nbr_matchs; $match++) {
                                $match_id = $results[$round][$matchup]['matchs'][$match]['match_id'];
                                $match_winner = $results[$round][$matchup]['matchs'][$match]['winner'];
                                $score_0 = $results[$round][$matchup]['matchs'][$match]['scores'][0];
                                $score_1 = $results[$round][$matchup]['matchs'][$match]['scores'][1];
                                $score_0_str = '&nbsp;';
                                $score_1_str = '&nbsp;';
                                if ($this->getField('AllowScore') == TRUE) {
                                    if (isset($score_0)) {
                                        $score_0_str = $score_0;
                                    }
                                    if (isset($score_1)) {
                                        $score_1_str = $score_1;
                                    }
                                }
                                switch ($match_winner) {
                                    case 'top':
                                        $class_str = 'match-winner';
                                        $score_str = $score_0_str;
                                        $match_link_str = '<a href="' . e_PLUGIN . 'ebattles/matchinfo.php?matchid=' . $match_id . '"><div class="' . $class_str . '" title="' . EB_MATCH_L1 . ' ' . ($match + 1) . '">' . $score_str . '</div></a>';
                                        $tbl[$match][0] = '<td>' . $match_link_str . '</td>';
                                        $class_str = 'match-loser';
                                        $score_str = $score_1_str;
                                        $match_link_str = '<a href="' . e_PLUGIN . 'ebattles/matchinfo.php?matchid=' . $match_id . '"><div class="' . $class_str . '" title="' . EB_MATCH_L1 . ' ' . ($match + 1) . '">' . $score_str . '</div></a>';
                                        $tbl[$match][1] = '<td>' . $match_link_str . '</td>';
                                        break;
                                    case 'bottom':
                                        $class_str = 'match-loser';
                                        $score_str = $score_1_str;
                                        $match_link_str = '<a href="' . e_PLUGIN . 'ebattles/matchinfo.php?matchid=' . $match_id . '"><div class="' . $class_str . '" title="' . EB_MATCH_L1 . ' ' . ($match + 1) . '">' . $score_str . '</div></a>';
                                        $tbl[$match][0] = '<td>' . $match_link_str . '</td>';
                                        $class_str = 'match-winner';
                                        $score_str = $score_0_str;
                                        $match_link_str = '<a href="' . e_PLUGIN . 'ebattles/matchinfo.php?matchid=' . $match_id . '"><div class="' . $class_str . '" title="' . EB_MATCH_L1 . ' ' . ($match + 1) . '">' . $score_str . '</div></a>';
                                        $tbl[$match][1] = '<td>' . $match_link_str . '</td>';
                                        break;
                                    default:
                                        $class_str = 'match-not-played';
                                        $matchObj = new Match($match_id);
                                        $permissions = $matchObj->get_permissions(USERID);
                                        $userclass = $permissions['userclass'];
                                        $can_report = $permissions['can_report'];
                                        $can_approve = $permissions['can_approve'];
                                        $can_delete = $permissions['can_delete'];
                                        $can_edit = $permissions['can_edit'];
                                        $match_link_str = '';
                                        $tbl[$match][0] = '';
                                        if ($can_approve == 1) {
                                            $match_link_str = ' <a href="' . e_PLUGIN . 'ebattles/matchinfo.php?matchid=' . $match_id . '"><img class="eb_image" src="' . e_PLUGIN . 'ebattles/images/exclamation.png" alt="' . EB_MATCH_L13 . '" title="' . EB_MATCH_L13 . '"/></a>';
                                            $tbl[$match][0] .= '<td rowspan="2" class="' . $class_str . '"><div class="' . $class_str . '" title="' . EB_MATCH_L1 . ' ' . ($match + 1) . '">' . $match_link_str . '</div></td>';
                                        }
                                        /*
                                        if($can_edit == 1)
                                        {
                                        	if($matchObj->getField('Status') == 'scheduled')
                                        	{
                                        		$match_link_str = ebImageLink('matchschedulededit', EB_MATCHR_L46, '', e_PLUGIN.'ebattles/matchreport.php?eventid='.$event_id.'&amp;matchid='.$match_id.'&amp;actionid=matchschedulededit&amp;userclass='.$userclass, 'page_white_edit.png', '', 'matchreport_link', '', EB_MATCHR_L46.' '.($match+1));
                                        		$tbl[$match][0] .= '<td rowspan="2" class="'.$class_str.'"><div class="'.$class_str.'">'.$match_link_str.'</div></td>';
                                        	}
                                        	else
                                        	{
                                        		$match_link_str = ebImageLink('matchedit', EB_MATCHR_L46, '', e_PLUGIN.'ebattles/matchreport.php?eventid='.$event_id.'&amp;matchid='.$match_id.'&amp;actionid=matchedit&amp;userclass='.$userclass, 'page_white_edit.png', '', 'matchreport_link', '', EB_MATCHR_L46.' '.($match+1));
                                        		$tbl[$match][0] .= '<td rowspan="2" class="'.$class_str.'"><div class="'.$class_str.'">'.$match_link_str.'</div></td>';
                                        	}		
                                        }
                                        */
                                        if ($can_report == 1) {
                                            $match_link_str = ebImageLink('matchscheduledreport', EB_MATCHR_L32, '', e_PLUGIN . 'ebattles/matchreport.php?eventid=' . $event_id . '&amp;matchid=' . $match_id . '&amp;actionid=matchscheduledreport&amp;userclass=' . $userclass, 'report.png', '', 'matchreport_link', '', EB_MATCHR_L32 . ' ' . ($match + 1));
                                            $tbl[$match][0] .= '<td rowspan="2" class="' . $class_str . '"><div class="' . $class_str . '" title="' . EB_MATCH_L1 . ' ' . ($match + 1) . '">' . $match_link_str . '</div></td>';
                                        }
                                        $tbl[$match][1] = '';
                                        break;
                                }
                            }
                            $matchup_string = '<table class="brackets-matchup"><tbody>';
                            $matchup_string .= '<tr>';
                            for ($match = 0; $match < $nbr_matchs; $match++) {
                                $matchup_string .= $tbl[$match][0];
                            }
                            $matchup_string .= '</tr>';
                            $matchup_string .= '<tr>';
                            for ($match = 0; $match < $nbr_matchs; $match++) {
                                $matchup_string .= $tbl[$match][1];
                            }
                            $matchup_string .= '</tr>';
                            $matchup_string .= '</tbody></table>';
                            //echo $tbl_str;
                        }
                        switch ($style) {
                            case 'elimination':
                                $brackets[$matchupsRows[$round][$matchup][0] + 1][2 * $round - 1] = '<td rowspan="' . $rowspan . '" class="match-details" title="' . EB_EVENT_L102 . ' ' . $round . ',' . $matchup . '">
							' . $matchup_string . '
							</td>';
                                break;
                            case 'round-robin':
                                $brackets[$matchupsRows[$round][$matchup][1] + 1][2 * $round - 1] = '<td rowspan="1" class="match-details" title="' . EB_EVENT_L102 . ' ' . $round . ',' . $matchup . '">
							' . $matchup_string . '
							</td>';
                                break;
                        }
                        $rounds[$round]['nbrMatchups']++;
                    }
                    // if(content!='E')
                    if ($scheduleNextMatches == true && $content[$round][$matchup][0][0] == 'T' && $content[$round][$matchup][1][0] == 'T' && $results[$round][$matchup]['winner'] == 'not played') {
                        $update_results = true;
                        $current_match = $results[$round][$matchup]['matchs'][$nbr_matchs - 1];
                        //var_dump($current_match);
                        if (!isset($current_match) || $current_match['winner'] != 'not played') {
                            /*
                            echo 'M'.$round.','.$matchup.':<br>';
                            var_dump($results[$round][$matchup]);
                            var_dump($content[$round][$matchup]);
                            */
                            // Need to schedule the next match
                            // Create Match ------------------------------------------
                            $reported_by = $this->getField('Owner');
                            $time_reported = $time;
                            $comments = '';
                            $time_scheduled = $time_reported;
                            $q = "INSERT INTO " . TBL_MATCHS . "(Event,ReportedBy,TimeReported, Comments, Status, TimeScheduled)\r\n\t\t\t\t\t\t\tVALUES ({$event_id},'{$reported_by}', {$time_reported}, '{$comments}', 'scheduled', {$time_scheduled})";
                            $result = $sql->db_Query($q);
                            $last_id = mysql_insert_id();
                            $match_id = $last_id;
                            // Create Scores ------------------------------------------
                            $teamTop = substr($content[$round][$matchup][0], 1);
                            $teamBottom = substr($content[$round][$matchup][1], 1);
                            switch ($this->getMatchPlayersType()) {
                                case 'Players':
                                    $playerTopID = $teams[$teamTop - 1]['PlayerID'];
                                    $playerBottomID = $teams[$teamBottom - 1]['PlayerID'];
                                    $teamTopID = 0;
                                    $teamBottomID = 0;
                                    break;
                                case 'Teams':
                                    $playerTopID = 0;
                                    $playerBottomID = 0;
                                    $teamTopID = $teams[$teamTop - 1]['PlayerID'];
                                    $teamBottomID = $teams[$teamBottom - 1]['PlayerID'];
                                    break;
                            }
                            $q = "INSERT INTO " . TBL_SCORES . "(MatchID,Player,Team,Player_MatchTeam,Player_Rank)\r\n\t\t\t\t\t\t\tVALUES ({$match_id},{$playerTopID},{$teamTopID},1,1)\r\n\t\t\t\t\t\t\t";
                            $result = $sql->db_Query($q);
                            $q = "INSERT INTO " . TBL_SCORES . "(MatchID,Player,Team,Player_MatchTeam,Player_Rank)\r\n\t\t\t\t\t\t\tVALUES ({$match_id},{$playerBottomID},{$teamBottomID},2,2)\r\n\t\t\t\t\t\t\t";
                            $result = $sql->db_Query($q);
                            $match_array = array();
                            $match_array['winner'] = 'not played';
                            $match_array['match_id'] = $match_id;
                            $results[$round][$matchup]['matchs'][$nbr_matchs] = $match_array;
                            if ($nbr_matchs == 0) {
                                // Send notification to all the players.
                                $fromid = 0;
                                $subject = SITENAME . " " . EB_MATCHR_L52;
                                switch ($this->getMatchPlayersType()) {
                                    case 'Players':
                                        $q_Players = "SELECT DISTINCT " . TBL_USERS . ".*" . " FROM " . TBL_MATCHS . ", " . TBL_SCORES . ", " . TBL_PLAYERS . ", " . TBL_GAMERS . ", " . TBL_USERS . " WHERE (" . TBL_MATCHS . ".MatchID = '{$match_id}')" . " AND (" . TBL_SCORES . ".MatchID = " . TBL_MATCHS . ".MatchID)" . " AND (" . TBL_PLAYERS . ".PlayerID = " . TBL_SCORES . ".Player)" . " AND (" . TBL_PLAYERS . ".Gamer = " . TBL_GAMERS . ".GamerID)" . " AND (" . TBL_GAMERS . ".User = "******".user_id)";
                                        $result_Players = $sql->db_Query($q_Players);
                                        $numPlayers = mysql_numrows($result_Players);
                                        break;
                                    case 'Teams':
                                        $q_Players = "SELECT DISTINCT " . TBL_USERS . ".*" . " FROM " . TBL_MATCHS . ", " . TBL_SCORES . ", " . TBL_TEAMS . ", " . TBL_PLAYERS . ", " . TBL_GAMERS . ", " . TBL_USERS . " WHERE (" . TBL_MATCHS . ".MatchID = '{$match_id}')" . " AND (" . TBL_SCORES . ".MatchID = " . TBL_MATCHS . ".MatchID)" . " AND (" . TBL_TEAMS . ".TeamID = " . TBL_SCORES . ".Team)" . " AND (" . TBL_PLAYERS . ".Team = " . TBL_TEAMS . ".TeamID)" . " AND (" . TBL_PLAYERS . ".Gamer = " . TBL_GAMERS . ".GamerID)" . " AND (" . TBL_GAMERS . ".User = "******".user_id)";
                                        $result_Players = $sql->db_Query($q_Players);
                                        $numPlayers = mysql_numrows($result_Players);
                                        break;
                                    default:
                                }
                                if ($numPlayers > 0) {
                                    for ($j = 0; $j < $numPlayers; $j++) {
                                        $pname = mysql_result($result_Players, $j, TBL_USERS . ".user_name");
                                        $pemail = mysql_result($result_Players, $j, TBL_USERS . ".user_email");
                                        $message = EB_MATCHR_L53 . $pname . EB_MATCHR_L54 . EB_MATCHR_L55 . $this->getField('Name') . EB_MATCHR_L56;
                                        $sendto = mysql_result($result_Players, $j, TBL_USERS . ".user_id");
                                        $sendtoemail = mysql_result($result_Players, $j, TBL_USERS . ".user_email");
                                        if (check_class($pref['eb_pm_notifications_class'])) {
                                            // Send PM
                                            sendNotification($sendto, $subject, $message, $fromid);
                                        }
                                        if (check_class($pref['eb_email_notifications_class'])) {
                                            // Send email
                                            require_once e_HANDLER . "mail.php";
                                            sendemail($sendtoemail, $subject, $message);
                                        }
                                    }
                                }
                            }
                            // if(nbr_matchs==0)
                        }
                        // create match
                    }
                    // schedule next match
                    /*
                    echo 'M'.$round.','.$matchup.':<br>';
                    var_dump($results[$round][$matchup]);
                    var_dump($content[$round][$matchup]);
                    echo '- matchup: top='.$matchups[$round][$matchup][0].', bottom='.$matchups[$round][$matchup][1].'<br>';
                    echo '- content: top='.$content[$round][$matchup][0].', bottom='.$content[$round][$matchup][1].'<br>';
                    echo '- winner='.$results[$round][$matchup]['winner'].', bye='.$results[$round][$matchup]['bye'].'<br>';
                    */
                }
                // for(matchup)
            } else {
                /* Last round, no match */
                for ($matchup = 1; $matchup <= $nbrMatchups; $matchup++) {
                    if (!isset($results[$round][$matchup]['winner'])) {
                        $results[$round][$matchup]['winner'] = '';
                    }
                    if (!isset($results[$round][$matchup]['bye'])) {
                        $results[$round][$matchup]['bye'] = false;
                    }
                    $match = 0;
                    $matchupString = $matchups[$round][$matchup][$match];
                    $content[$round][$matchup][$match] = $matchupString == '' ? 'E' : $matchupString;
                    if ($matchupString[$match] = 'W') {
                        $matchupArray = explode(',', substr($matchupString, 1));
                        $matchupRound = $matchupArray[0];
                        $matchupMatchup = $matchupArray[1];
                        $winner = $results[$matchupRound][$matchupMatchup]['winner'];
                        $bye = $results[$matchupRound][$matchupMatchup]['bye'];
                        $rowTop = $matchupsRows[$matchupRound][$matchupMatchup][0];
                        $rowBottom = $matchupsRows[$matchupRound][$matchupMatchup][1];
                        $row = ($rowBottom - $rowTop) / 2 + $rowTop;
                        if ($bye != true) {
                            $brackets[$rowTop][2 * $round - 2] = '<td class="grid border-top"></td>';
                            $brackets[$rowBottom][2 * $round - 2] = '<td class="grid border-bottom"></td>';
                            for ($i = $rowTop + 1; $i < $rowBottom; $i++) {
                                $brackets[$i][2 * $round - 2] = '<td class="grid border-vertical"></td>';
                            }
                            for ($i = $rowTop + 2; $i < $rowBottom; $i++) {
                                $brackets[$i][2 * $round - 3] = '';
                            }
                            $brackets[$row][2 * $round - 2] = '<td class="grid border-middle"></td>';
                        }
                        $matchupsRows[$round][$matchup][$match] = $rowTop;
                        if ($winner == 'top') {
                            $content[$round][$matchup][$match] = $content[$matchupRound][$matchupMatchup][0];
                        } else {
                            if ($winner == 'bottom') {
                                $content[$round][$matchup][$match] = $content[$matchupRound][$matchupMatchup][1];
                            }
                        }
                        $topWins = $results[$round][$matchup]['topWins'];
                        $bottomWins = $results[$round][$matchup]['bottomWins'];
                        if ($topWins > $bottomWins) {
                            $topWins .= '+';
                            $bottomWins .= '-';
                        }
                        if ($topWins < $bottomWins) {
                            $topWins .= '-';
                            $bottomWins .= '+';
                        }
                        if ($content[$round][$matchup][0][0] != 'E') {
                            $brackets[$row][2 * $round - 1] = html_bracket_team_cell($teams, $content[$round][$matchup][$match], $topWins, 'victor');
                        } else {
                            $brackets[$row][2 * $round - 1] = html_bracket_team_cell($teams, $content[$round][$matchup][$match], $bottomWins);
                        }
                    }
                }
                // for(matchup)
            }
            $rowspan = 2 * $rowspan + 1;
        }
        $bracket_html = '<div id="panel_brackets">';
        $bracket_html .= '<div id="brackets_frame" style="height: 400px;">';
        $bracket_html .= '<div id="brackets">';
        $bracket_html .= '<table class="brackets">';
        $bracket_html .= '<thead><tr>';
        for ($i = 1; $i < $nbrRounds; $i++) {
            if ($rounds[$i]['nbrMatchups'] != 0) {
                $bracket_html .= '<th colspan="2" title="' . EB_EVENTM_L146 . ' ' . $rounds[$i]['BestOf'] . '">';
                $bracket_html .= $rounds[$i]['Title'] . '<br />';
                $bracket_html .= '<div class="smalltext">' . EB_EVENTM_L146 . ' ' . $rounds[$i]['BestOf'] . '</div>';
                $bracket_html .= '</th>';
            } else {
                $bracket_html .= '<th colspan="2"></th>';
            }
        }
        $bracket_html .= '</tr></thead>';
        $bracket_html .= '<tbody>';
        for ($row = 1; $row <= $nbrRows; $row++) {
            $bracket_html .= '<tr>';
            for ($column = 1; $column <= 2 * $nbrRounds; $column++) {
                $bracket_html .= $brackets[$row][$column];
            }
            $bracket_html .= '</tr>';
        }
        $bracket_html .= '</tbody>';
        $bracket_html .= '</table>';
        $bracket_html .= '</div>';
        // brackets
        $bracket_html .= '</div>';
        // brackets_frame
        $bracket_html .= '<div class="clearer"></div>';
        $bracket_html .= '</div>';
        // panel-brackets
        /*
        echo "rounds:<br>";
        var_dump($rounds);
        echo "matchups:<br>";
        var_dump($matchups);
        echo "results:<br>";
        var_dump($results);
        echo "content:<br>";
        var_dump($content);
        echo "teams:<br>";
        var_dump($teams);
        */
        if ($update_results == true) {
            $this->updateResults($results);
            $this->updateFieldDB('Results');
        }
        return array($bracket_html);
    }
 public function setMessagedeail($data)
 {
     $uid = $data['user'];
     $adid = $data['adid'];
     $userto = $data['userto'];
     $message = $data['message'];
     if (isset($uid) && isset($adid) && isset($userto) && isset($message)) {
         if ($uid != '' && $adid != '' && $userto != '' && $message != '') {
             if (trim($message) != '') {
                 $data = array('clad_id' => trim($adid), 'ad_msg_from' => $uid, 'ad_msg_to' => trim($userto), 'ad_message' => trim($message), 'ad_msg_read_flag' => 0);
                 $ret = $this->common_model->insertData(MESSAGE, $data);
                 $messages['user'] = $uid;
                 $messages['userto'] = $userto;
                 /*** User notification ***/
                 $macids = array();
                 $macid = $this->common_model->getMacids($userto);
                 foreach ($macid as $val) {
                     $macids[] = $val->macid;
                 }
                 ## get ad title
                 $resTitle = $this->common_model->selectData(CLASSIFIEDAD, 'clad_title', array("clad_id" => $adid));
                 $pushMsg = "You have new message on Ad " . $resTitle[0]->clad_title . " - " . trim($message);
                 $msg = array('message' => $pushMsg, 'title' => 'Gujjubazar', 'subtitle' => 'No. 1 Classified site', 'type' => 'message', 'msgcnt' => 3, 'vibrate' => 1, 'sound' => 1);
                 if (count($macids) != 0) {
                     sendNotification($macids, $msg);
                 }
                 $this->manageCache($adid);
                 $result['status'] = "200";
                 $result['message'] = "Request successfuly completed";
                 $result['data'] = $messages;
             } else {
                 $result['status'] = "200";
                 $result['message'] = "Messagefield is blank";
                 $result['data'] = $messages;
             }
         } else {
             $result['status'] = "204";
             $result['message'] = "Please enter valid data";
             $result['data'] = array();
         }
     } else {
         $result['status'] = "204";
         $result['message'] = "Please enter valid data";
         $result['data'] = array();
     }
     return $result;
 }
Exemplo n.º 26
0
        if (($youAre = checkYouAre($messageItem->message)) != false) {
            $translated = 'No, you ' . $youAre . '! ' . randomTacoReference();
            sendNotification($roomId, $yoda, $userName, $translated, "green");
            exit;
        }
        /*if (preg_match('/' . $myself . '/', $messageItem->message) != false) {
              sleep(5);
              sendNotification($roomId, $yoda, $userName, '@' . $messageItem->from->mention_name, "gray", true);
              exit;
          }*/
        break;
    case "room_enter":
        $fromRoomId = $result->item->room->id;
        if ($fromRoomId == $roomId) {
            $userName = $result->item->sender->name;
            sendNotification($roomId, $yoda, $userName, 'Welcome apprentice <b>' . $userName . '</b>! The <b>' . getPawel() . '</b>...', "green");
            //<br>Besides the Yoda Monastery, you should also have access to a private audience with Master Yoda.<br>This private room allows you to execute commands for which the result will only show in Yoda Monastery.', "green");
            generatePrivateAudiences($roomId, $myToken);
        }
        break;
}
function dump($data)
{
    ob_start();
    var_dump($data);
    return '<pre>' . ob_get_clean();
}
function sendNotification($roomId, $token, $userName, $message, $color = "gray", $identify = false, $private = false)
{
    if (!is_null($userName) && $private) {
        $privateBotsList = json_decode(file_get_contents('private_audience_bots.txt'), true);
Exemplo n.º 27
0
function testNotification()
{
    error_log('\\ntest notification\\n', 3, '/var/tmp/php.log');
    sendNotification(49, 'abcd');
}
Exemplo n.º 28
0
$gifs = json_decode(file_get_contents($url));
$gifs = array_merge($gifs, $custom_gifs);
$gif = $gifs[array_rand($gifs)];
// get currency sign to use (right now, just USD and INR supported. More to follow? **cough**pullrequest**cough**)
$dollar_sign = $event_json->data->object->currency == 'inr' ? '&#x20b9;' : '$';
$amount = $dollar_sign . number_format($event_json->data->object->amount / 100, 2);
// send the notification to our chat room
// hipchat
if ($hipchat['auth_token']) {
    $url = sprintf('https://api.hipchat.com/v2/room/%s/notification?auth_token=%s', $hipchat['room_id'], $hipchat['auth_token']);
    $data = array('message' => sprintf('%s <br><img src="%s">', $amount, $gif), 'color' => 'green', 'notify' => true);
    sendNotification($url, $data);
}
// slack
if ($slack['webhook_url']) {
    $data = array('text' => sprintf('%s - <%s>', $amount, $gif), 'username' => 'Just got paid', 'icon_emoji' => ':heavy_dollar_sign:', 'unfurl_links' => true);
    sendNotification($slack['webhook_url'], $data);
}
function sendNotification($url, $data)
{
    $data_string = json_encode($data);
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Content-Length: ' . strlen($data_string)));
    // send the request and close the handle
    $body = curl_exec($ch);
    curl_close($ch);
}
Exemplo n.º 29
0
/**
* Saves a story submission
*
* @param    array   $A  Data for that submission
* @return   string      HTML redirect
*
*/
function savestory($A)
{
    global $_CONF, $_TABLES, $_USER;
    $retval = '';
    $story = new Story();
    $story->loadSubmission();
    // pseudo-formatted story text for the spam check
    $result = PLG_checkforSpam($story->GetSpamCheckFormat(), $_CONF['spamx']);
    if ($result > 0) {
        COM_updateSpeedlimit('submit');
        COM_displayMessageAndAbort($result, 'spamx', 403, 'Forbidden');
    }
    COM_updateSpeedlimit('submit');
    $result = $story->saveSubmission();
    if ($result == STORY_NO_ACCESS_TOPIC) {
        // user doesn't have access to this topic - bail
        $retval = COM_refresh($_CONF['site_url'] . '/index.php');
    } elseif ($result == STORY_SAVED || $result == STORY_SAVED_SUBMISSION) {
        if (isset($_CONF['notification']) && in_array('story', $_CONF['notification'])) {
            sendNotification($_TABLES['storysubmission'], $story);
        }
        if ($result == STORY_SAVED) {
            $retval = COM_refresh(COM_buildUrl($_CONF['site_url'] . '/article.php?story=' . $story->getSid()));
        } else {
            $retval = COM_refresh($_CONF['site_url'] . '/index.php?msg=2');
        }
    }
    return $retval;
}
Exemplo n.º 30
-1
        print "\nError has occurred";
    }
}
function setNotification($message, $user_id)
{
    try {
        $dbh = new PDO('mysql:host=mysql488.db.sakura.ne.jp;dbname=meganeshibu_db;charset=utf8', 'meganeshibu', 'DBmaster777', array(PDO::ATTR_EMULATE_PREPARES => false));
    } catch (PDOException $e) {
        exit('データベース接続失敗。' . $e->getMessage());
    }
    $registTime = new DateTime();
    $sql = "insert into NotificationTable(UserID, NotificationInfo, RegistTime) values('" . $user_id . "',' " . $message . "',' " . $registTime->format('Y-m-d H:i:s') . "')";
    $stmt = $dbh->query($sql);
    $dbh = null;
}
$notificationList = checkNotification('', '+1 hour');
foreach ($notificationList as $notification) {
    $regId = $notification['notificationID'];
    if ($notification['type'] == 'スケジュール') {
        $ref = '開始';
    } else {
        if ($notification['type'] == 'タスク') {
            $ref = '終了';
        }
    }
    $message = $notification['type'] . '「' . $notification['name'] . '」の' . $ref . '1時間前です';
    if ($regId) {
        sendNotification($message, $regId);
    }
    setNotification($message, $notification['user_id']);
}