Example #1
0
 /**
  * Get list of messages
  */
 public static function getPage($page = 0)
 {
     $app = \Slim\Slim::getInstance();
     $app->expires(time());
     $userDAO = new UserDAO();
     $groupDAO = new GroupDAO();
     $groupsQuery = array();
     if (!$userDAO->hasRole('ADMIN')) {
         $strong = \Strong\Strong::getInstance();
         $user = $strong->getUser();
         $groupsQuery['user_id'] = $user['id'];
     }
     $groups = $groupDAO->getList($groupsQuery);
     if (0 == $groups['total']) {
         return $app->redirect(MAINURL . '/groups');
     }
     $chatDAO = new ChatDAO();
     $query = $_GET;
     $query['from'] = preg_replace('![^0-9]*!', '', $query['search']);
     if (!$userDAO->hasRole('ADMIN')) {
         $strong = \Strong\Strong::getInstance();
         $user = $strong->getUser();
         $query['user_id'] = $user['id'];
     }
     $pager = new Pager(MAINURL . '/inbox/', 25);
     $pager->setPage($page);
     $query = $pager->getQueryArray($query);
     $list = $chatDAO->getList($query);
     $pager->setCount(count($list['list']));
     if (isset($list['total'])) {
         $pager->setTotal($list['total']);
     }
     $app->view->set('menu', 'inbox');
     $app->view->set('query', $query);
     $app->view->set('result', $list);
     $app->view->set('pager', $pager);
     $app->render('inbox/list.twig.html');
 }
Example #2
0
<?php

require_once __DIR__ . '/../vendor/autoload.php';
define("MAINDIR", __DIR__ . '/../');
require_once __DIR__ . '/../config.php';
use GitGis\Whatsapp\Model\Message;
use GitGis\Whatsapp\Model\MessageDAO;
use GitGis\Whatsapp\Model\Group;
use GitGis\Whatsapp\Model\GroupDAO;
use GitGis\Whatsapp\Model\WhatsappDAO;
$groupDao = new GroupDAO();
$group = $groupDao->fetch(1);
$messageDao = new MessageDAO();
for ($cnt = 0; $cnt < 200; $cnt++) {
    $message = new Message();
    $message->setKind(Message::KIND_TEXT_MSG);
    $message->setCtime(time());
    $message->setUserId(1);
    $message->setData('Test ' . $cnt);
    $message->setStime(time());
    $message->setGroupId($group->getId());
    $message = $messageDao->save($message);
    $messageDao->addStatus($message, Message::MESSAGE_STATUS_TO_SEND);
}
Example #3
0
 /**
  * Deletes group
  */
 public static function postDeletePage($id)
 {
     $app = \Slim\Slim::getInstance();
     $userDAO = new UserDAO();
     if (!$userDAO->hasRole('ADMIN')) {
         return $app->status(403);
     }
     if (!empty($_POST['yes'])) {
         $dao = new GroupDAO();
         $dao->delete($id);
     }
     return $app->redirect(MAINURL . '/groups');
 }
Example #4
0
    /**
     * Saves message to DB
     * 
     * @param Message $item
     * @throws \Exception
     * @return Message
     */
    public function save(Message $item)
    {
        if (empty($item)) {
            throw new \Exception('Empty item');
        }
        $groupDao = new GroupDAO();
        $item->setTarget(implode(',', array_keys($groupDao->getNumbers($item->getGroupId()))));
        // 		if (!$item->getTarget()) $item->setTarget('');
        if (!$item->getData()) {
            $item->setData('');
        }
        if (!$item->getStime()) {
            $item->setStime(0);
        }
        $db = DBConnection::getInstance();
        if ($item->getId() == 0) {
            $query = $db->prepare("INSERT INTO messages\n\t\t\t\t\t(group_id, sender_id, user_id, kind, target, data, ctime, stime)\n\t\t\t\t\tVALUES\n\t\t\t\t\t(:group_id, :sender_id, :user_id, :kind, :target, :data, :ctime, :stime)");
            $query->bindParam('group_id', $item->getGroupId());
            $query->bindParam('sender_id', $item->getSenderId());
            $query->bindParam('user_id', $item->getUserId());
            $query->bindParam('kind', $item->getKind());
            $query->bindParam('target', $item->getTarget());
            $query->bindParam('data', $item->getData());
            $query->bindParam('ctime', time());
            $query->bindParam('stime', $item->getStime());
            $query->execute();
            $item->setId($db->lastInsertId());
        } else {
            $sql = ' UPDATE messages SET
                group_id = :group_id,
                sender_id = :sender_id,
                user_id = :user_id,
                kind = :kind,
			    target = :target,
                data = :data,
			    stime = :stime
                WHERE id = :id ';
            $query = $db->prepare($sql);
            $query->bindParam('id', $item->getId(), \PDO::PARAM_INT);
            $query->bindParam('group_id', $item->getGroupId(), \PDO::PARAM_INT);
            $query->bindParam('sender_id', $item->getSenderId(), \PDO::PARAM_INT);
            $query->bindParam('user_id', $item->getUserId(), \PDO::PARAM_INT);
            $query->bindParam('kind', $item->getKind());
            $query->bindParam('target', $item->getTarget());
            $query->bindParam('data', $item->getData());
            $query->bindParam('stime', $item->getStime());
            $query->execute();
        }
        return $item;
    }
