PHP
1
Вклад в тег
protected static $apiURL = 'http://services.ukrposhta.com/barcodestatistic/Default.aspx';
public static function updateTrackingInfo($sendEmail = false) {
Yii::import('application.lib.simpleHtmlDom.*');
$packages = Tracking::model()->findAll();
if (empty($packages)) {
return;
}
$ttns = array();
$ttnsObj = array();
foreach ($packages as $package) {
$ttns[] = $package->tr_num;
$ttnsObj[$package->tr_num] = $package;
}
$result = self::uploadTTNs($ttns);
if(empty($result)){
return;
}
$html = new simple_html_dom();
$html->load($result);
$rows = $html->find('#ctl00_centerContent_ListBarcodes tr');
foreach ($rows as $row) {
$trackNum = trim($row->find('td', 0)->plaintext);
$package = $ttnsObj[$trackNum];
if (!empty($trackNum) && !empty($package)) {
$status = trim($row->find('td', 3)->plaintext);
if ($status !== $package->last_status) {
$package->last_status = $status;
$package->last_update = time();
$package->notified = 0;
}
$package->save();
}
}
}
public static function uploadTTNs($ttns) {
if (0 === count($ttns))
return FALSE;
$fields = array(
'__VIEWSTATE' => array(
'content' => ''
),
'ctl00$centerContent$btnUpload' => array(
'content' => 'Пошук'
),
'ctl00$centerContent$fileUploadXmlBarcodes' => array(
'filename' => 'ttn.txt',
'type' => 'text/plain',
'content' => implode("\r\n", $ttns)
),
);
$data = '';
$delimiter = '-------------' . uniqid();
foreach ($fields as $name => $field) {
$data .= "--" . $delimiter . "\r\n";
$data .= 'Content-Disposition: form-data; name="' . $name . '"';
if (!empty($field['filename'])) {
$data.= '; filename="' . $field['filename'] . '"' . "\r\n";
$data .= 'Content-Type: ' . $field['type'];
}
$data .= "\r\n\r\n";
$data .= $field['content'] . "\r\n";
}
$data .= "--" . $delimiter . "--\r\n";
$handle = curl_init(self::$apiURL);
$options = array(
CURLOPT_USERAGENT => 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)',
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POSTFIELDS => $data,
CURLOPT_HTTPHEADER => array(
'Content-Type: multipart/form-data; boundary=' . $delimiter,
'Content-Length: ' . strlen($data))
);
curl_setopt_array($handle, $options);
$result = curl_exec($handle);
curl_close($handle);
return $result;
}