Guest User

Untitled

a guest
Sep 28th, 2015
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 17.46 KB | None | 0 0
  1. <?php
  2. class GetResponse {
  3.     /** API ключ */
  4.     private $apiKey;
  5.     /** API url */
  6.     private $apiUrl;
  7.    
  8.     private $client;
  9.     private $db;
  10.    
  11.     public function __construct() {
  12.         $this->apiKey = $_SESSION['grProfile']['apiKey'];
  13.         $this->apiUrl = $_SESSION['grProfile']['apiUrl'];
  14.         $this->client = new jsonRPCClient($this->apiUrl);
  15.         $this->db = new DB_MySQL();    
  16.     }
  17.    
  18.     /**
  19.      * Считывает данные с xml файла
  20.      * @param       string $xml
  21.      * @return      array xml данные
  22.      * @author      Игорь Быра <ihorbyra@gmail.com>
  23.      * @version     1.0
  24.      */
  25.     public function parseXML($xml) {
  26.         $xml = simplexml_load_file($xml);
  27.  
  28.         $data = array(
  29.                 'campaign' => (string) $xml->config->campaign,
  30.                 'campaign_target' => (string) $xml->config->campaign_target,
  31.                 'date_start' => (string) $xml->config->date_start,
  32.                 'date_end' => (string) $xml->config->date_end,
  33.                 'cycle_day' => (string) $xml->config->cycle_day,
  34.                 'completed' => (string) $xml->config->completed
  35.             );
  36.        
  37.         return $data;
  38.     }
  39.    
  40.     /**
  41.      * Получает информацию о кампании
  42.      * @param       string $data
  43.      * @return      array данные по кампании
  44.      * @author      Игорь Быра <ihorbyra@gmail.com>
  45.      * @version     1.0
  46.      */
  47.     public function getCampaign($data) {
  48.         $campaignName = $data;
  49.         $campaign = $this->client->get_campaigns(
  50.                         $this->apiKey,
  51.                         array('name' => array('EQUALS' => $campaignName))
  52.                     );
  53.                    
  54.         return $campaign;
  55.     }
  56.    
  57.     public function getCampaignById($id) {
  58.         $campaign = $this->client->get_campaign(
  59.             $this->apiKey,
  60.             array('campaign' => $id)
  61.         );
  62.                    
  63.         return $campaign;
  64.     }
  65.    
  66.     /**
  67.      * Получает список всех кампаний
  68.      * @return      array список кампаний
  69.      * @author      Игорь Быра <ihorbyra@gmail.com>
  70.      * @version     1.0
  71.      */
  72.     public function getCampaigns() {
  73.         $campaign = $this->client->get_campaigns($this->apiKey);
  74.         return $campaign;
  75.     }
  76.    
  77.     public function getContacts($campaign) {
  78.         $contacts = $this->client->get_contacts(
  79.             $this->apiKey,
  80.                 array(
  81.                     'campaigns' => array(
  82.                         $campaign
  83.                     )
  84.                 )
  85.         );     
  86.         return $contacts;
  87.     }
  88.    
  89.     /**
  90.      * Получает информацию о контактах кампании $campaign, созданых в период с $data['date_start'] до $data['date_end']
  91.      * @param       string $campaign
  92.      * @param       array $data
  93.      * @return      array данные по контактах кампании $campaign
  94.      * @author      Игорь Быра <ihorbyra@gmail.com>
  95.      * @version     1.0
  96.      */
  97.     public function getContactsByPeriod($data) {
  98.         $campaignId = $data['campaign'];
  99.        
  100.         $today = date('Y-m-d');
  101.         $date = new DateTime($today);
  102.         $modifier = (($data['eachDay'] > 1) ?  -$data['eachDay'].' days' : -$data['eachDay'].' day');
  103.         $date->modify($modifier);
  104.         $dateTo = $date->format('Y-m-d');
  105.  
  106.         $contacts = $this->client->get_contacts(
  107.             $this->apiKey,
  108.                 array(
  109.                     'campaigns' => array(
  110.                         $campaignId
  111.                     ),
  112.                     'created_on' => array(
  113.                         'FROM' => $dateTo,
  114.                         'TO' => $dateTo
  115.                     )
  116.                 )
  117.         );     
  118.         return $contacts;
  119.     }
  120.    
  121.     /**
  122.      * Перемещает контакты в кампании $campaign
  123.      * @param       array $contacts
  124.      * @param       string $campaign
  125.      * @return      void
  126.      * @author      Игорь Быра <ihorbyra@gmail.com>
  127.      * @version     1.1
  128.      */
  129.     public function moveContacts($contacts, $campaign) {
  130.         //$campaignId = array_keys($campaign);
  131.         //$campaignId = array_pop($campaignId);
  132.        
  133.         $contactsId = array_keys($contacts);
  134.        
  135.         foreach ($contactsId as $contact) {
  136.             $move = $this->client->move_contact(
  137.                 $this->apiKey,
  138.                     array('contact' => $contact,
  139.                           'campaign' => $campaign
  140.                     )
  141.             );
  142.         }          
  143.     }
  144.    
  145.     /**
  146.      * Меняет значение completed в xml файле
  147.      * @param       string $xmlSorce
  148.      * @throws      Exception
  149.      * @return      bool
  150.      * @author      Игорь Быра <ihorbyra@gmail.com>
  151.      * @version     1.0
  152.      */
  153.     public function setComplete($xmlSorce) {
  154.         $xml = simplexml_load_file($xmlSorce);
  155.         $result = $xml->xpath('/root/config/completed');
  156.         $result[0][0] = 1;
  157.  
  158.         if ($xml->asXML($xmlSorce) === false) {
  159.             throw new Exception('Cannot save values into "'.$xmlSorce.'"',99);
  160.         }
  161.         return true;
  162.     }
  163.    
  164.     /**
  165.      * Добавляет контакты в цикл на день
  166.      * @param       integer $cycleDay
  167.      * @param       array $contacts
  168.      * @return      void
  169.      * @author      Игорь Быра <ihorbyra@gmail.com>
  170.      * @version     1.0
  171.      */
  172.     public function setContactCycle($cycleDay = null, $contacts) {     
  173.         $contactsId = array_keys($contacts);
  174.        
  175.         foreach ($contactsId as $contact) {        
  176.             $set = $this->client->set_contact_cycle(
  177.                 $this->apiKey,
  178.                     array('contact' => $contact,
  179.                           'cycle_day' => $cycleDay
  180.                     )
  181.             );
  182.         }          
  183.     }
  184.    
  185.     /**
  186.      * Создает процесс по работе с кампаниями
  187.      * @return      void
  188.      * @author      Игорь Быра <ihorbyra@gmail.com>
  189.      * @version     1.0
  190.      */
  191.     public function addProcess($data) {
  192.         $date = date('Y-m-d');
  193.         $query = "INSERT INTO `campaign_actions` (`id`, `grId`, `action`, `campaign`, `campaignTarget`, `cycleDay`, `eachDay`, `date`)
  194.                     VALUES (NULL, '{$data['grId']}', '{$data['action']}', '{$data['campaign']}', '{$data['campaignTarget']}', '{$data['cycleDay']}', '{$data['eachDay']}', '{$date}')";
  195.         $result = $this->db->Execute($query);
  196.     }
  197.    
  198.     /**
  199.      * Редактирует процесс по работе с кампаниями
  200.      * @return      void
  201.      * @author      Игорь Быра <ihorbyra@gmail.com>
  202.      * @version     1.0
  203.      */
  204.     public function editProcess($data) {
  205.         $query = "UPDATE `campaign_actions`
  206.                     SET `grId` = '{$data['grId']}', `action` = '{$data['action']}', `campaign` = '{$data['campaign']}',
  207.                     `campaignTarget` = '{$data['campaignTarget']}', `cycleDay` = '{$data['cycleDay']}', `eachDay` = '{$data['eachDay']}'
  208.                     WHERE `id` = '{$data['id']}'";
  209.         $result = $this->db->Execute($query);
  210.     }
  211.    
  212.     /**
  213.      * Выводит информацию о процессе
  214.      * @param       int $id
  215.      * @return      array
  216.      * @author      Игорь Быра <ihorbyra@gmail.com>
  217.      * @version     1.0
  218.      */
  219.     public function getProcess($id) {
  220.         $query = "SELECT * FROM `campaign_actions` WHERE `id` = '{$id}'";
  221.         $result = $this->db->Execute($query);
  222.         $row = mysql_fetch_object($result);
  223.         $process = array(
  224.             'id' => $row->id,
  225.             'action' => $row->action,
  226.             'campaign' => $row->campaign,
  227.             'campaignTarget' => $row->campaignTarget,
  228.             'cycleDay' => $row->cycleDay,
  229.             'eachDay' => $row->eachDay,
  230.             'date' => $row->date
  231.         );
  232.         return $process;
  233.     }
  234.    
  235.     /**
  236.      * Удаляет процесс
  237.      * @param       int $id - ID процесса
  238.      * @return      void
  239.      * @author      Игорь Быра <ihorbyra@gmail.com>
  240.      * @version     1.0
  241.      */
  242.     public function deleteProcess($id) {
  243.         $query = "UPDATE `campaign_actions` SET `deleted` = '1' WHERE `id` = '{$id}'";
  244.         $result = $this->db->Execute($query);
  245.     }
  246.    
  247.     /**
  248.      * VIEW Выводит список кампаний в виде списка <select>
  249.      * @param       array $campaigns
  250.      * @return      string список кампаний
  251.      * @author      Игорь Быра <ihorbyra@gmail.com>
  252.      * @version     1.1
  253.      */
  254.     public function printCampaigns($campaigns, $currentCampaign = null) {  
  255.         foreach ($campaigns as $campaignId => $campaignInfo) {
  256.             $selected = (($currentCampaign !== null && $currentCampaign == $campaignId) ? ' selected' : '');
  257.             $content .= '<option'.$selected.' value="'.$campaignId.'">'.$campaignInfo['name'].'</option>';
  258.         }
  259.         return $content;
  260.     }
  261.    
  262.     /**
  263.      * VIEW Вывод всех процессов
  264.      * @return      string список процессов
  265.      * @author      Игорь Быра <ihorbyra@gmail.com>
  266.      * @version     1.0
  267.      */
  268.     public function getProcesses($grId) {
  269.         $query = "SELECT * FROM `campaign_actions` WHERE `deleted` = '0' AND `grId` = '{$grId}' ORDER BY `id` DESC";
  270.         $result = $this->db->Execute($query);
  271.         $num = mysql_num_rows($result);
  272.        
  273.         if ($num > 0) {
  274.             $content = '<table class="table table-hover">
  275.                             <tr>
  276.                                 <th>Дата создания</th>
  277.                                 <th>Действие</th>
  278.                                 <th>Кампания(источник)</th>
  279.                                 <th>Кампания(цель)</th>
  280.                                 <th>Цикл на день</th>
  281.                                 <th>Делается каждые</th>
  282.                                 <td>&nbsp;</td>    
  283.                                 <td>&nbsp;</td>                        
  284.                             </tr>';
  285.             while ($row = mysql_fetch_object($result)) {
  286.                 $action = (($row->action == '0') ? 'копирование' : 'перемещение');
  287.                 $campaign = $this->getCampaignById($row->campaign);
  288.                 $campaignTarget = $this->getCampaignById($row->campaignTarget);
  289.                 //$campaign =  var_export($campaign, true);
  290.                 $content .= '<tr id="process_'.$row->id.'">
  291.                                 <td>'.$row->date.'</td>
  292.                                 <td>'.$action.'</td>
  293.                                 <td>'.$campaign[$row->campaign]['name'].'</td>
  294.                                 <td>'.$campaignTarget[$row->campaignTarget]['name'].'</td>
  295.                                 <td>'.$row->cycleDay.'</td>
  296.                                 <td>'.$row->eachDay.'</td>
  297.                                 <td>
  298.                                     <button onClick="locate(\'/getresponse/newForm/'.$row->id.'/\')" type="button" class="btn btn-success btn-sm">
  299.                                       <span class="glyphicon glyphicon-pencil"></span>
  300.                                     </button>
  301.                                 </td>  
  302.                                 <td>
  303.                                     <button onClick="deleteProcess('.$row->id.')" type="button" class="btn btn-danger btn-sm">
  304.                                       <span class="glyphicon glyphicon-remove"></span>
  305.                                     </button>
  306.                                 </td>  
  307.                             </tr>';
  308.             }
  309.             $content .= '</table>';
  310.             return $content;
  311.         }      
  312.         return 'На данный момент нет ниодного процесса';
  313.     }
  314.    
  315.    
  316.     /**
  317.      * Вывод GetResponse профайлов в массив
  318.      * @return      array список профайлов
  319.      * @author      Игорь Быра <ihorbyra@gmail.com>
  320.      * @version     1.0
  321.      *
  322.      */
  323.     public function getResponseProfiles() {
  324.         $data = array();
  325.        
  326.         $query = "SELECT * FROM `api_data` WHERE `deleted` = '0'";
  327.         $result = $this->db->Execute($query);
  328.         $num = mysql_num_rows($result);
  329.        
  330.         if ($num > 0) {
  331.             while ($row = mysql_fetch_object($result)) {
  332.                 $data[] = array('id' => $row->id,
  333.                             'name' => $row->name,
  334.                             'apikey' => $row->apikey,
  335.                             'apiurl' => $row->apiurl,
  336.                             'default' => $row->default);
  337.             }
  338.             return $data;
  339.         }
  340.         else
  341.             return false;
  342.     }
  343.    
  344.     /**
  345.      * VIEW Вывод всех профайлов
  346.      * @param       array $data
  347.      * @return      string
  348.      * @author      Игорь Быра <ihorbyra@gmail.com>
  349.      * @version     1.0
  350.      */
  351.     public function viewResponseProfiles($data) {
  352.        
  353.         if ($data === false) $content = 'На данный момент нет GetResponse профайлов';
  354.         else {
  355.             $cData = count($data);
  356.             $content = '<table class="table table-hover">
  357.                             <tr>
  358.                                 <th>Название</th>
  359.                                 <th>API Key</th>
  360.                                 <th>API Url</th>
  361.                                 <td>&nbsp;</td>    
  362.                                 <td>&nbsp;</td>
  363.                                 <td>&nbsp;</td>                        
  364.                             </tr>';
  365.             for ($i = 0; $i < $cData; $i++) {
  366.                 $defaultColor = (($data[$i]['default'] == '0') ? 'btn-danger' : 'btn-success');
  367.                 $defaultIcon = (($data[$i]['default'] == '0') ? 'glyphicon-remove-circle' : 'glyphicon-ok-circle');
  368.                 $content .= '<tr id="profile_'.$data[$i]['id'].'">
  369.                                 <td>'.$data[$i]['name'].'</td>
  370.                                 <td>'.$data[$i]['apikey'].'</td>
  371.                                 <td>'.$data[$i]['apiurl'].'</td>
  372.                                 <td>
  373.                                     <button onClick="locate(\'/getresponseProfiles/default/'.$data[$i]['id'].'/\')" type="button" class="btn '.$defaultColor.' btn-sm">
  374.                                       <span class="glyphicon '.$defaultIcon.'"></span>
  375.                                     </button>
  376.                                 </td>  
  377.                                 <td>
  378.                                     <button onClick="locate(\'/getresponseProfiles/newForm/'.$data[$i]['id'].'/\')" type="button" class="btn btn-primary btn-sm">
  379.                                       <span class="glyphicon glyphicon-pencil"></span>
  380.                                     </button>
  381.                                 </td>      
  382.                                 <td>
  383.                                     <button onClick="deleteProfile('.$data[$i]['id'].')" type="button" class="btn btn-danger btn-sm">
  384.                                       <span class="glyphicon glyphicon-remove"></span>
  385.                                     </button>
  386.                                 </td>                          
  387.                             </tr>';
  388.             }
  389.             $content .= '</table>';        
  390.         }
  391.  
  392.         return $content;   
  393.     }
  394.    
  395.     /**
  396.      * Удаляет профайл
  397.      * @param       int $id - ID профайла
  398.      * @return      void
  399.      * @author      Игорь Быра <ihorbyra@gmail.com>
  400.      * @version     1.0
  401.      */
  402.     public function deleteProfile($id) {
  403.         $query = "UPDATE `api_data` SET `deleted` = '1' WHERE `id` = '{$id}'";
  404.         $result = $this->db->Execute($query);
  405.     }
  406.    
  407.     /**
  408.      * Создает профайл
  409.      * @return      void
  410.      * @author      Игорь Быра <ihorbyra@gmail.com>
  411.      * @version     1.0
  412.      */
  413.     public function addProfile($data) {
  414.         $query = "INSERT INTO `api_data` (`id`, `name`, `apikey`, `apiurl`, `default`, `deleted`)
  415.                     VALUES (NULL, '{$data['name']}', '{$data['apiKey']}', '{$data['apiUrl']}', '0', '0');";
  416.         $result = $this->db->Execute($query);
  417.     }
  418.    
  419.     /**
  420.      * Выводит информацию о профайле
  421.      * @param       int $id
  422.      * @return      array
  423.      * @author      Игорь Быра <ihorbyra@gmail.com>
  424.      * @version     1.0
  425.      */
  426.     public function getProfile($id) {
  427.         $query = "SELECT * FROM `api_data` WHERE `id` = '{$id}'";
  428.         $result = $this->db->Execute($query);
  429.         $row = mysql_fetch_object($result);
  430.         $profile = array(
  431.             'id' => $row->id,
  432.             'name' => $row->name,
  433.             'apiKey' => $row->apikey,
  434.             'apiUrl' => $row->apiurl,
  435.             'default' => $row->default
  436.         );
  437.         return $profile;
  438.     }
  439.    
  440.     /**
  441.      * Редактирует профайл
  442.      * @return      void
  443.      * @author      Игорь Быра <ihorbyra@gmail.com>
  444.      * @version     1.0
  445.      */
  446.     public function editProfile($data) {
  447.         $query = "UPDATE  `api_data` SET  `name` =  '{$data['name']}',
  448.                         `apikey` =  '{$data['apiKey']}',
  449.                         `apiurl` =  '{$data['apiUrl']}'
  450.                  WHERE  `id` ='{$data['id']}'";
  451.         $result = $this->db->Execute($query);
  452.     }
  453.    
  454.     /**
  455.      * Выводит список профайлов
  456.      * @return      string
  457.      * @author      Игорь Быра <ihorbyra@gmail.com>
  458.      * @version     1.0
  459.      */
  460.     public function viewProfilesList() {
  461.         $profile = $this->getResponseProfiles();
  462.         if ($profile === false) $content = '<ul class="dropdown-menu"><li>На данный момент нет GetResponse профайлов</li></ul>';
  463.         else {
  464.             $cData = count($profile);
  465.             $content = '<ul class="dropdown-menu">';
  466.             for ($i = 0; $i < $cData; $i++) {
  467.                 //TODO: проверить на работоспособность
  468.                 $icon = ( isset($_SESSION['grProfile']) ? (($profile[$i]['id'] == $_SESSION['grProfile']['id']) ? 'glyphicon-ok' : '') : (($profile[$i]['default'] == '1') ? 'glyphicon-ok' : '') );
  469.                 $content .= '<li>
  470.                                 <a href="/changeProfile/'.$profile[$i]['id'].'/"><i class="glyphicon '.$icon.'"></i> '.$profile[$i]['name'].'</a>
  471.                             </li>';
  472.                 if (($i+1) < $cData) $content .= '<li class="divider"></li>';
  473.             }
  474.             $content .= '</ul>';
  475.         }
  476.         return $content;
  477.     }
  478.    
  479.     /**
  480.      * Выводит данные профайла по умолчанию
  481.      * @return      array
  482.      * @author      Игорь Быра <ihorbyra@gmail.com>
  483.      * @version     1.0
  484.      */
  485.     public function getDefaultProfile() {
  486.         $query = "SELECT * FROM `api_data` WHERE `default` = '1' AND `deleted` = '0'";
  487.         $result = $this->db->Execute($query);
  488.         $row = mysql_fetch_object($result);
  489.         $data = array(
  490.             'id' => $row->id,
  491.             'name' => $row->name,
  492.             'apiKey' => $row->apikey,
  493.             'apiUrl' => $row->apiurl
  494.         );
  495.         return $data;
  496.     }
  497.    
  498.     /**
  499.      * Смена профайла
  500.      * @param       integer $id
  501.      * @return      array
  502.      * @author      Игорь Быра <ihorbyra@gmail.com>
  503.      * @version     1.0
  504.      */
  505.     public function changeProfile($id) {
  506.         $query = "SELECT * FROM `api_data` WHERE `id` = '{$id}'";
  507.         $result = $this->db->Execute($query);
  508.         $row = mysql_fetch_object($result);
  509.         $data = array(
  510.             'id' => $row->id,
  511.             'name' => $row->name,
  512.             'apiKey' => $row->apikey,
  513.             'apiUrl' => $row->apiurl
  514.         );
  515.         return $data;
  516.     }
  517.    
  518.     /**
  519.      * Выводит данные всех профайлов
  520.      * @return      array
  521.      * @author      Игорь Быра <ihorbyra@gmail.com>
  522.      * @version     1.0
  523.      */
  524.     public function getProfiles() {
  525.         $query = "SELECT * FROM `api_data` WHERE `deleted` = '0'";
  526.         $result = $this->db->Execute($query);
  527.         $num = mysql_num_rows($result);
  528.        
  529.         if ($num > 0) {
  530.             $profiles = array();
  531.             while ($row = mysql_fetch_object($result)) {
  532.                 $profiles[] = array(
  533.                     'id' => $row->id,
  534.                     'name' => $row->name,
  535.                     'apiKey' => $row->apikey,
  536.                     'apiUrl' => $row->apiurl
  537.                 );
  538.             }
  539.         } else return false;
  540.     }
  541.    
  542.    
  543.     /**
  544.      * Вывод всех процессов в массив для запуска крона
  545.      * @return      array список процессов
  546.      * @author      Игорь Быра <ihorbyra@gmail.com>
  547.      * @version     1.0
  548.      */
  549.     public function getProcessesForCron($grId) {
  550.         $cronjob = array();
  551.         $query = "SELECT * FROM `campaign_actions` WHERE `deleted` = '0' AND `grId` = '{$grId}' ORDER BY `id` DESC";
  552.         $result = $this->db->Execute($query);
  553.         $num = mysql_num_rows($result);
  554.        
  555.         if ($num > 0) {
  556.             while ($row = mysql_fetch_object($result)) {               
  557.                 $cronjob[] = array('id' => $row->id,
  558.                             'campaign' => $row->campaign,
  559.                             'campaignTarget' => $row->campaignTarget,
  560.                             'cycleDay' => $row->cycleDay,
  561.                             'eachDay' => $row->eachDay,
  562.                             'date' => $row->date);
  563.             }
  564.         }
  565.         return $cronjob;
  566.     }
  567.    
  568.  
  569. }
  570.  
  571. ?>
Add Comment
Please, Sign In to add comment