Example #5
0
 public static function getSentPage($page = 0)
 {
     $app = \Slim\Slim::getInstance();
     $limit = 50;
     if ($_GET['format'] == 'csv') {
         $page = 0;
         $limit = 10000;
     }
     $userDAO = new UserDAO();
     $messageDAO = new MessageDAO();
     $groupDAO = new GroupDAO();
     $groups = $groupDAO->getList();
     $groups = $groups['list'];
     $formUtils = new FormUtils();
     $startTime = $formUtils->toTimestamp($_GET['start_date'] . ' 00:00');
     $endTime = $formUtils->toTimestamp($_GET['end_date'] . ' 23:59');
     if ($endTime <= 0) {
         $endTime = time();
     }
     if ($startTime <= 0) {
         $startTime = $endTime - 7 * 24 * 3600;
     }
     $app->view->set('start_date', $startTime);
     $app->view->set('end_date', $endTime);
     $query = $_GET;
     $query['start_date'] = $startTime;
     $query['end_date'] = $endTime;
     if (!$userDAO->hasRole('ADMIN')) {
         $strong = \Strong\Strong::getInstance();
         $user = $strong->getUser();
         $query['user_id'] = $user['id'];
     }
     $pager = new Pager(MAINURL . '/reports/sent/?' . http_build_query($_GET), $limit);
     $pager->setPage($page);
     $query = $pager->getQueryArray($query);
     $list = $messageDAO->getList($query);
     $pager->setCount(count($list['list']));
     if (isset($list['total'])) {
         $pager->setTotal($list['total']);
     }
     $reportTable = array();
     foreach ($list['list'] as $message) {
         $statuses = $messageDAO->getStatuses($message);
         foreach ($statuses as $status) {
             if (empty($status['target'])) {
                 continue;
             }
             $key = $status['message_id'];
             if (!empty($reportTable[$key])) {
                 $reportRow = $reportTable[$key];
             } else {
                 $reportRow = array();
                 $group = $groups[$message->getGroupId()];
                 $reportRow['group'] = $group->getNickname();
                 $reportRow['groupCnt'] = count($groupDAO->getNumbers($group->getId()));
                 $reportRow['ctime'] = $message->getCtime();
                 $reportRow['msg'] = $message->getData();
                 $reportRow['targets'] = array();
                 $reportRow['sent'] = array();
                 $reportRow['recv'] = array();
                 $reportRow['error'] = 0;
                 $reportRow['status'] = 0;
             }
             $reportRow['targets'] = $message->getTarget();
             switch ($status['status']) {
                 case Message::MESSAGE_STATUS_ERROR:
                     $reportRow['status'] = 'ERR';
                     break;
                 case Message::MESSAGE_STATUS_RECEIVED_BY_SERVER:
                 case Message::MESSAGE_STATUS_RECEIVED_BY_PHONE:
                     $reportRow['status'] = 'RECV';
                     $reportRow['recv'][$status['target']] = 1;
                     break;
                 case Message::MESSAGE_STATUS_SENT:
                     $reportRow['status'] = 'SENT';
                     $reportRow['sent'][$status['target']] = 1;
                     if ($reportRow['sent_time'] < $status['mtime']) {
                         $reportRow['sent_time'] = $status['mtime'];
                     }
                     break;
             }
             $reportTable[$key] = $reportRow;
         }
     }
     foreach ($reportTable as $k => $v) {
         $v['sentCnt'] = count($v['sent']);
         $v['recvCnt'] = count($v['recv']);
         $reportTable[$k] = $v;
     }
     $app->view->set('menu', 'reports');
     $app->view->set('reportTable', array_values($reportTable));
     $app->view->set('query', $query);
     $app->view->set('pager', $pager);
     if ($_GET['format'] == 'csv') {
         header("Content-type: text/csv");
         header("Content-disposition: attachment; filename=sent.csv");
         $app->render('reports/sent.twig.csv');
     } else {
         $app->render('reports/sent.twig.html');
     }
 }
