Skip to content

Instantly share code, notes, and snippets.

@morwin10
Created July 5, 2018 10:11
Show Gist options
  • Save morwin10/fb05e98ac6ca7ba93794b27fc0126ee5 to your computer and use it in GitHub Desktop.
Save morwin10/fb05e98ac6ca7ba93794b27fc0126ee5 to your computer and use it in GitHub Desktop.
<?php
if (!headers_sent()) {
header('Content-Type: text/html');
}
error_reporting(E_ALL);
ini_set('default_socket_timeout', 6000);
ini_set('session.gc_maxlifetime', 60*60*22); //22h
ini_set('display_errors', 'On');
ini_set('display_startup_errors', 'On');
ini_set('max_execution_time', 3600); //300 seconds = 5 minutes
ini_set("request_terminate_timeout", 3600);
ini_set('memory_limit', '3G');
set_time_limit(0);
ignore_user_abort(true);
date_default_timezone_set("Asia/Jerusalem");
file_put_contents('time.txt', date( "d/m/Y H:i:s" ,time() ) . PHP_EOL, FILE_APPEND);
require_once '../wp-load.php';
require_once '../wp-admin/includes/media.php';
require_once '../wp-admin/includes/file.php';
require_once '../wp-admin/includes/image.php';
Class CronJob {
public static $arr_new_pics = [];
public static $arr_new_properies = [];
public static $arr_old_pics = [];
public static $arr_old_properies = [];
public static $arr_of_users = [];
public static $db;
public static $new_xml;
public static $old_xml;
public static $all_new_prperties;
public static function start() {
self::get_new_xml();
if (file_exists('old_xml.xml')) {
self::$old_xml = simplexml_load_string( file_get_contents('old_xml.xml') );
// if ( self::$old_xml->asXml() == self::$new_xml->asXml() ) die('two xml Files are equal! evrithing OK!');
}
if (file_exists('arr_old_properies.txt')) {
self::$arr_old_properies = unserialize(file_get_contents('arr_old_properies.txt'));
}
if (file_exists('arr_old_pics.txt')) {
self::$arr_old_pics = unserialize(file_get_contents('arr_old_pics.txt'));
}
self::check_for_updates();
}
public static function check_for_updates() {
if (self::$all_new_prperties) {
foreach(self::$all_new_prperties as $new_property) {
$serial = (int) $new_property->serial;
echo "<br>SER: <span style='color: darkred'>$serial<span> "; // html
self::clear_property($new_property);
if(self::property_need_to_set($new_property, $serial)){
self::set_property($new_property, $serial);
}
if(isset(self::$arr_new_properies["$serial"])) {
$post_id = self::$arr_new_properies["$serial"];
$arr_ids_pic = self::check_and_inserting_pics($serial, $post_id);
if($arr_ids_pic) self::insert_meta_pic($arr_ids_pic, $post_id);
}
}
} else {
echo 'אין נכסים חדשים';
}
}
public static function get_values_meta($meta, $id) {
$str = '';
if (is_array($meta) || is_object($meta))
{
foreach ((array) $meta as $key => $val)
{
$str .= " ($id, '$key', '$val') , \n";
}
}
return rtrim($str, ", \n");
}
public static function clear_property(&$property) {
unset($property->gishaYN, $property->startdate, $property->lastdate, $property->removal, $property->front);
return $property;
}
public static function property_need_to_set($new_property, $serial){
$old_property;
if($new_property->mainaction == 'מכירה' && !self::check_if_has_pic($serial) ) return false;
// לדלג אם הנכס קיים ומעודכן
if(isset(self::$old_xml) && $old_property = self::get_propertie_by_serial($serial, self::$old_xml)) {
if(!empty(self::$arr_old_properies) && isset(self::$arr_old_properies["$serial"])) {
self::clear_property($old_property);
if($old_property->asXml() == $new_property->asXml()){
self::$arr_new_properies["$serial"] = self::$arr_old_properies["$serial"];
return false;
}
}
}
return true;
}
//
public static function set_property($new_property, $serial) {
$post_id = isset(self::$arr_old_properies["$serial"]) ? self::$arr_old_properies["$serial"] : 0;
$arr_of_data_property = self::parse_property($new_property);
$post_id = self::insert_or_update_property($arr_of_data_property, $post_id , $serial);
self::$arr_new_properies["$serial"] = $post_id ;
return $post_id;
}
public static function insert_meta_pic($ids, $post_id) {
$sql = "DELETE FROM `el_postmeta` WHERE (`post_id`,`meta_key`) IN (($post_id,'_thumbnail_id') ,($post_id,'ANG_img-gallery'));";
$values = self::get_values_meta_pic($ids, $post_id);
$sql .= "INSERT INTO `el_postmeta`(`post_id`, `meta_key`, `meta_value`) VALUES $values";
$db = self::db();
$stmt = $db->prepare($sql);
$stmt->execute();
}
public static function get_values_meta_pic($ids, $post_id) {
$str = '';
foreach ($ids as $id) {
$str .= " ($post_id, 'ANG_img-gallery', '$id') ,";
}
$str .= "($post_id, '_thumbnail_id', '$ids[0]')";
return $str;
}
public static function check_and_inserting_pics($serial, $post_id = 0) { // post id 0 for new; | update
$all_pics = self::get_pictures_by_serial($serial);
if ($all_pics) {
$arr_of_inserting_pic = [];
$i;
foreach($all_pics as $pic) {
$i;
$picID = (int) $pic->picID;
if(!$i = self::check_pic($picID)){
$id = self::insert_pic($pic, $post_id);
self::$arr_new_pics["$picID"] = $id;
$arr_of_inserting_pic[] = $id;
continue;
}
self::$arr_new_pics["$picID"] = $i;
}
return $arr_of_inserting_pic;
}
return false;
}
public static function parse_property ($property) {
$arr = [ 'html' => '', 'rel' => '', 'post' => [], 'meta' => [] ]; // html <div> first if true return it
foreach($property as $key => $value) {
$value = (string) $value;
if(( !$value && $key != 'comments2' ) ) continue;
switch ($key) {
case 'city':
$rel = ($value) == 'אלעד' ? ($property->mainaction == 'מכירה') ? '10' : '11' : '12';
$rel = ( preg_match('/מגרשים|עסקים/', $property->mainaction) ) ? '18' : $rel;
$arr["meta"]["property_address_suburb"] = $value;
$arr["rel"] = $rel;
// unset($property->mainaction);
break;
case 'agent':
$arr['post']["post_author"] = self::get_user_id($value);
// $arr['html'] .= "<b class='cron_info_agent'>סוכן: </b> <span style='color: black;'>$value</span> <br>";
break;
case 'serial':
$arr['post']["post_title"] = $value;
$arr['post']["post_name"] = $value;
break;
case 'floor':
if($value == 0) continue;
$arr['meta']["property_year_built"] = ($value == 1) ? 'ראשונה' : $value;
break;
case 'priceshekel':
$ar = ($property->mainaction == 'השכרה') ? ['property_rent', 'property_rent_display'] : ["property_price", "property_price_display"];
$price = number_format((float)$value);
$arr['meta'][ $ar[0] ] = $price;
$arr['meta'][ $ar[1] ] = 'yes';
$arr['meta']["property_price_view"] = $price;
$arr['meta']["property_price"] = $price;
break;
case 'mirpesetShemeshYN':
if ($value != 'true') continue;
$arr['meta']["property_balcony"] = 'yes';
break;
case 'comments2': // old prop && up or ins
$arr['post']["post_content"] = $value;
break;
case 'mamadYN':
if ($value != 'true') continue;
$arr['html'] .= "<b class='cron_info_mamadYN'>חדר ממ''ד: </b> <span style='color: black;'>יש</span> <br>";
break;
case 'soragimYN':
if ($value != 'true') continue;
$arr['meta']["property_workshop"] = 'yes';
break;
case 'machsanYN':
if ($value != 'true') continue;
$arr['meta']["property_shed"] = 'yes';
break;
case 'meshupatsYN':
if ($value != 'true') continue;
$arr['html'] .= "<b class='cron_info_meshupatsYN'>משופצת: </b> <span style='color: black;'>כן</span><br>";
break;
case 'objecttype':
$arrObjecttype = ['קוטג' => 'Flat', 'דירת גן' => 'AcreageSemi-rural', 'דירה' => 'Apartment', 'יח. דיור' => 'Unit' , 'פנטהאוס' => 'Retirement', 'חנות' => 'Other', 'מחסן' => 'Warehouse', 'משרד' => 'Unit', 'ד.גג' => 'Townhouse', 'דופלקס' => 'Alpine', 'וילה' => 'Villa', 'בית' => 'House'];
$a = explode('/', $value);
$d = 'Apartment';
if( preg_match('/חנות|משרד|מחסן/', $value ) ) $arr['html'] .= "<b class='cron_info_objecttype'>נכס: </b> <span style='color: black;'>חנות</span><br>";
foreach ($a as $v) {
if( isset($arrObjecttype[$v])) $d = $arrObjecttype[$v]; break;
}
$arr['meta']["property_category"] = $d;
break;
case 'floors':
if ($value < 2) continue;
$arr['html'] .= "<b class='cron_info_floors'>קומות בבניין: </b> <span style='color: black;'>$value</span> <br>";
break;
case 'lift':
if($value != 'כן' ) continue;
$arr['meta']["property_study"] = "yes";
break;
case 'street':
$arr['meta']["property_address_street"] = $value;
$arr['meta']["property_address_display"] = 'yes';
break;
case 'builtsqmr':
$arr['meta']["property_bedrooms"] = $value;
break;
case 'room':
$arr['meta']["property_rooms"] = $value;
break;
case 'shcuna':
$arr['html'] .= "<b class='cron_info_shcuna'>שכונה: </b> <span style='color: black;'>$value</span><br>";
break;
case 'fieldsqmr':
$arr['html'] .= "<b class='cron_info_fieldsqmr'>שטח מגרש: </b> <span style='color: black;'>$value</span> <br>";
break;
case 'park':
$arr['html'] .= "<b class='cron_info_park'>חניה: </b> <span style='color: black;'>$value</span> <br>";
break;
case 'kitchen':
$arr['html'] .= "<b class='cron_info_kitchen'>מטבח: </b> <span style='color: black;'>$value</span> <br>";
break;
case 'toilet':
$arr['html'] .= "<b class='cron_info_toilet'>שרותים: </b> <span style='color: black;'>$value</span> <br>";
break;
case 'a_c':
$arr['html'] .= "<b class='cron_info_a_c'>מזגן: </b> <span style='color: black;'>$value</span> <br>";
break;
case 'boiler':
$arr['html'] .= "<b class='cron_info_boiler'>בוילר: </b> <span style='color: black;'>$value</span> <br>";
break;
case 'ginasqmr':
$arr['html'] .= "<b class='cron_info_ginasqmr'>גינה מ''ר: </b> <span style='color: black;'>$value</span> <br>";
break;
case 'rihut':
$arr['html'] .= "<b class='cron_info_rihut'>ריהוט: </b> <span style='color: black;'>$value</span> <br>";
break;
case 'tkufa':
$arr['html'] .= "<b class='cron_info_tkufa'>תקופת השכרה: </b> <span style='color: black;'>$value</span> <br>";
break;
case 'iska':
$arr['html'] .= "<b class='cron_info_iska'>להשכרה / למכירה: </b> <span style='color: black;'>$value</span> <br>";
break;
default:
continue;
}
}
$content = isset($arr['post']['post_content']) ? $arr['post']['post_content'] : '';
$h3_serial = "<p style='direction: ltr;color: rgb(139, 165, 100);text-shadow: 2px 1px 13px rgb(255, 97, 46);padding-bottom: 10px;'>מס' נכס: $property->serial </p>";
$arr['post']['post_content'] = "$h3_serial $content ";
if(!empty($arr['html'])) $arr['post']['post_content'] .= "<div class='cron_info' style='color: #af1ab3;'>" . $arr['html'] . "</div>";
unset($arr['html']);
return $arr;
}
public static function insert_or_update_property($arr_of_data_property, $post_id = 0, $serial = '') {
if(!empty($arr_of_data_property['post'])) {
$arr['ID'] = $post_id;
$arr['post_author'] = ( isset($arr_of_data_property['post']["post_author"]) ) ? $arr_of_data_property['post']["post_author"] : 2;
$arr['post_title'] = (string) $serial;
// echo "title: " . $arr_of_data_property['post_title'] . "<br>";
$arr['post_content'] = $arr_of_data_property['post']['post_content'];
$arr['post_status'] = 'publish';
$arr['ping_status'] = 'closed';
$arr['comment_status'] = 'closed';
$arr['post_type'] = isset($arr_of_data_property['rel']) && $arr_of_data_property['rel'] == 11 ? 'rental' : ($arr_of_data_property['rel'] == 18 ? 'business' : 'property');
// echo "REL: {$arr_of_data_property['rel']} <br>";
echo "fun: <span style='color: red'>wp_insert_post<span>"; // HTML
$post_id = wp_insert_post( $arr );
self::$arr_new_properies["$serial"] = $post_id;
// echo "<pre>postID: $post_id</pre>";
}
if(!empty($arr_of_data_property['rel'])) {
$rel = $arr_of_data_property['rel'];
echo "fun: <span style='color: red'>DELETE el_term_relationships<span>"; // HTML
$sql = "DELETE FROM `el_term_relationships` WHERE `object_id` = $post_id; INSERT INTO `el_term_relationships` (`object_id`, `term_taxonomy_id`) VALUES ($post_id, $rel)" ;
$db = self::db();
$stmt = $db->prepare($sql);
$stmt->execute();
}
if(!empty($arr_of_data_property['meta'])) {
$sql_meta = "DELETE FROM `el_postmeta` WHERE `post_id` = $post_id AND `meta_key` LIKE 'prop%';";
$meta = self::get_values_meta($arr_of_data_property['meta'], $post_id);
$sql_meta .= "INSERT INTO `el_postmeta`(`post_id`, `meta_key`, `meta_value`) VALUES $meta";
$db = self::db();
$stmt = $db->prepare($sql_meta);
echo "fun: <span style='color: red'>INSERT el_postmeta<span>"; // HTML
$stmt->execute();
}
return $post_id;
}
public static function get_user_id($user_name) {
$user_id = 2;
if(empty(self::$arr_of_users)) {
$db = self::db();
$stmt = $db->prepare("SELECT `ID`, `display_name` FROM `el_users`");
echo "fun: <span style='color: red'>userid<span>"; // HTML
$stmt->execute();
$res = $stmt->fetchAll(PDO::FETCH_ASSOC);
$arr = [];
foreach ($res as $key => $val) {
$arr[explode(' ', $val['display_name'])[0]] = $res[$key]['ID'];
}
self::$arr_of_users = $arr;
}
$agents = preg_split("/[\s\,]+/u", $user_name);
foreach ($agents as $key => $agent) {
if(!empty(self::$arr_of_users) && isset(self::$arr_of_users[$agent])) {
$user_id = self::$arr_of_users[$agent];
}
}
return $user_id;
}
// false== insert
public static function check_pic($pic_id) {
if( isset(self::$arr_old_pics) && isset(self::$arr_old_pics["$pic_id"]) ) {
return self::$arr_old_pics["$pic_id"];
}
return false;
}
public static function insert_pic($pic, $post_id = 0) {
$uploaddir = wp_upload_dir();
$uploadfile = $uploaddir['path'] . '/' . $pic->picID . '.jpg';
parse_str($pic->picurl, $url);
$url = str_replace($url['pic'], urlencode($url['pic']), $pic->picurl);
$contents= file_get_contents($url);
$savefile = fopen($uploadfile, 'w');
fwrite($savefile, $contents);
fclose($savefile);
$attachment = [
'post_mime_type' => 'image/jpeg',
'post_title' => $pic->picID,
'post_parent' => $post_id,
'post_type' => 'attachment',
'post_content' => '',
'post_status' => 'inherit'
];
echo "fun: <span style='color: red'>wp_insert_attachment<span>"; // HTML
$attach_id = wp_insert_attachment( $attachment, $uploadfile );
$imagenew = get_post( $attach_id );
$fullsizepath = get_attached_file( $imagenew->ID );
$attach_data = wp_generate_attachment_metadata( $attach_id, $fullsizepath );
echo "fun: <span style='color: red'> wp_update_attachment_metadata<span>"; // HTML
wp_update_attachment_metadata( $attach_id, $attach_data );
self::$arr_new_pics["$pic->picID"] = $attach_id;
return $attach_id;
}
public static function get_new_xml()
{
if(!isset(self::$new_xml)){
try {
$url = "http://webtiv.co.il/xml.aspx?clientguid=698WpRJdL9k%3d&agentsguid=Jb%2fMhO4aUtE%3d";
$output = file_get_contents($url);
self::$new_xml = simplexml_load_string($output);
self::$new_xml->asXML('temp_new_xml.xml');
self::$all_new_prperties = (self::$new_xml) ? self::$new_xml->xpath('/NewDataSet/Properties') : false;
} catch (Exception $ex) {
file_put_contents('log_curl_error', print_r($ex, true));
}
}
return self::$new_xml;
}
public static function get_propertie_by_serial ($serial, &$xml) {
$propertie = $xml->xpath("/NewDataSet/Properties/serial[.='$serial']/parent::*");
return $propertie ? $propertie[0] : false;
}
public static function check_if_has_pic( $serial) {
$serial = (int) $serial;
$pictures = self::$new_xml->xpath("//NewDataSet/pictures/picserial[.=$serial]/parent::*");
return $pictures ? $pictures : false;
}
public static function get_pictures_by_serial ($serial) {
$Pictures = self::$new_xml->xpath("//NewDataSet/pictures/picserial[.=$serial]/parent::*");
return $Pictures ? $Pictures : false;
}
public static function db(){
if(!isset(self::$db)) {
try {
$dsn = 'mysql:host=127.0.0.1;dbname=**********;charset=utf8';
$db = new PDO($dsn, '*****', '*****');
self::$db = $db;
} catch (Exception $ex) {
echo 'Failed: ' . $ex->getMessage();
}
}
return self::$db;
}
public static function delete(){
if(!empty(self::$arr_old_properies)) {
$property_for_del = array_diff_assoc(self::$arr_old_properies, self::$arr_new_properies);
if($property_for_del) {
$str = implode(",", array_values($property_for_del));
$sql = "DELETE FROM `el_posts` WHERE `ID` IN($str); DELETE FROM `el_postmeta` WHERE `post_id` IN($str); DELETE FROM `el_term_relationships` WHERE`object_id` IN($str); ";
$stmt = self::db()->prepare($sql);
$stmt->execute();
}
}
if(!empty(self::$arr_old_pics)) {
$pic_for_del = array_diff_assoc(self::$arr_old_pics, self::$arr_new_pics);
if($pic_for_del) {
foreach ($pic_for_del as $idPic) {
wp_delete_attachment( $idPic, true );
}
}
}
}
public static function finish(){
file_put_contents('arr_old_properies.txt', serialize(self::$arr_new_properies));
file_put_contents('arr_old_pics.txt', serialize(self::$arr_new_pics));
rename("temp_new_xml.xml", "old_xml.xml");
}
}
CronJob::start();
CronJob::delete();
CronJob::finish();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment