test

test


<?php
    include_once("conf.php");
    
    class Call {
       public $Id;
       public $CreatedOn;
       public $CreatedById = BPM_DefaultOwnerID;
       public $ModifiedOn;
       public $ModifiedById = BPM_DefaultOwnerID;
       public $Caption;
       public $IntegrationId;
       public $CallerId;
       public $CalledId;
       public $StartDate;
       public $EndDate;
       public $Duration;
       public $BeforeConnectionTime;
       public $TalkTime;
       public $HoldTime;
       public $DirectionId;
       
       public $_missed;
       public $_links;
    }
    
    class CallFile {
       public $Id;
       public $Name;
       public $CreatedOn;
       public $CreatedById = BPM_DefaultOwnerID;
       public $ModifiedOn;
       public $ModifiedById = BPM_DefaultOwnerID;
       public $CallId;
       public $TypeId;
       public $Version = 1;
       public $Size;
       
       public $_path;
    }
    
    class CDRSync {
       
       private $DB;
       
       static protected $GUID_NULL = "00000000-0000-0000-0000-000000000000";
             
       function Login() {
          if (!$this->ConnectToDB()) {
             return false;
          }
          $url = BPM_Url . BPM_LoginAction;
          $request_data["WorkspaceName"] = BPM_WorkspaceName;
          $request_data["TimeZoneOffset"] = BPM_TimeZoneOffset;
          $request_data["UserName"] = BPM_UserName;
          $request_data["UserPassword"] = BPM_UserPassword;
          $jcres = json_encode($request_data);
          $ch = curl_init($url);
          curl_setopt($ch, CURLOPT_COOKIEJAR, BPM_CookieFileName);
          curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
          curl_setopt($ch, CURLOPT_POSTFIELDS, $jcres);
          curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
          curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
          curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
          curl_setopt($ch, CURLOPT_HTTPHEADER, array(
             'Content-Type: application/json',
             'Content-Length: ' . strlen($jcres))
          );
          $result = curl_exec($ch);
          curl_close($ch);
          if ($result === FALSE) {
             $this->LogWrite("Error connecting to " . BPM_Url . " (" . __METHOD__ . ")");
             return false;
          }
          $result = json_decode($result);
          if ($result->Code != '0') {
             $this->LogWrite($result->Message . " (" . __METHOD__ . ")");
             return false;
          }
          return true;
       }
       
       function PrintTable($year, $month, $day) {
          $sql = "SELECT * 
             FROM cdr
             WHERE YEAR(calldate) = {$year}
                AND MONTH(calldate) = {$month}
                AND DAYOFMONTH(calldate) = {$day}
             ORDER BY calldate DESC";
          $cdr_calls = $this->DB->query($sql)->fetchAll(PDO::FETCH_CLASS, 'stdClass');
          $i = 0;
          echo count($cdr_calls) . "<br><br>";
          
          $html = "<style>
             table, th, td {
                border: 1px solid black;
                border-collapse: collapse;
             }
             </style>
             <table>";
          
          foreach($cdr_calls AS $cdr_call) {
             if ($i == 0) {
                $i = 1;
                $html .= "<thead><tr>";
                foreach($cdr_call as $key => $value) {
                   $html .= "<th>$key</th>";
                }
                $html .= "</tr></thead><tbody>";
             }
             $html .= "<tr>";
             foreach($cdr_call as $key => $value) {
                $html .= "<td>$value</td>";
             }
             $html .= "</tr>";
          }
          $html .= "</tbody></table>";
          echo $html;          
       }
             
       function Export($year = 0, $month = 0, $day = 0) {
          if ($year > 0 && $month > 0 && $day > 0) {
             $filter = "year(StartDate) eq $year and month(StartDate) eq $month and day(StartDate) eq $day";
             $date_filter = "(YEAR(calldate) = {$year} AND MONTH(calldate) = {$month} AND DAYOFMONTH(calldate) = {$day})";
          } else {
             $hour_offset = -1;
             $datetime = $this->GetFormatedDate(date('Y-m-d H:i:s', strtotime("{$hour_offset} hour")), false);
             $filter = "StartDate gt {$datetime}";
             $date_filter = "(calldate > DATE_ADD(NOW(), INTERVAL {$hour_offset} HOUR))";
          }
          $file_select = "'' AS recordingfile";
          if (FILE_NAME_IN_CDR_TABLE) {
             $file_select = "recordingfile";
          }        
          
          $missed_sql = "SELECT src, '' AS dst, clid, '' AS dstchannel, uniqueid, MIN(calldate) AS calldate, MAX(duration) AS duration, '' AS recordingfile,
                   0 AS billsec, 1 AS missed           
                FROM cdr 
                WHERE {$date_filter}
                   AND disposition = 'NO ANSWER'
                   AND LENGTH(src) > " . BPM_InternalPhoneNumberMaxLen . "
                   AND lastapp = 'Queue'
                   AND lastdata like '%BASE0CC%'
                GROUP BY src, uniqueid";
          
          $sql = "SELECT DISTINCT src, dst, clid, dstchannel, uniqueid, calldate, duration, {$file_select}, billsec, 0 AS missed
                FROM cdr 
                WHERE {$date_filter}
                   AND (
                            disposition = 'ANSWERED'
                            OR (
                         disposition != 'ANSWERED'
                         AND LENGTH(src) <= " . BPM_InternalPhoneNumberMaxLen . "
                                AND LENGTH(dst) > " . BPM_InternalPhoneNumberMaxLen . "
                               )
                        )
                   AND lastapp in ('Dial', 'Queue')";
          
          $cdr_calls = array_merge(
             $this->DB->query($sql)->fetchAll(PDO::FETCH_CLASS, 'stdClass'),
             $this->DB->query($missed_sql)->fetchAll(PDO::FETCH_CLASS, 'stdClass')
          );
          
          $calls = $this->GetEntities('AprCallView', $filter, array(), array(), $orderby = array("CreatedOn desc"));
          if (!is_array($calls)) {
              return;
          }
          
          /*
          echo "<pre>";
          print_r($calls);
          echo "</pre>";
          */
          
          $DIDs = $this->GetDestinationNumberDIDLookup();
          $processed_calls = array();
          
          foreach($cdr_calls AS $cdr_call) {
             if (in_array($cdr_call->uniqueid, $processed_calls)) {
                continue;
             }
             $DID = $this->ParseDID($cdr_call->clid);
             $DIDId = !empty($DID) && isset($DIDs[$DID]) ? $DIDs[$DID] : "";
             $existing_call = "";            
             foreach($calls as $value) {
                if (strpos($value->IntegrationId, $cdr_call->uniqueid) !== FALSE) {
                   $existing_call = $value;
                   if ($cdr_call->billsec > 0 && $existing_call->TalkTime > 0) {
                      break;
                   }
                }  
             }
             $missed    = $cdr_call->missed;
             $talktime_greater_than_0 = false;
             if (empty($existing_call)) {
                $call = new Call();
                $call->_missed = $missed;
                $call->CreatedOn = $this->GetFormatedDate($cdr_call->calldate);
                $call->IntegrationId = $cdr_call->uniqueid;
                $call->CallerId = $cdr_call->src;
                $call->CalledId = $cdr_call->dst;
                if (PARSE_DST_FROM_DSTCHANNEL === TRUE) {
                   if ((strlen($cdr_call->src) > BPM_InternalPhoneNumberMaxLen && strlen($cdr_call->dst) > BPM_InternalPhoneNumberMaxLen) ||
                      strlen($cdr_call->dst) <= 1)
                   {
                      $called_id = $this->GetCalledIdFromChannel($cdr_call->dstchannel);
                      if ($called_id != "") {
                         $call->CalledId = $called_id;
                      }
                   }
                }
                $call->StartDate = $this->GetFormatedDate($cdr_call->calldate);
                $call->EndDate = $this->GetFormatedDate(date('Y-m-d H:i:s', strtotime($cdr_call->calldate) + $cdr_call->duration));
                $call->Duration = $cdr_call->duration;
                $call->BeforeConnectionTime = $cdr_call->duration - $cdr_call->billsec;
                $call->TalkTime = $cdr_call->billsec;
                $call->HoldTime = 0;
                $this->SetCallInfo($call);
                $talktime_greater_than_0 = $call->TalkTime > 0;
                if ($talktime_greater_than_0 && !empty($DIDId) && $call->DirectionId == BPM_DirectionInID) {
                   $call->UsrDestinationNumberDIDId = $DIDId;
                }
                $callId = $this->ExportCall($call);
                if (!empty($callId) && $missed == 0) {
                   $path = $this->GetFilePath($cdr_call);
                   if (!empty($path)) {
                      $call_file = new CallFile();
                      //if ($talktime_greater_than_0) {
                      $call_file->_path = $path;
                      $call_file->CallId = $callId;
                      $call_file->Size = filesize($path);
                      $this->CopySysColumnValues($call, $call_file);
                      $this->ExportCallFile($call_file);
                      //} else {
                      //$this->LogWrite("Время разговора равно 0, файл не загружен. Идентификатор звонка: {$call->IntegrationId}, файл: {$path}");
                      //}
                   }  
                }
             } else {
                if ($missed == 0) {
                   $talktime_greater_than_0 = $existing_call->TalkTime > 0;
                   if ($talktime_greater_than_0 && $existing_call->UsrDirectionId == BPM_DirectionInID && !empty($DIDId) && $existing_call->UsrDestinationNumberDIDId != $DIDId) {
                      $fields = array("UsrDestinationNumberDIDId" => $DIDId);
                      $json = json_encode($fields);
                      $this->UpdateEntity("Call", $existing_call->Id, $json);
                   }
                   if (!$existing_call->FileExists) {
                      $path = $this->GetFilePath($cdr_call);
                      if (!empty($path)) {                     
                         //if ($talktime_greater_than_0) {
                         $call_file = new CallFile();
                         $call_file->_path = $path;
                         $call_file->CallId = $existing_call->Id;
                         $call_file->Size = filesize($path);
                         $this->CopySysColumnValues($existing_call, $call_file);
                         $this->ExportCallFile($call_file);
                         //} else {
                         //$this->LogWrite("Время разговора равно 0, файл не загружен. Идентификатор звонка: {$existing_call->IntegrationId}, файл: {$path}");
                         //}
                      }
                   }  
                }              
             }
             //if ($talktime_greater_than_0 || $missed == 1) {
             $processed_calls[] = $cdr_call->uniqueid;
             //}             
          }
       }
       
       function GetCalledIdFromChannel($channel) {
          if(preg_match("/SIP\/([0-9]*)-/", $channel, $matches)) {
             return str_replace("-", "", str_replace("SIP/", "", $matches[0]));
          }
          return "";
       }
       
       function ParseDID($clid) {
          if (preg_match('/\"(.*?)\"/', $clid, $match) == 1) {
             return preg_replace('/[^0-9]/', '', $match[1]);
          }
          return "";
       }
       
       function ExportCall($call) {
          if ($call->IntegrationId > 250) {
             $call->IntegrationId = substr($call->IntegrationId, 0, 233); // (18 * 13 - 1) урезаем, так как поле вмещает 250 символов, в 250 помещается 13 uniqueid длинной 17 c разделителем ';'
          }
          foreach($call->_links AS $name=>$value) {
             if (!empty($value)) {
                $call->$name = $value;
             }
          }
          unset($call->Id);
          $this->UnsetNonColumnAttributes($call);
          $json = json_encode($call);
                        $this->LogWrite("Json CreateEntity: {$json}" . " (" . __METHOD__ . ")");
          $created_entity = $this->CreateEntity("Call", $json);
          if (empty($created_entity)) {
             $this->LogWrite("Ошибка добавления звонка. Json: {$json}" . " (" . __METHOD__ . ")");
             return "";
          }
          return $created_entity->Id;
       }
       
       function ExportCallFile($call_file) {
          $path = $call_file->_path;
          $call_file->Name = htmlspecialchars(basename($path));
          $call_file->TypeId = BPM_FileLinkTypeID;
          if (EXPORT_CALL_FILE) {
             $call_file->TypeId = BPM_FileTypeID;
          }
          unset($call_file->Id);
          $this->UnsetNonColumnAttributes($call_file);

          $json = json_encode($call_file);
          
          
          // $call_id = $json['CallId'];
          $call_id = $call_file->CallId;
          $this->LogWrite("call_id, path, json in ExportCallFile {$call_id}, {$path}, {$json}");

          $command = "/usr/bin/python3 /usr/share/nginx/html/cdr_sync_for_creatio/upload_call.py {$call_id} {$path}";
          $output = shell_exec($command);
          $this->LogWrite("output in ExportCallFile {$output}");

          // $created_entity = $this->CreateEntity("CallFile", $json);
          // if (empty($created_entity)) {
          // $this->LogWrite("Ошибка добавления файла звонка. Json: {$json}" . " (" . __METHOD__ . ")");
          // return "";
          // }
          // if (EXPORT_CALL_FILE) {
          //     $this->ExportCallFileData($path, $created_entity->Id, $call_file->Size);
          // }
       }
       
       function ExportCallFileData($path, $id, $size) {
          $this->LogWrite("Path, id, size in ExportCallFileData {$path}, {$id}, {$size}");
          $url = BPM_Url . BPM_ServiceAction . "CallFile({$id})/Data";
          $this->LogWrite("url in ExportCallFileData {$url}");
          $mime_type = "audio/mpeg";
          $handle = fopen($path, "r");
          $data = fread($handle, $size);
          fclose($handle);
          $headers = $this->GetHeaders($size, "application/octet-stream;odata=verbose", $mime_type);
          $headers[] = "binaryStringRequestBody: true";
          $ch = curl_init($url);        
          curl_setopt($ch, CURLOPT_VERBOSE, 1);
          curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
          curl_setopt($ch, CURLOPT_COOKIEFILE, BPM_CookieFileName);
          curl_setopt($ch, CURLOPT_COOKIEJAR, BPM_CookieFileName);
          curl_setopt($ch, CURLOPT_POSTFIELDS, $data); 
          curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
          curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
          curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
          curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
          $response = curl_exec($ch);
          if ($response === false) {
             $this->LogWrite("Ошибка отправки файла в Creatio: " . curl_error($ch) . " (" . __METHOD__ . ")");
             curl_close($ch);
             return "";
          }
          $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
          if ($http_code != 201 && $http_code != 200) {
             $this->LogWrite("Ошибка добавления файла в Creatio: " . $http_code . " (" . __METHOD__ . ")");
             curl_close($ch);
             return "";
          }
          curl_close($ch);
       }
       
       function GetFilePath($cdr_call) {
          $file_name = $cdr_call->recordingfile;
          if (empty($file_name)) {
             $file_name = $this->GetFilePathByUniqueId($cdr_call->uniqueid);
             if (empty($file_name)) {
                return "";
             }
          }
          $file_dir = FILE_DIR;
          $file_parts = explode("/", $file_name);
          $file_name = $file_parts[1];
          $new_file_name = str_replace('wav', 'mp3', $file_name);
          $cdr_call->recordingfile = $_new_file_name;
          $file_path = exec("find {$file_dir} -type f -name '{$new_file_name}'");
          if (!file_exists($file_path)) {
                $error_code = ERROR_CODE_02;
                $this->LogWrite("Error exporting call file ({$error_code}). File name: {$file_dir}/{$new_file_name}" . " (" . __METHOD__ . ")");
                return "";
          }
          return $file_path;
       }
       
       function GetFilePathByUniqueId($uniqueid) {
          $sql = "SELECT recordingfile 
             FROM cdr
             WHERE uniqueid = '{$uniqueid}'
                and recordingfile != ''
             ORDER BY calldate DESC
             LIMIT 1";
          $cdr_call = $this->DB->query($sql)->fetch(PDO::FETCH_OBJ);
          if (!$cdr_call) {
             return "";
          }
          return $cdr_call->recordingfile;
       }
       
       function SetCallInfo(&$call) {
          $call->DirectionId = (strlen($call->CallerId) <= BPM_InternalPhoneNumberMaxLen ? BPM_DirectionOutID : BPM_DirectionInID);
          if ($call->_missed == 0) {
             $call->Caption = ($call->DirectionId == BPM_DirectionOutID ? BPM_CaptionOut : BPM_CaptionIn) . ": " . $call->CallerId . "->" . $call->CalledId;
          } else {
             $call->Caption = BPM_CaptionMissed . ": " . $call->CallerId . "->" . $call->CalledId;
          }        
          $call->CreatedById = $this->GetCallOwnerID($call);
          $call->ModifiedById = $call->CreatedById;
          $call->_links = $this->GetCallLinks($call);
       }     
       
       function GetCallOwnerID($call) {
          $owner_id = BPM_DefaultOwnerID;
          $phone = ($call->DirectionId == BPM_DirectionOutID ? $call->CallerId : $call->CalledId);
          if (empty($phone)) {
             return $owner_id;
          }
          $filter = "Number eq '$phone' and (CommunicationType/Id eq " . BPM_CommunicationTypeInternalID .
             " or CommunicationType/Id eq " . BPM_CommunicationTypeWorkID . ")";
          
          $communications = $this->GetEntities('ContactCommunication', $filter);
          if (!is_array($communications) || empty($communications)) {
              return $owner_id;
          }        
          return $communications[0]->ContactId;
       } 
       
       function GetCallLinks($call) {
          $links = array('ContactId' => '', 'AccountId' => '', 'LeadId' => '');
          $phone = ($call->DirectionId == BPM_DirectionOutID ? $call->CalledId : $call->CallerId);
          $expand = array('Contact($expand=Account($select=Id))');
          $orderby = array('Contact/CreatedOn desc');
          $select = array('ContactId');
          if (strlen($phone) < 10) {
             $is_internal_call = true;
             $filter = "Number eq '$phone' and (CommunicationType/Id eq " . BPM_CommunicationTypeInternalID .
                " or CommunicationType/Id eq " . BPM_CommunicationTypeWorkID . ")";
          } else {
             $is_internal_call = false;
             $search_number = substr(strrev($phone), 0, 10);
             $filter = "startswith(SearchNumber, '$search_number')";
          }  
          
          $communications = $this->GetEntities('ContactCommunication', $filter, $select, $expand, $orderby);
          if (is_array($communications) && !empty($communications)) {
             $links['ContactId'] = $communications[0]->ContactId;
             if ($communications[0]->Contact->Account->Id != self::$GUID_NULL) {    
                $links['AccountId'] = $communications[0]->Contact->Account->Id;
             }              
             return $links;
          }
          
          if (!$is_internal_call) {
             $expand = array();
             $orderby = array('CreatedOn desc');             
             $select = array('AccountId');
             $communications = $this->GetEntities('AccountCommunication', $filter, $select, $expand, $orderby);
             if (is_array($communications) && !empty($communications)) {
                $links['AccountId'] = $communications[0]->AccountId;
                return $links;
             }
             if (SEARCH_LEAD) {
                $filter = "startswith(BusinesPhoneSearchNumber,'{$search_number}') or startswith(MobilePhoneSearchNumber,'{$search_number}')";
                $select = array('Id');
                $leads = $this->GetEntities('AprLeadView', $filter, $select);
                if (is_array($leads) && !empty($leads)) {
                   $links['LeadId'] = $leads[0]->Id;
                   return $links;
                }
             }
          }  
          return $links;
       }
       
       function GetDestinationNumberDIDLookup() {
          $DIDs = array();
          $select = array('Id', 'Description');
          $records = $this->GetEntities('UsrDestinationNumberDIDLookup', "", $select);
          if (!is_array($records)) {
             return $DIDs;
          }
          foreach($records as $record) {
             if (array_key_exists($record->Description, $DIDs)) {
                continue;
             }
             $DIDs[$record->Description] = $record->Id;
          }
          return $DIDs;
       }
       
       function CreateEntity($entity_name, $json) {
          $url = BPM_Url . BPM_ServiceAction . $entity_name;
          $headers = $this->GetHeaders(strlen($json));
          $ch = curl_init($url);
          curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
          curl_setopt($ch, CURLOPT_COOKIEFILE, BPM_CookieFileName);
          curl_setopt($ch, CURLOPT_COOKIEJAR, BPM_CookieFileName);
          curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
          curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
          curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
          curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
          curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
          $response = curl_exec($ch);
          if ($response === false) {
             $this->LogWrite("Ошибка отправки данных в Creatio: " . curl_error($ch) . " (" . __METHOD__ . "); url: " . $url);
             curl_close($ch);
             return "";
          }
          $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
          if ($http_code != 201) {
             $this->LogWrite("Ошибка добавления записи в Creatio: " . $http_code . " (" . __METHOD__ . "); url: " . $url);
             curl_close($ch);
             return "";
          }
          curl_close($ch);
          return json_decode($response);
       }
       
       function UpdateEntity($entity_name, $id, $json) {
          $url = BPM_Url . BPM_ServiceAction. $entity_name . "({$id})";
          $headers = $this->GetHeaders(strlen($json));
          $ch = curl_init($url);
          curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PATCH");
          curl_setopt($ch, CURLOPT_COOKIEFILE, BPM_CookieFileName);
          curl_setopt($ch, CURLOPT_COOKIEJAR, BPM_CookieFileName);
          curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
          curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
          curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
          curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
          curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
          $response = curl_exec($ch);
          if ($response === false) {
             $this->LogWrite("Ошибка отправки данных в Creatio: " . curl_error($ch) . " (" . __METHOD__ . "); url: " . $url);
             curl_close($ch);
             return "";
          }
          $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
          if ($http_code != 204 && $http_code != 201 && $http_code != 200) {
             $this->LogWrite("Ошибка обновления записи в Creatio: " . $http_code . " (" . __METHOD__ . "); url: " . $url);
             curl_close($ch);
             return "";
          }
          curl_close($ch);
       }
       
       function GetEntities($entity_name, $filter = '', $select = array(), $expand = array(), $orderby = array()) {
          $url = BPM_Url . BPM_ServiceAction . $entity_name;
          $headers = $this->GetHeaders();
          $delimeter = '?';
          if (!empty($filter)) {
             $url .= '?$filter=' . urlencode($filter);
             $delimeter = '&';
          }
          if (count($select) > 0) {
             $url .= $delimeter . '$select=' . urlencode(implode(',', $select));
             $delimeter = '&';
          }
          if (count($expand) > 0) {
             $url .= $delimeter . '$expand=' . urlencode(implode(',', $expand));
             $delimeter = '&';
          }
          if (count($orderby) > 0) {
             $url .= $delimeter . '$orderby=' . urlencode(implode(',', $orderby));
             $delimeter = '&';
          }
          $url .= $delimeter . '$top=5000';
          $ch = curl_init($url);
          curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
          curl_setopt($ch, CURLOPT_COOKIEFILE, BPM_CookieFileName);
          curl_setopt($ch, CURLOPT_COOKIEJAR, BPM_CookieFileName);
          curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
          curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
          curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
          curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
          $response = curl_exec($ch);
          if ($response === false) {
             $this->LogWrite("Ошибка отправки данных в Creatio: " . curl_error($ch) . " (" . __METHOD__ . "); url: " . $url);
             curl_close($ch);
             return "";
          }
          $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
          if ($http_code != 200) {
             $this->LogWrite("Ошибка отправки данных в Creatio: " . $http_code . " (" . __METHOD__ . "); url: " . $url);
             curl_close($ch);
             return "";
          }
          curl_close($ch);
          return json_decode($response)->value;
       }
       
       function UnsetNonColumnAttributes(&$object) {
          foreach ($object as $key => $value) {
             if (substr($key, 0, 1) == "_") {
                unset($object->$key);
             }
          }
       }
       
       function CopySysColumnValues($source, &$dest) {
          $source->CreatedOn = $dest->CreatedOn;
          $source->CreatedById = $dest->CreatedById;
          $source->ModifiedOn = $dest->ModifiedOn;
          $source->ModifiedById = $dest->ModifiedById;
       }
       
       function GetHeaders($content_length = 0, $accept = "application/json;odata=verbose", $content_type = "application/json") {
          $cookies = $this->ExtractCookies();
          $headers = array();
          $headers[] = 'Accept: ' . $accept;
          $headers[] = 'Content-Type: ' . $content_type;
          if ($content_length > 0) {
             $headers[] = 'Content-Length: ' . $content_length;
          }
          if (isset($cookies['BPMCSRF'])) {
             $headers[] = 'BPMCSRF: ' . $cookies['BPMCSRF']['value'];
          }
          if (isset($cookies['BPMSESSIONID'])) {
             $headers[] = 'BPMSESSIONID: ' . $cookies['BPMSESSIONID']['value'];
          }
          return $headers;
       }
       
       function GetFormatedDate($date, $use_offsets = true) {
          $time = strtotime($date);
          if ($use_offsets) {
             $time += CALL_DATE_OFFSET * 60 * 60 + BPM_TimeZoneOffset * 60;
          }
          return str_replace('&&', 'T', date('Y-m-d&&H:i:s', $time)) . 'Z';
       }
       
       function GenGUID() {
          if (function_exists('com_create_guid') === true) {
             return trim(com_create_guid(), '{}');
          }
          return sprintf('%04X%04X-%04X-%04X-%04X-%04X%04X%04X', mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(16384, 20479), mt_rand(32768, 49151), mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535));
       }
       
       function ConnectToDB() {
          try {
             $db = new PDO("mysql:host=" . DBHOST . ";dbname=" . DBNAME, DBUSER, DBPASS);
             $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
             $db->exec("set names ".DEFAULTCHARSET);
             $this->DB = $db;
             echo "Connected to Mysql: " . date("Y-m-d H:i:s") . "<br>";
             return true;
          } catch(PDOException $e) {
             $this->LogWrite($e->getMessage() . " (" . __METHOD__ . ")");
             return false;
          }
       }
       
       function LogWrite($text) {
          $data = date('Y-m-d H:i:s') . ": " . $text . PHP_EOL;
          $fp = fopen('error_log.txt', 'a');
          fwrite($fp, $data);
          fclose($fp);
       }
       
       function ExtractCookies() {
          $lines = file(BPM_CookieFileName, FILE_IGNORE_NEW_LINES);
          $cookies = array();
          foreach ($lines as $line) {
             $cookie = array();
             if (substr($line, 0, 10) == '#HttpOnly_') {
                $line = substr($line, 10);
                $cookie['httponly'] = true;
             } else {
                $cookie['httponly'] = false;
             }
             if( strlen( $line ) > 0 && $line[0] != '#' && substr_count($line, "\t") == 6) {
                $tokens = explode("\t", $line);
                $tokens = array_map('trim', $tokens);
                $cookie['domain'] = $tokens[0];
                $cookie['flag'] = $tokens[1];
                $cookie['path'] = $tokens[2];
                $cookie['secure'] = $tokens[3];
                $cookie['expiration-epoch'] = $tokens[4];
                $cookie['name'] = urldecode($tokens[5]);
                $cookie['value'] = urldecode($tokens[6]);
                $cookie['expiration'] = date('Y-m-d h:i:s', $tokens[4]);
                $cookies[$cookie['name']] = $cookie;
             }
          }
          return $cookies;
       }
    }
?>


Report Page