Example #6
0
function hex($str)
{
    $retVal = '';
    for ($i = 0; $i < strlen($str); $i++) {
        $retVal .= sprintf("%02X ", ord($str[$i]));
    }
    return $retVal;
}
function logToCronFile($msg)
{
    echo date("Y-m-d H:i:s") . ' ' . time() . " " . $msg . "\n";
    file_put_contents(__DIR__ . '/logs/whatsapp.' . date('Ymd') . '.log', date("Y-m-d H:i:s") . " " . $msg . "\n", FILE_APPEND | LOCK_EX);
}
ob_start();
$senderDAO = new SenderDAO();
$groupDAO = new GroupDAO();
$messageDAO = new MessageDAO();
$senders = $senderDAO->getList();
foreach ($senders['list'] as $sender) {
    if ('' == $sender->getPassword()) {
        logToCronFile("No password for sender: " . $sender->getUsername());
        continue;
    }
    $sender = $senderDAO->fetch($sender->getId());
    if (($sender->getFlags() & \GitGis\Whatsapp\Model\Sender::FLAG_UNSYNC) > 0) {
        logToCronFile("Syncing " . $sender->getUsername());
        $groups = $groupDAO->getList(array('user_id' => $sender->getUserId()));
        $contacts = array();
        foreach ($groups['list'] as $groupId => $group) {
            $groupDAO->clearSynced($groupId);
            $groupNumbers = $groupDAO->getNumbers($groupId);
Example #7
0
 /**
  * Process message form
  */
 public static function postEditPage($id)
 {
     $app = \Slim\Slim::getInstance();
     $dao = new MessageDAO();
     $userDAO = new UserDAO();
     $strong = \Strong\Strong::getInstance();
     $user = $strong->getUser();
     $user = $userDAO->fetch($user['id']);
     $groupDAO = new GroupDAO();
     $groupsQuery = array();
     $senderDAO = new SenderDAO();
     $sendersQuery = array();
     $strong = \Strong\Strong::getInstance();
     $user2 = $strong->getUser();
     $groupsQuery['user_id'] = $user2['id'];
     $sendersQuery['user_id'] = $user2['id'];
     $groups = $groupDAO->getList($groupsQuery);
     if (0 == $groups['total']) {
         return $app->redirect(MAINURL . '/groups');
     }
     $senders = $senderDAO->getList($sendersQuery);
     if (0 == $senders['total']) {
         return $app->redirect(MAINURL . '/senders');
     }
     $app->view->set('KIND_TEXT_MSG', Message::KIND_TEXT_MSG);
     $app->view->set('KIND_PHOTO_MSG', Message::KIND_PHOTO_MSG);
     $app->view->set('KIND_AUDIO_MSG', Message::KIND_AUDIO_MSG);
     $app->view->set('KIND_VIDEO_MSG', Message::KIND_VIDEO_MSG);
     $item = $dao->fetch($id);
     if (empty($item)) {
         return $app->notFound();
     } else {
         if (!$userDAO->hasRole('ADMIN') && $item->getGroupId() > 0 && !in_array($item->getGroupId(), array_keys($groups['list']))) {
             return $app->status(403);
         }
         if (empty($_POST['data'])) {
             $_POST['data'] = $item->getData();
         }
     }
     $statuses = $dao->getStatuses($item);
     if (!empty($_POST['resend'])) {
         $dao->resend($item);
         $app->redirect(MAINURL . '/messages/edit/' . $item->getId());
         return;
     }
     $item->dataHuman = self::getHumanUrl($item);
     $mime = '*/*';
     if (Message::KIND_PHOTO_MSG == $item->getKind()) {
         $mime = 'image/*';
     }
     if (Message::KIND_AUDIO_MSG == $item->getKind()) {
         $mime = 'audio/*';
     }
     if (Message::KIND_VIDEO_MSG == $item->getKind()) {
         $mime = 'video/*';
     }
     $item->setUserId($user->getId());
     $dateParts = explode('-', $_POST['stime_date']);
     $timeParts = explode(':', $_POST['stime_time']);
     $stime = mktime($timeParts[0], $timeParts[1], $timeParts[2], $dateParts[1], $dateParts[2], $dateParts[0]);
     $item->setStime($stime);
     if ($item->getKind() == Message::KIND_TEXT_MSG) {
         $item->setData($_POST['data']);
     }
     $item->setGroupId($_POST['group_id']);
     $item->setSenderId($_POST['sender_id']);
     $personalized = array();
     $customField = $dao->getCustomFields($item);
     $numbers = $groupDAO->getNumbers($item->getGroupId());
     foreach ($customField as $num => $fields) {
         if (empty($numbers[$num])) {
             continue;
         }
         $personalized[$num] = $num;
     }
     $_POST['personalized'] = 'personalized $validator';
     $validator = new \Valitron\Validator($_POST);
     $validator->addRule('credits', function ($name, $value) use($user, $userDAO) {
         if ($userDAO->hasRole('ADMIN')) {
             return true;
         }
         return $user->getCredits() > 0;
     });
     $validator->addRule('time', function ($name, $value) {
         $value = explode(':', $value);
         if (count($value) != 3) {
             return false;
         }
         return true;
     });
     $validator->addRule('personalized', function ($name, $value) use($personalized, $numbers) {
         if (count($personalized) == 0) {
             return true;
         }
         return count($personalized) == count($numbers);
     });
     $validator->rule('personalized', 'personalized');
     $validator->label('Personalized');
     $validator->rule('required', 'group_id');
     $validator->label('Group');
     $validator->rule('required', 'sender_id');
     $validator->label('Sender');
     $validator->rule('date', 'stime_date');
     $validator->label('Date');
     $validator->rule('time', 'stime_time');
     $validator->label('Time');
     $validator->rule('required', 'data');
     $validator->label('Message');
     $validator->rule('credits', 'credits');
     $validator->label('Credits');
     if ($validator->validate()) {
         $item = $dao->save($item);
         if (!empty($_POST['send']) && empty($statuses)) {
             $dao->addStatus($item, Message::MESSAGE_STATUS_TO_SEND);
             if (!$userDAO->hasRole('ADMIN')) {
                 $numbers = $groupDAO->getNumbers($item->getGroupId());
                 $user->setCredits($user->getCredits() - count($numbers));
                 $userDAO->save($user);
             }
         }
         $app->redirect(MAINURL . '/messages/edit/' . $item->getId());
     } else {
         $app->view->set('menu', 'messages');
         $app->view->set('id', $id);
         $app->view->set('item', $item);
         $app->view->set('numbers', $numbers);
         $app->view->set('numbers_count', count($numbers));
         $app->view->set('personalized', $personalized);
         $app->view->set('personalized_count', count($personalized));
         $app->view->set('groups', $groups);
         $app->view->set('senders', $senders);
         $app->view->set('statuses', $statuses);
         $app->view->set('errors', $validator->errors());
         $app->view->set('mime', $mime);
         $app->render('messages/edit.twig.html');
     }
 }
Example #8
0
 /**
  * Send message to WhatsApp, then add statuses to DB
  * 
  * @param Message $message
  */
 public function sendMessage(Message $message, Sender $sender)
 {
     $messageDAO = new MessageDAO();
     if ('' == $sender->getPassword()) {
         $messageDAO->addStatus($message, Message::MESSAGE_STATUS_ERROR, 'Sender not registered - go sender and use confirm SMS function');
         return;
     }
     $statuses = $messageDAO->getStatuses($message);
     $sentOk = array();
     foreach ($statuses as $status) {
         if (empty($status['target'])) {
             continue;
         }
         switch ($status['status']) {
             case Message::MESSAGE_STATUS_SENT:
             case Message::MESSAGE_STATUS_RECEIVED_BY_SERVER:
             case Message::MESSAGE_STATUS_RECEIVED_BY_PHONE:
                 $sentOk[$status['target']] = 1;
                 $messageDAO->setMessageTargetStatus($message, $status['target'], $status['status']);
                 break;
         }
     }
     echo "Already sent to: " . implode(",", array_keys($sentOk)) . "\n";
     $groupDao = new GroupDAO();
     $syncedNumbers = $groupDao->getNumbers($message->getGroupId(), true);
     try {
         $w = $this->getWhatsProt($sender);
         if (empty($w)) {
             return;
         }
         $targets = explode(',', $message->getTarget());
         $targets = array_combine($targets, $targets);
         $statuses = $messageDAO->getStatuses($message);
         foreach ($statuses as $status) {
             if ($status['status'] == Message::MESSAGE_STATUS_RECEIVED_BY_SERVER) {
                 unset($targets[$status['target']]);
             }
         }
         $filteredTargets = array();
         $notSynced = array();
         $allTargets = array();
         foreach ($targets as $target) {
             if ($target == $sender->getUsername()) {
                 continue;
             }
             if (empty($syncedNumbers[$target])) {
                 $notSynced[$target] = $target;
                 continue;
             }
             if (!empty($sentOk[$target])) {
                 continue;
             }
             $allTargets[] = $target;
             if (count($filteredTargets) <= 48) {
                 $filteredTargets[] = $target;
             }
         }
         echo "Filtered: " . implode(",", $filteredTargets) . "\n";
         echo "Not synced: " . implode(",", array_keys($notSynced)) . "\n";
         if (empty($filteredTargets)) {
             $messageDAO->addStatus($message, Message::MESSAGE_STATUS_ERROR, "No synced numbers. Sync Group.");
         }
         $targets = $filteredTargets;
         foreach ($allTargets as $target) {
             $messageDAO->setMessageTargetStatus($message, $target, 0);
         }
         $customFields = $messageDAO->getCustomFields($message);
         $this->currentMessage = $message;
         $this->currentTargets = $targets;
         switch ($message->getKind()) {
             case Message::KIND_TEXT_MSG:
                 $data = $message->getData();
                 if (false && strpos($data, '$field') === false) {
                     $w->cleanDebug();
                     $this->lastSentMessageId = 0;
                     sleep(strlen($data) / 4);
                     $w->sendBroadcastMessage($targets, $data);
                     $whatsapp_id = $this->lastSentMessageId;
                     $debugMsgReceiver = $w->getDebugBuf();
                     $this->printDebug($w->getDebugBuf());
                     if (!$whatsapp_id) {
                         $messageDAO->addStatus($message, Message::MESSAGE_STATUS_ERROR, $debugMsgReceiver);
                         break;
                     }
                 } else {
                     foreach ($filteredTargets as $target) {
                         $sendRetVal = null;
                         $data = $message->getData();
                         if (!empty($customFields[$target])) {
                             for ($i = 1; $i < 6; $i++) {
                                 $data = str_replace('$field' . $i, $customFields[$target]['field' . $i], $data);
                             }
                         }
                         $w->cleanDebug();
                         $this->lastSentMessageId = 0;
                         $w->sendMessageComposing($target);
                         sleep(strlen($data) / 4);
                         $w->sendMessage($target, $data);
                         $whatsapp_id = $this->lastSentMessageId;
                         $debugMsgReceiver = $w->getDebugBuf();
                         $this->printDebug($w->getDebugBuf());
                         if (!$whatsapp_id) {
                             $messageDAO->addStatus($message, Message::MESSAGE_STATUS_ERROR, $debugMsgReceiver);
                             continue;
                         }
                     }
                 }
                 break;
             case Message::KIND_PHOTO_MSG:
                 if (false) {
                     $w->cleanDebug();
                     $this->lastSentMessageId = 0;
                     sleep(8);
                     $w->sendBroadcastImage($targets, WEBDIR . '/uploads/' . $message->getData(), false);
                     $whatsapp_id = $this->lastSentMessageId;
                     $debugMsgReceiver = $w->getDebugBuf();
                     $this->printDebug($w->getDebugBuf());
                     if (!$whatsapp_id) {
                         $messageDAO->addStatus($message, Message::MESSAGE_STATUS_ERROR, $debugMsgReceiver);
                         break;
                     }
                 } else {
                     foreach ($filteredTargets as $target) {
                         $sendRetVal = null;
                         $w->cleanDebug();
                         $this->lastSentMessageId = 0;
                         sleep(4);
                         $w->sendMessageImage($target, WEBDIR . '/uploads/' . $message->getData(), false);
                         $whatsapp_id = $this->lastSentMessageId;
                         $debugMsgReceiver = $w->getDebugBuf();
                         $this->printDebug($w->getDebugBuf());
                         if (!$whatsapp_id) {
                             $messageDAO->addStatus($message, Message::MESSAGE_STATUS_ERROR, $debugMsgReceiver);
                             continue;
                         }
                     }
                 }
                 break;
             case Message::KIND_AUDIO_MSG:
                 if (false) {
                     $w->cleanDebug();
                     $this->lastSentMessageId = 0;
                     sleep(8);
                     $w->sendBroadcastAudio($targets, WEBDIR . '/uploads/' . $message->getData(), false);
                     $whatsapp_id = $this->lastSentMessageId;
                     $debugMsgReceiver = $w->getDebugBuf();
                     $this->printDebug($w->getDebugBuf());
                     if (!$whatsapp_id) {
                         $messageDAO->addStatus($message, Message::MESSAGE_STATUS_ERROR, $debugMsgReceiver);
                         break;
                     }
                 } else {
                     foreach ($filteredTargets as $target) {
                         $sendRetVal = null;
                         $w->cleanDebug();
                         $this->lastSentMessageId = 0;
                         sleep(4);
                         $w->sendMessageAudio($target, WEBDIR . '/uploads/' . $message->getData(), false);
                         $whatsapp_id = $this->lastSentMessageId;
                         $debugMsgReceiver = $w->getDebugBuf();
                         $this->printDebug($w->getDebugBuf());
                         if (!$whatsapp_id) {
                             $messageDAO->addStatus($message, Message::MESSAGE_STATUS_ERROR, $debugMsgReceiver);
                             continue;
                         }
                     }
                 }
                 break;
             case Message::KIND_VIDEO_MSG:
                 if (false) {
                     $w->cleanDebug();
                     $this->lastSentMessageId = 0;
                     sleep(8);
                     $w->sendBroadcastVideo($targets, WEBDIR . '/uploads/' . $message->getData(), false);
                     $whatsapp_id = $this->lastSentMessageId;
                     $debugMsgReceiver = $w->getDebugBuf();
                     $this->printDebug($w->getDebugBuf());
                     if (!$whatsapp_id) {
                         $messageDAO->addStatus($message, Message::MESSAGE_STATUS_ERROR, $debugMsgReceiver);
                         break;
                     }
                 } else {
                     foreach ($filteredTargets as $target) {
                         $sendRetVal = null;
                         $w->cleanDebug();
                         $this->lastSentMessageId = 0;
                         sleep(4);
                         $w->sendMessageVideo($target, WEBDIR . '/uploads/' . $message->getData(), false);
                         $whatsapp_id = $this->lastSentMessageId;
                         $debugMsgReceiver = $w->getDebugBuf();
                         $this->printDebug($w->getDebugBuf());
                         if (!$whatsapp_id) {
                             $messageDAO->addStatus($message, Message::MESSAGE_STATUS_ERROR, $debugMsgReceiver);
                             continue;
                         }
                     }
                 }
                 break;
         }
         $messageDAO->setMessageTargetStatus($message, $status['target'], Message::MESSAGE_STATUS_SENT);
     } catch (\Exception $ex) {
         $this->printDebug($w->getDebugBuf());
         $messageDAO->addStatus($message, Message::MESSAGE_STATUS_ERROR, $ex->getMessage());
     }
     $this->currentTargets = null;
     $this->currentMessage = null;
 }