Advertisement
Guest User

Untitled

a guest
Jul 11th, 2017
132
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 55.25 KB | None | 0 0
  1. <?php
  2. /**
  3.  * Handling build of JSON data for database table row
  4.  * Updating cache column for table row
  5.  */
  6.  
  7. namespace App\libs;
  8.  
  9. use App\Model\Exceptions\DatabaseCacheUpdateException;
  10. use App\Web\Paths;
  11. use Symfony\Component\Config\Definition\Exception\Exception;
  12.  
  13. class DatabaseCacheManager
  14. {
  15.  
  16.     const DB_USER = "gloffer_test";
  17.     const DB_PASSWORD = "GlofferTest2015";
  18.     const DB_DATABASE = "gloffer";
  19.  
  20.     const DB_CACHE_USER = "gloffer_test";
  21.     const DB_CACHE_PASSWORD = "GlofferTest2015";
  22.     const DB_CACHE_DATABASE = "gloffer_cache";
  23.  
  24.     const STORE_TYPE = "single";
  25.  
  26.     /**
  27.      * @var \mysqli
  28.      */
  29.     private $dbConnection;
  30.  
  31.     /**
  32.      * @var \mysqli
  33.      */
  34.     private $dbConnectionCache;
  35.  
  36.  
  37.     /**
  38.      * @var string
  39.      */
  40.     private $type;
  41.  
  42.     /**
  43.      * @var int
  44.      */
  45.     private $id;
  46.  
  47.     /**
  48.      * @var bool
  49.      */
  50.     private $live_record;
  51.  
  52.     /**
  53.      * @var array
  54.      */
  55.     private $arrayData;
  56.  
  57.     /**
  58.      * @var bool
  59.      */
  60.     private $needRebuild;
  61.  
  62.  
  63.     private $serverAddress;
  64.  
  65.     private $serverAddressCache;
  66.  
  67.     public function __construct()
  68.     {
  69.         $this->live_record = FALSE;
  70.         $this->needRebuild = TRUE;
  71.         $this->arrayData = array();
  72.  
  73.  
  74.         if(isset($_SERVER["HTTP_HOST"]))
  75.         {
  76.             $this->serverAddress = $_SERVER["HTTP_HOST"] == "158.196.145.34" ? "localhost" : "158.196.145.34";
  77.         }
  78.         else
  79.         {
  80.             $this->serverAddress = "158.196.145.34";
  81.         }
  82.  
  83.         $this->serverAddressCache = "158.196.145.34";
  84.  
  85.         $this->dbConnection = mysqli_connect($this->serverAddress, self::DB_USER, self::DB_PASSWORD, self::DB_DATABASE);
  86.         if (mysqli_connect_errno()) {
  87.             //\Tracy\Debugger::log("Couldnt connect to database in DatabaseCacheManager.");
  88.             throw new \Exception("Couldn't connect to database");
  89.  
  90.         }
  91.  
  92.         mysqli_query($this->dbConnection, "SET character_set_client=utf8");
  93.         mysqli_query($this->dbConnection, "SET character_set_connection=utf8");
  94.         mysqli_query($this->dbConnection, "SET character_set_results=utf8");
  95.  
  96.         $this->dbConnectionCache = mysqli_connect($this->serverAddressCache, self::DB_CACHE_USER, self::DB_CACHE_PASSWORD, self::DB_CACHE_DATABASE);
  97.         if (mysqli_connect_errno()) {
  98.             //\Tracy\Debugger::log("Couldnt connect to database in DatabaseCacheManager.");
  99.             throw new \Exception("Couldn't connect to cache database");
  100.  
  101.         }
  102.  
  103.         mysqli_query($this->dbConnectionCache, "SET character_set_client=utf8");
  104.         mysqli_query($this->dbConnectionCache, "SET character_set_connection=utf8");
  105.         mysqli_query($this->dbConnectionCache, "SET character_set_results=utf8");
  106.     }
  107.  
  108.  
  109.     public function __destruct()
  110.     {
  111.         @$this->dbConnection->close();
  112.         @$this->dbConnectionCache->close();
  113.     }
  114.  
  115.     public function setHTTPHost($host)
  116.     {
  117.  
  118.     }
  119.  
  120.  
  121.     public function storeCache()
  122.     {
  123.         if($this->needRebuild) {
  124.             $this->buildJsonData();
  125.         }
  126.  
  127.        return $this->updateCache();
  128.     }
  129.  
  130.  
  131.     public function setPublished()
  132.     {
  133.         $query = "UPDATE cac_cache SET cache_status='published' WHERE cac_cache_type='$this->type' AND cac_cache_id='$this->id'";
  134.         $result = mysqli_query($this->dbConnectionCache, $query);
  135.  
  136.         if(mysqli_error($this->dbConnectionCache)) {
  137.             throw new \Exception("SetPublished [" . $this->id . "] query failed: " . mysqli_error($this->dbConnectionCache));
  138.         }
  139.  
  140.         return TRUE;
  141.     }
  142.  
  143.     public function setElastic()
  144.     {
  145.         $query = "UPDATE cac_cache SET cache_status='elastic' WHERE cac_cache_type='$this->type' AND cac_cache_id='$this->id'";
  146.         $result = mysqli_query($this->dbConnectionCache, $query);
  147.  
  148.         if(mysqli_error($this->dbConnectionCache)) {
  149.             throw new \Exception("setElastic [" . $this->id . "] query failed: " . mysqli_error($this->dbConnectionCache));
  150.         }
  151.  
  152.         return TRUE;
  153.     }
  154.  
  155.  
  156.     public function setWaiting()
  157.     {
  158.         $query = "UPDATE cac_cache SET cache_status='waiting' WHERE cac_cache_type='$this->type' AND cac_cache_id='$this->id'";
  159.         $result = mysqli_query($this->dbConnectionCache, $query);
  160.  
  161.         if(mysqli_error($this->dbConnectionCache)) {
  162.             throw new \Exception("SetWaiting[" . $this->id . "] query failed: " . mysqli_error($this->dbConnectionCache));
  163.         }
  164.  
  165.         return TRUE;
  166.     }
  167.  
  168.  
  169.     public function setError($cacheReport = NULL)
  170.     {
  171.         if($cacheReport == NULL)
  172.         {
  173.             $query = "UPDATE cac_cache SET cache_status = 'error', cache_report = $cacheReport WHERE cac_cache_type = '$this->type' AND cac_cache_id = $this->id";
  174.         }
  175.        else
  176.         {
  177.             $query =  sprintf("UPDATE cac_cache SET cache_status = 'error', cache_report = '%s' WHERE cac_cache_type = '%s' AND cac_cache_id = '%s'", mysqli_real_escape_string($this->dbConnection,$cacheReport), $this->type, $this->id);
  178.         }
  179.  
  180.         $result = mysqli_query($this->dbConnectionCache, $query);
  181.  
  182.         if(mysqli_error($this->dbConnectionCache)) {
  183.             throw new \Exception("SetError [" . $this->id . "] query failed: " . mysqli_error($this->dbConnectionCache));
  184.         }
  185.  
  186.         return TRUE;
  187.     }
  188.  
  189.     public function setReport($cacheReport)
  190.     {
  191.         $query =  sprintf("UPDATE cac_cache SET cache_report = '%s' WHERE cac_cache_type = '%s' AND cac_cache_id = '%s'", mysqli_real_escape_string($this->dbConnection,$cacheReport), $this->type, $this->id);
  192.  
  193.         $result = mysqli_query($this->dbConnectionCache, $query);
  194.  
  195.         if(mysqli_error($this->dbConnectionCache)) {
  196.             throw new \Exception("setReport [" . $this->id . "] query failed: " . mysqli_error($this->dbConnectionCache));
  197.         }
  198.  
  199.         return TRUE;
  200.     }
  201.  
  202.  
  203.     public function setRebuild()
  204.     {
  205.         $query = "UPDATE cac_cache SET cache_status='rebuild' WHERE cac_cache_type='$this->type' AND cac_cache_id='$this->id'";
  206.         $result = mysqli_query($this->dbConnectionCache, $query);
  207.  
  208.         if(mysqli_error($this->dbConnectionCache)) {
  209.             throw new \Exception("SetRebuild [" . $this->id . "] query failed: " . mysqli_error($this->dbConnectionCache));
  210.         }
  211.  
  212.         return TRUE;
  213.     }
  214.  
  215.     public function setEmpty()
  216.     {
  217.         $query = "UPDATE cac_cache SET cache_status='empty', cache = NULL, cache_report = NULL WHERE cac_cache_type='$this->type' AND cac_cache_id='$this->id'";
  218.         $result = mysqli_query($this->dbConnectionCache, $query);
  219.  
  220.         if(mysqli_error($this->dbConnectionCache)) {
  221.             throw new \Exception("SetEmpty [" . $this->id . "] query failed: " . mysqli_error($this->dbConnectionCache));
  222.         }
  223.  
  224.         return TRUE;
  225.     }
  226.  
  227.  
  228.  
  229.     protected function buildJsonData()
  230.     {
  231.         try
  232.         {
  233.             $this->needRebuild = FALSE;
  234.             if ($this->type == NULL || $this->id == NULL) {
  235.                 return;
  236.             }
  237.  
  238.             // Nastaveni parametru pro vyhledavani, single nebo multi,jen aktivni zaznamy, ukladani do cache a poslani hodnot do rabbitmq
  239.             $pole = array();
  240.             $type = self::STORE_TYPE;
  241.             $origin_id = NULL;
  242.  
  243.             if ($type == "multi") {
  244.                 $id = " id IN ($this->id) ";
  245.             } else {
  246.                 $id = " id='$this->id' ";
  247.                 $origin_id = $this->id;
  248.             }
  249.  
  250.  
  251.             if ($this->live_record) {
  252.  
  253.                 $live = "
  254.            AND active IN ('enabled','new')
  255.            AND visibility NOT IN ('blocked','invisible')";
  256.  
  257.                 $live_tra_object = "
  258.            AND tra_object_visibility NOT IN ('blocked','invisible')";
  259.             } else {
  260.                 $live = "";
  261.                 $live_tra_object = "";
  262.             }
  263.  
  264.             /////////////////////////////////////////////////////////////////////////////////////////////////////
  265.             // Zakladní informace o objektu
  266.             $objectBlackList = ['label', 'title', 'description', 'cache', 'content', 'note', 'reaction'];
  267.  
  268.             $categoryBlackList = ['cat_category_show_parameters',
  269.                 'cat_category_show_bus_auction', 'cat_category_show_description',
  270.                 'cat_category_show_bus_quote', 'cat_category_show_location_map',
  271.                 'cat_category_show_bus_rent', 'cat_category_show_tag', 'cat_category_redirect',
  272.                 'language', 'country', 'destination', 'duration_begin', 'duration_end'];
  273.  
  274.  
  275.             $query = "SELECT * FROM $this->type WHERE $id $live ORDER BY id";
  276.             $result = mysqli_query($this->dbConnection, $query);
  277.  
  278.             if($result === FALSE) {
  279.                 throw new \Exception("DatabaseCacheManager false query on type: $this->type [" . $origin_id . "] " . mysqli_error($this->dbConnection));
  280.             }
  281.  
  282.             if(mysqli_num_rows($result) == FALSE) {
  283.                 throw new \Exception("Empty result for type " . $this->type . " and ID: " . $this->id);
  284.             }
  285.  
  286.             while ($row = mysqli_fetch_assoc($result)) {
  287.  
  288.                 //echo $row['id']."<hr>";
  289.  
  290.  
  291.                 if ($this->type == "cat_category" || $this->type == "cat_trademark" ||
  292.                     $this->type == "cms_article" || $this->type == "cms_structure") {
  293.                     $this->remove_elements_from_black_list($row, $categoryBlackList);
  294.                 }
  295.  
  296.                 $this->remove_prefix($row, $this->type . "_");
  297.  
  298.                 if ($this->type == "cms_article") {
  299.                     $this->remove_prefix($row, "cms_");
  300.                 }
  301.  
  302.                 $this->remove_elements_from_black_list($row, $objectBlackList);
  303.  
  304.                 // Připojení názvu tabulky do pole hodnot (pro_product, cat_category, atd...)
  305.                 $row = array_merge(['source' => $this->type], $row);
  306.  
  307.                // $this->changeStringToNumber($row);
  308.  
  309.                 $pole[$row['id']] = $row;
  310.                 $pole[$row['id']]['translate'] = array();
  311.  
  312.                 if (isset($row["cat_category_id"]) == TRUE) {
  313.                     $pole[$row['id']]['category'] = array();
  314.                 }
  315.  
  316.                 //$pole[$row['id']]['property'] = array();
  317.                 //$pole[$row['id']]['contact'] = array();
  318.                 //$pole[$row['id']]['image'] = array();
  319.                 //$pole[$row['id']]['link_in_country'] = array();
  320.  
  321.             }
  322.  
  323.             //////////////////////////////////////////////////////////////////////////////////////////////////////
  324.             // Ceny
  325.  
  326.             $tables_pricing = array("pro_catalog", "pro_product", "pro_watchdog", "pro_request",
  327.                 "pro_response", "bus_auction", "bus_quote", "bus_rent", "bus_trade");
  328.  
  329.  
  330.             if (in_array($this->type, $tables_pricing)) {
  331.                 foreach ($pole[$origin_id] as $key => $value) {
  332.                     if (substr($key, 0, 5) == "price" OR $key == "currency") {
  333.                         $pole[$origin_id]['pricing'][$key] = $value;
  334.                         $this->remove_element($pole[$origin_id], $key);
  335.                     }
  336.                     if ($key == "changed") {
  337.                         $pole[$origin_id]['pricing'][$key] = $value;
  338.                     }
  339.                 }
  340.                 $this->changeStringToNumber($pole[$origin_id]['pricing']);
  341.             }
  342.  
  343.             //////////////////////////////////////////////////////////////////////////////////////////////////////
  344.             // Rating
  345.             // Rating parameters are between basic parameters in default
  346.  
  347.            /* $tables_rating = array("pro_catalog", "pro_product", "fir_firm", "fir_branch",
  348.                 "shp_shop", "cat_category", "cat_trademark");
  349.  
  350.             if (in_array($this->type, $tables_rating)) {
  351.                 foreach ($pole[$origin_id] as $key => $value) {
  352.                     if (substr($key, 0, 6) == "rating") {
  353.                         $pole[$origin_id]['rating'][$key] = $value;
  354.                         $this->remove_element($pole[$origin_id], $key);
  355.                     }
  356.                 }
  357.                 $this->changeStringToNumber($pole[$origin_id]['rating']);
  358.             }*/
  359.  
  360.             /////////////////////////////////////////////////////////////////////////////////////////////////////
  361.             $categoryCounter = 0;
  362.             //Doplnenie kategorii spolu s parent kategoriami
  363.             if (isset($pole[$origin_id]['category']) == TRUE || $this->type == "cat_category") {
  364.  
  365.                 // docasne vytvoreni category casti u cat_category kvuli category path
  366.                 if ($this->type == "cat_category" ) {
  367.                     $pole[$origin_id]["cat_category_id"] = $origin_id;
  368.                     $pole[$origin_id]['category'] = [];
  369.                 }
  370.                 $category_id = $pole[$origin_id]["cat_category_id"];
  371.  
  372.                 while ($category_id != NULL) {
  373.                     $query = "SELECT id, cat_category_parent_id, cat_category_code, priority_level, priority_internal, priority_commercial FROM cat_category WHERE id=" . $category_id;
  374.                     $result = mysqli_query($this->dbConnection, $query);
  375.                     $row = mysqli_fetch_assoc($result);
  376.  
  377.                     if($result === FALSE) {
  378.                         throw new \Exception("DatabaseCacheManager false query on cat_category [" . $origin_id . "] " . mysqli_error($this->dbConnection));
  379.                     }
  380.  
  381.                     if ($row != NULL) {
  382.                         $category = array();
  383.                         $category["id"] = $row["id"];
  384.                         $category["code"] = $row["cat_category_code"];
  385.                         $category['cat_category_priority_level'] = $row["priority_level"];
  386.                         $category['cat_category_priority_internal'] = $row["priority_internal"];
  387.                         $category['cat_category_priority_commercial'] = $row["priority_commercial"];
  388.  
  389.                         if($row["id"] == $pole[$origin_id]["cat_category_id"]) {
  390.                             $pole[$origin_id]['cat_category_priority_level'] = $row["priority_level"];
  391.                             $pole[$origin_id]['cat_category_priority_internal'] = $row["priority_internal"];
  392.                             $pole[$origin_id]['cat_category_priority_commercial'] = $row["priority_commercial"];
  393.                         }
  394.  
  395.                         $this->remove_prefix($category, "cat_");
  396.                         $this->changeStringToNumber($category);
  397.  
  398.                         array_push($pole[$origin_id]['category'], $category);
  399.                         if ($row["cat_category_parent_id"] != NULL) {
  400.                             $category_id = $row["cat_category_parent_id"];
  401.                         } else {
  402.                             $category_id = NULL;
  403.                         }
  404.                     }
  405.  
  406.                     $categoryCounter++;
  407.                 }
  408.  
  409.  
  410.                 for($i = 0; $i < count($pole[$origin_id]['category']); $i++){
  411.                     $pole[$origin_id]['category'][$i]['category_order'] = $categoryCounter - $i - 1;
  412.                 }
  413.  
  414.                 $pole[$origin_id]['category'] = array_reverse($pole[$origin_id]['category'], true);
  415.  
  416.                 $this->remove_prefix($pole[$origin_id], "cat_");
  417.             }
  418.             //doplnenie sub-kategorii
  419. //            if ($this->type == "cat_category") {
  420. //                $pole[$origin_id]["children_categories"] = array();
  421. //                $query = "SELECT id, cat_category_code FROM cat_category WHERE cat_category_parent_id = $origin_id";
  422. //                $result = mysqli_query($this->dbConnection, $query);
  423. //
  424. //                if($result === FALSE) {
  425. //                    throw new \Exception("DatabaseCacheManager false query on cat_category [" . $origin_id . "] " . mysqli_error($this->dbConnection));
  426. //                }
  427. //
  428. //                while ($row = mysqli_fetch_assoc($result))
  429. //                {
  430. //                    $subcat = array("id" => $row["id"], "code" => $row["cat_category_code"]);
  431. //                    $this->changeStringToNumber($subcat);
  432. //
  433. //                    array_push($pole[$origin_id]["children_categories"], $subcat);
  434. //                }
  435. //            }
  436.  
  437.  
  438. //            //doplnenie sub structures pre cms_structure
  439. //            if ($this->type == "cms_structure") {
  440. //                $pole[$origin_id]["children_structures"] = array();
  441. //                $query = "SELECT id, cms_structure_code FROM cms_structure WHERE cms_structure_parent_id = $origin_id";
  442. //                $result = mysqli_query($this->dbConnection, $query);
  443. //
  444. //                if($result === FALSE) {
  445. //                    throw new \Exception("DatabaseCacheManager false query on cms_structure [" . $origin_id . "] " . mysqli_error($this->dbConnection));
  446. //                }
  447. //
  448. //                while ($row = mysqli_fetch_assoc($result)) {
  449. //                    $subcat = array("id" => $row["id"], "code" => $row["cms_structure_code"]);
  450. //                    $this->changeStringToNumber($subcat);
  451. //                    array_push($pole[$origin_id]["children_structures"], $subcat);
  452. //                }
  453. //            }
  454.  
  455.  
  456.             // Doplneni jazyku = preklady
  457.  
  458.             $query = "SELECT tra_object_id AS id, language, tra_object_label AS label,tra_object_title AS title,tra_object_description AS description,tra_object_content AS content, tra_object_slug AS slug FROM tra_object WHERE " . str_replace('id', 'tra_object_id', $id) . " AND tra_object_type='$this->type'  $live $live_tra_object ORDER BY language";
  459.             $result = mysqli_query($this->dbConnection, $query);
  460.  
  461.             while ($row = mysqli_fetch_assoc($result)) {
  462.  
  463.                 $allowedLanguages = ['cs', 'sk', 'en'];
  464.                 if (in_array($row['language'],$allowedLanguages)) {
  465.                     $pole[$row['id']]['translate'][$row['language']]['label'] = str_replace('"','\\"',$row['label']);
  466.                     $pole[$row['id']]['translate'][$row['language']]['title'] = str_replace('"','\\"',$row['title']);
  467.  
  468.                     $pole[$row['id']]['translate'][$row['language']]['description'] = str_replace('"','\\"',strip_tags($row['description']));
  469.                     $pole[$row['id']]['translate'][$row['language']]['content'] = str_replace('"','\\"',strip_tags($row['content']));
  470.  
  471.                     $pole[$row['id']]['translate'][$row['language']]['description_source'] = htmlspecialchars($row['description'], ENT_QUOTES, 'UTF-8');
  472.                     $pole[$row['id']]['translate'][$row['language']]['content_source'] = htmlspecialchars($row['content'], ENT_QUOTES, 'UTF-8');
  473.                     $pole[$row['id']]['translate'][$row['language']]['slug'] = $row['slug'];
  474.  
  475.                     if (isset($pole[$origin_id]['category']) == TRUE || $this->type == "cat_category") {
  476.  
  477.                         $translateCategoriesIds = array();
  478.                         //kategoria produktu
  479.                         $category_path = "";
  480.                         $category_destination = "";
  481.  
  482.                         foreach($pole[$origin_id]['category'] as $cat) {
  483.                             array_push($translateCategoriesIds, $cat["id"]);
  484.                         }
  485.  
  486.  
  487.                         if(count($translateCategoriesIds)) {
  488.                             $trCatQuery = "SELECT tra_object_id AS id, tra_object_title AS title FROM tra_object WHERE tra_object_type = 'cat_category' AND tra_object_id IN(" . implode(",", $translateCategoriesIds) . ") AND language = '" . $row["language"] . "'" . $live . $live_tra_object . " ORDER BY tra_object_id DESC";
  489.                             $trCatResult = mysqli_query($this->dbConnection, $trCatQuery);
  490.  
  491.                             $translatedCategories = [];
  492.                             while ($tRow = mysqli_fetch_assoc($trCatResult)) {
  493.                                 $translatedCategories[] = ["id" => $tRow['id'], "title" => $tRow['title']];
  494.                             }
  495.  
  496.                             //serazeni od nejvyssi kategorie po nejnizsi
  497.                             usort($translatedCategories, function ($a, $b) use ($translateCategoriesIds) {
  498.                                 $pos_a = array_search($a['id'], $translateCategoriesIds);
  499.                                 $pos_b = array_search($b['id'], $translateCategoriesIds);
  500.                                 return $pos_a - $pos_b;
  501.                             });
  502.  
  503.                             foreach ($translatedCategories as $item) {
  504.                                     $category_path .= $item['title'] . " | ";
  505.  
  506.                                     if (isset($pole[$origin_id]['category_id']) && $pole[$origin_id]['category_id'] == $item['id']) {
  507.                                         $category_destination = $item['title'];
  508.                                     }
  509. //                                $category_path = rtrim($category_path, ' | ');
  510.                             }
  511.  
  512.                             $category_path = rtrim($category_path, ' | ');
  513.  
  514.                         }
  515.  
  516.                         $pole[$origin_id]['translate'][$row['language']]['category_path'] = $category_path;
  517.  
  518.                         $pole[$origin_id]['translate'][$row['language']]['category_destination'] = $category_destination;
  519.                         //array_push()
  520.                     }
  521.                 }
  522.                 //test
  523.   /*              $pole[$row['id']]['translate'][$row['language']]['label'] = $pole[$row['id']]['translate'][$row['language']]['label'];
  524.                 $pole[$row['id']]['translate'][$row['language']]['title'] = $pole[$row['id']]['translate'][$row['language']]['title'];
  525.                 $pole[$row['id']]['translate'][$row['language']]['description'] = $pole[$row['id']]['translate'][$row['language']]['description'];
  526.                 $pole[$row['id']]['translate'][$row['language']]['content'] = $pole[$row['id']]['translate'][$row['language']]['content'];
  527.                 $pole[$row['id']]['translate'][$row['language']]['content_strip_tags'] = $pole[$row['id']]['translate'][$row['language']]['content_strip_tags'];
  528. */
  529.             }
  530.  
  531.             // ostraneni docasne category casti u cat_category
  532.             if ($this->type == "cat_category" ) {
  533.                 unset($pole[$origin_id]['category']);
  534.                 unset($pole[$origin_id]['category_id']);
  535.                 unset($pole[$origin_id]['category_priority_level']);
  536.                 unset($pole[$origin_id]['category_priority_internal']);
  537.                 unset($pole[$origin_id]['category_priority_commercial']);
  538.             }
  539.  
  540.             /////////////////////////////////////////////////////////////////////////////////////////////////////
  541.             // Parametry produktu
  542.             $propertyBlackList = ['duration_begin', 'duration_end', 'active', 'created', 'changed', 'cache'];
  543.  
  544.             //    Blacklist pro vnitřní cyklus(value_multi)
  545.             $innerBlackList = ['priority_level', 'priority_internal', 'priority_commercial', 'visibility', 'active', 'note', 'value_note', 'country', 'value_slug', 'destination'];
  546.  
  547.             $tables_property = array('pro_catalog', 'pro_product', 'pro_request', 'pro_response', 'pro_watchdog', 'bus_auction', 'bus_rent', 'bus_quote');
  548.  
  549.  
  550.             $addonBlackList = ['value_note', 'value_cache', 'tolerance_order',
  551.                 'tolerance_value', 'tolerance_percent', 'tolerance_operation', 'tolerance_range_max', 'tolerance_range_min', 'value_checkbox'];
  552.  
  553.             if (in_array($this->type, $tables_property)) {
  554.  
  555.                 $query = "SELECT  pv.*,
  556.                prp_property_dependency_id AS dependency_id,
  557.                prp_unit_default_id AS unit_default_id,
  558.                prp_property_code AS code,
  559.                prp_property_icon AS icon,
  560.                prp_property_type AS type,
  561.                prp_property_show AS 'show',
  562.                prp_property_slug AS slug,
  563.                prp_unit_code AS unit_code,
  564.                prp_property_value_cache AS value_cache
  565.                FROM prp_property p JOIN pro_value pv ON (p.id=pv.prp_property_id) LEFT JOIN prp_unit pu ON (pv.prp_unit_id=pu.id)  WHERE " . str_replace('id', $this->type . '_id', $id) . " " . str_replace('active', 'pv.active', str_replace('visibility', 'pv.visibility', $live));
  566.                 $result = mysqli_query($this->dbConnection, $query);
  567.                 $value_multi = array();
  568.  
  569.                 if(mysqli_num_rows($result)) {
  570.                     $pole[$origin_id]['property'] = array();
  571.                 }
  572.  
  573.                 $i = 0;
  574.  
  575.                 while ($row = mysqli_fetch_assoc($result)) {
  576.  
  577.                     array_push($value_multi, $row['id']);
  578.  
  579.                     $pom_id = $row[$this->type . '_id'];
  580.  
  581.                     for ($ckl = 0; $ckl < sizeof($tables_property); $ckl++) $this->remove_element($row, $tables_property[$ckl] . '_id');
  582.  
  583.                     $this->remove_elements_from_black_list($row, $propertyBlackList);
  584.                     $this->remove_elements_from_black_list($row, $innerBlackList);
  585.  
  586.                     $this->remove_prefix($row, "pro_");
  587.                     $this->remove_prefix($row, "cat_");
  588.                     $this->remove_prefix($row, "prp_");
  589.  
  590.                     // Odstranění prvků začínajících prefixem "value" a majícíh hodnotu null
  591.                     foreach ($row as $key => $value) {
  592.                         if ($value == null AND substr($key, 0, 5) == "value" AND $key != "value_single_id") {
  593.                             $this->remove_element($row, $key);
  594.                         }
  595.                     }
  596.  
  597.  
  598.                     //get exact value code for single_id from prp_property_value or store value in one exact field
  599.                     if (isset($row["value_single_id"])) {
  600.                         if ($row["value_cache"] == "no") {
  601.                             $query_property_value = "SELECT prp_property_value_title FROM prp_property_value WHERE id=" . $row["value_single_id"];
  602.                             $result_property_value = mysqli_query($this->dbConnection, $query_property_value);
  603.                             $property_value = mysqli_fetch_assoc($result_property_value);
  604.                             $row["value"] = $property_value["prp_property_value_title"];
  605.                         }
  606.                         else {
  607.                             $row["value"] = null;
  608.                         }
  609.                     } elseif (isset($row["value_text"])) {
  610.                         $row["value"] = $row["value_text"];
  611.                     } elseif (isset($row["value_textarea"])) {
  612.                         $row["value"] = $row["value_textarea"];
  613.                     } elseif (isset($row["value_texteditor"])) {
  614.                         $row["value"] = $row["value_texteditor"];
  615.                     } elseif (isset($row["value_date"])) {
  616.                         $row["value"] = $row["value_date"];
  617.                     } elseif (isset($row["value_time"])) {
  618.                         $row["value"] = $row["value_time"];
  619.                     } elseif (isset($row["value_datetime"])) {
  620.                         $row["value"] = $row["value_datetime"];
  621.                     } elseif (isset($row["value_checkbox"])) {
  622.                         $row["value"] = $row["value_checkbox"];
  623.                     }
  624.                     else
  625.                         $row["value"] = null;
  626.  
  627.                     $row['multi'] = array();
  628.  
  629.                     //$pole[$pom_id]['property'][$row['id']] = $row;
  630.  
  631.                     $query_m = "SELECT ppv.* FROM pro_value_multi pm JOIN prp_property_value ppv ON (pm.prp_property_value_id=ppv.id)
  632.                      WHERE pro_value_id=" . $row['id'] . "  " . str_replace('active', 'pm.active', str_replace('visibility', 'pm.visibility', $live));
  633.                     $result_m = mysqli_query($this->dbConnection, $query_m);
  634.  
  635.  
  636.                     while ($row_m = mysqli_fetch_assoc($result_m)) {
  637.                         $this->remove_prefix($row_m, "prp_");
  638.                         $this->remove_prefix($row_m, "property_", ['property_id', 'property_value_parent_id']);
  639.  
  640.                         $this->remove_elements_from_black_list($row_m, $propertyBlackList);
  641.                         $this->remove_elements_from_black_list($row_m, $innerBlackList);
  642. //                        $this->remove_elements_from_black_list($row_m, $valueMultiBlackList);
  643.  
  644.                         $row_m["value"] = $row_m["value_code"];
  645.                         $row_m["value"] = $row_m["value_code"];
  646.  
  647.  
  648.                         if ($row["value_cache"] == "no") {
  649.                             $row_m['value'] = $row_m["value_title"];
  650.                         }
  651.  
  652.                         $this->changeStringToNumber($row_m);
  653.                         array_push($row['multi'], $row_m);// = $row_m;
  654.  
  655.                     }
  656.  
  657.                     if (is_array($pole[$origin_id]['property']) == FALSE) {
  658.                         $pole[$origin_id]['property'] = array();
  659.                     }
  660.  
  661.                     $this->remove_elements_from_black_list($row, $addonBlackList);
  662.  
  663.                     $this->changeStringToNumber($row);
  664.                     array_push($pole[$origin_id]['property'], $row);
  665.                 }
  666.  
  667.             }
  668.  
  669.             /////////////////////////////////////////////////////////////////////////////////////////////////////
  670.             // Kontakt z lnk_contact
  671.  
  672.             $contactBlackList = ['duration_begin', 'duration_end', 'active', 'created', 'changed', 'cache', 'priority_level', 'priority_commercial', 'priority_internal', 'visibility', 'note'];
  673.  
  674.             // Určuje, které prvky se mají odstranit na základě typu kontaktu
  675.             $contactTypeRelatedColumns = ['phone' => ['lnk_contact_phone'], 'mobile' => ['lnk_contact_mobile'], 'fax' => ['lnk_contact_fax'], 'email' => ['lnk_contact_email'], 'web' => ['lnk_contact_web'], 'facebook' => ['lnk_contact_social_facebook'], 'linkedin' => ['lnk_contact_social_linkedin'], 'google+' => ['lnk_contact_social_google'], 'pinterest' => ['lnk_contact_social_pinterest'], 'instagram' => ['lnk_contact_social_instagram'], 'twitter' => ['lnk_contact_social_twitter'], 'youtube' => ['lnk_contact_video_youtube'], 'vimeo' => ['lnk_contact_video_vimeo'], 'bank_account' => ['lnk_contact_bank_account', 'lnk_contact_bank_iban', 'lnk_contact_bank_bic_swift', 'lnk_contact_bank_name'], 'address' => ['lnk_contact_address_street', 'lnk_contact_address_street_number', 'lnk_contact_address_locality', 'lnk_contact_address_neighborhood', 'lnk_contact_address_postal_code', 'lnk_contact_address_region', 'lnk_contact_address_country', 'lnk_contact_place_id'], 'gps' => ['lnk_contact_gps_latitude', 'lnk_contact_gps_longitude', 'lnk_contact_gps_altitude', 'lnk_contact_gps_latitude_number', 'lnk_contact_gps_longitude_number', 'lnk_contact_gps_altitude_number']];
  676.  
  677.             $tables_contact = array('cor_user', 'fir_firm', 'fir_branch', 'shp_shop', 'fir_employee', 'cat_category', 'cat_trademark', 'pro_catalog', 'pro_product', 'shp_feed_product', 'pro_request', 'pro_response', 'pro_watchdog', 'bus_auction', 'bus_rent', 'bus_quote');
  678.  
  679.             if (in_array($this->type, $tables_contact)) {
  680.  
  681.                 //$query="SELECT * FROM lnk_contact WHERE ".str_replace('id',$this->type.'_id',$id)." $live ORDER BY lnk_contact_order";
  682.                 $query = "SELECT * FROM lnk_contact WHERE lnk_contact_object_type = '$this->type' AND
  683.                  lnk_contact_object_id = '$origin_id' ORDER BY lnk_contact_order";
  684.                 $result = mysqli_query($this->dbConnection, $query);
  685.  
  686.                 if($result === FALSE) {
  687.                     throw new \Exception("DatabaseCacheManager false query on lnk_contact [" . $origin_id . "] " . mysqli_error($this->dbConnection));
  688.                 }
  689.  
  690.                 if(mysqli_num_rows($result)) {
  691.                     $pole[$origin_id]['contact'] = array();
  692.                 }
  693.  
  694.  
  695.                 $i = 0;
  696.                 while ($row = mysqli_fetch_assoc($result)) {
  697.  
  698.                     $allowedTypes = explode(',', $row['lnk_contact_type']);
  699.  
  700.                     foreach ($contactTypeRelatedColumns as $key => $value) {
  701.  
  702.                         if (!in_array($key, $allowedTypes)) {
  703.  
  704.                             foreach ($value as $item) {
  705.  
  706.                                 $this->remove_element($row, $item);
  707.                             }
  708.                         }
  709.                     }
  710.  
  711. //                    $row['lnk_contact_content_strip_tags'] = strip_tags($row['lnk_contact_content']);
  712.  
  713.                     $this->remove_prefix($row, "lnk_contact_");
  714.                     $this->remove_elements_from_black_list($row, $contactBlackList);
  715.  
  716.                     $this->changeStringToNumber($row);
  717.                     array_push($pole[$origin_id]['contact'], $row);
  718.                     //$pole[$pom_id]['contact'][$i]=$row;
  719.  
  720.                     $i++;
  721.                 }
  722.             }
  723.  
  724.  
  725.             /////////////////////////////////////////////////////////////////////////////////////////////////////
  726.             // Pocty
  727.             if ($this->type != "cat_category") {
  728.                 $pole[$origin_id]["stats"] =
  729.                     [   "request_count" => 0,
  730.                         "sales_count" => 0,
  731.                         "favorite_like" => 0,
  732.                         "favorite_dislike" => 0,
  733.                         "inspection_month" => 0,
  734.                         "inspection_year" => 0,
  735.                         "inspection_full" => 0
  736.                     ];
  737.             }
  738.  
  739.             /////////////////////////////////////////////////////////////////////////////////////////////////////
  740.             // Obrazky
  741.  
  742.             $tables_image = array('cor_user', 'fir_firm', 'fir_branch', 'shp_shop', 'fir_employee', 'cat_category', 'cat_trademark', 'pro_catalog', 'pro_product', 'shp_feed_product', 'pro_request', 'pro_response', 'pro_watchdog', 'bus_auction', 'bus_rent', 'bus_quote', 'prp_property', 'prp_unit', 'gal_gallery_item', 'cms_article', 'cms_structure', 'cms_blog', 'cms_questionnaire', 'cms_index', 'cms_test', 'cms_query', 'web_slider');
  743.  
  744.             $imagesBlackList = ["extension", "object_id", "cor_user_id", "object_type", "imageExtension", "sanatized_name"];
  745.  
  746.             if (in_array($this->type, $tables_image)) {
  747.  
  748.                 $query = "SELECT img_image_link.*, img_image.img_image_extension AS imageExtension
  749.                  FROM img_image_link
  750.                  LEFT JOIN img_image ON img_image.id = img_image_link.img_image_id
  751.                  WHERE img_image_link_object_type = '$this->type' AND
  752.                  img_image_link_object_id = '$origin_id' ORDER BY img_image_link_order";
  753.                 $result = mysqli_query($this->dbConnection, $query);
  754.                 $i = 0;
  755.                 $type = "";
  756.  
  757.                 if($result === FALSE) {
  758.                     throw new \Exception("DatabaseCacheManager false query on img_image_link [" . $origin_id . "] " . mysqli_error($this->dbConnection));
  759.                 }
  760.  
  761.                 if(mysqli_num_rows($result)) {
  762.                     $pole[$origin_id]['image'] = array();
  763.                 }
  764.  
  765.                 while ($row = mysqli_fetch_assoc($result)) {
  766.  
  767.                     $this->remove_prefix($row, "img_image_link_");
  768.                     $this->remove_prefix($row, "img_");
  769.                     $this->remove_prefix($row, "image_", ["image_id"]);
  770.                     $this->remove_elements_from_black_list($row, $innerBlackList);
  771.                     $this->remove_elements_from_black_list($row, $propertyBlackList);
  772.                     $this->remove_element($row, "link_note");
  773.                     if ($type != $row['type']) {
  774.                         $i = 0;
  775.                         $type = $row['type'];
  776.                     }
  777.  
  778.                     //get base relative path for image
  779.                     $path = Paths::getRemoteImageBasePath($row["image_id"], $row["imageExtension"]);
  780.                     $row["path"] = "/images" . $path;
  781.  
  782.                     $this->remove_elements_from_black_list($row, $imagesBlackList);
  783.  
  784.                     $this->changeStringToNumber($row);
  785.                     if ($row['type'] == "main") {
  786.                         array_unshift($pole[$origin_id]['image'], $row);
  787.                     }
  788.                     else{
  789.                         array_push($pole[$origin_id]['image'], $row);
  790.                     }
  791.                     //$pole[$pom_id]['image'] = $row;
  792.                     $i++;
  793.                 }
  794.             }
  795.  
  796.             /////////////////////////////////////////////////////////////////////////////////////////////////////
  797.             // Vazba na jine zeme dostupnosti produktu link_in_country
  798.             $query = "SELECT id,lnk_in_country_object_id,lnk_in_country_price_convert,lnk_in_country_price_new,lnk_in_country_exchange_rate,currency,country,duration_begin,duration_end FROM lnk_in_country WHERE " . str_replace('id', 'lnk_in_country_object_id', $id) . " AND lnk_in_country_object_type='$this->type' $live";
  799.             $result = mysqli_query($this->dbConnection, $query);
  800.  
  801.             if($result === FALSE) {
  802.                 throw new \Exception("DatabaseCacheManager false query on link_in_country [" . $origin_id . "] " . mysqli_error($this->dbConnection));
  803.             }
  804.  
  805.             if(mysqli_num_rows($result)) {
  806.                 $pole[$origin_id]['link_in_country'] = array();
  807.             }
  808.  
  809.             while ($row = mysqli_fetch_assoc($result)) {
  810.  
  811.                 $pom_id = $row['lnk_in_country_object_id'];
  812.                 $pom_id_lnk = $row['id'];
  813.  
  814.                 $this->remove_prefix($row, "lnk_in_country_");
  815.  
  816.                 $this->remove_element($row, 'id');
  817.                 $this->remove_element($row, 'lnk_in_country_object_id');
  818.  
  819.                 $this->changeStringToNumber($row);
  820.                 array_push($pole[$pom_id]['link_in_country'], $row);
  821.                 //$pole[$pom_id]['link_in_country'][$pom_id_lnk]=$row;
  822.             }
  823.  
  824.             /////////////////////////////////////////////////////////////////////////////////////////////////////
  825.             // Branch u firmy
  826.             if ($this->type == "fir_firm") {
  827.  
  828.                 $query = "SELECT * FROM fir_branch WHERE " . str_replace('id', $this->type . '_id', $id) . " $live";
  829.                 $result = mysqli_query($this->dbConnection, $query);
  830.                 $i = 0;
  831.  
  832.                 if($result === FALSE) {
  833.                     throw new \Exception("DatabaseCacheManager false query on fir_firm [" . $origin_id . "] " . mysqli_error($this->dbConnection));
  834.                 }
  835.  
  836.                 while ($row = mysqli_fetch_assoc($result)) {
  837.                     $pom_id = $row[$this->type . '_id'];
  838.  
  839.                     for ($ckl = 0; $ckl < sizeof($tables_image); $ckl++) $this->remove_element($row, $tables_image[$ckl] . '_id');
  840.  
  841.                     $this->remove_prefix($row, "fir_branch_");
  842.                     $this->remove_elements_from_black_list($row, $contactBlackList);
  843.  
  844.                     $this->changeStringToNumber($row);
  845. //                    array_push($pole[$pom_id]['branch'], $row);
  846.                     $pole[$pom_id]['branch'][$i] = $row;
  847.                     $i++;
  848.                 }
  849.             }
  850.  
  851.             // Shop u firm a branch
  852.             $tables_shop = array('fir_firm', 'fir_branch');
  853.             if (in_array($this->type, $tables_shop)) {
  854.  
  855.                 $query = "SELECT * FROM shp_shop WHERE " . str_replace('id', $this->type . '_id', $id) . " $live";
  856.                 $result = mysqli_query($this->dbConnection, $query);
  857.                 $i = 0;
  858.                 $type = "";
  859.  
  860.                 if($result === FALSE) {
  861.                     throw new \Exception("DatabaseCacheManager false query on firm and branch [" . $origin_id . "] " . mysqli_error($this->dbConnection));
  862.                 }
  863.  
  864.  
  865.                 while ($row = mysqli_fetch_assoc($result)) {
  866.  
  867.                     $pom_id = $row[$this->type . '_id'];
  868.  
  869.                     for ($ckl = 0; $ckl < sizeof($tables_image); $ckl++) $this->remove_element($row, $tables_image[$ckl] . '_id');
  870.  
  871.                     $this->remove_prefix($row, "shp_shop_");
  872.                     $this->remove_elements_from_black_list($row, $contactBlackList);
  873.  
  874.                     $this->changeStringToNumber($row);
  875. //                    array_push($pole[$pom_id]['shop'], $row);
  876.                     $pole[$pom_id]['shop'][$i] = $row;
  877.                     $i++;
  878.                 }
  879.             }
  880.  
  881.  
  882.  
  883.             /////////////////////////////////////////////////////////////////////////////////////////////////////
  884.             // Property values
  885. //            if ($this->type == "prp_property") {
  886. //
  887. //                $query = "SELECT * FROM prp_property_value WHERE prp_property_id = " . $this->id;
  888. //                $result = mysqli_query($this->dbConnection, $query);
  889. //                $i = 0;
  890. //                while ($row = mysqli_fetch_assoc($result)) {
  891. //                    $this->remove_prefix($row, "prp_property_value_");
  892. //
  893. //                    $this->remove_elements_from_black_list($row, $propertyBlackList);
  894. //                    $this->remove_elements_from_black_list($row, $objectBlackList);
  895. //
  896. //
  897. //                    $queryTranslateValues = "SELECT tra_object_id AS id, language, tra_object_label AS label,tra_object_title AS title,tra_object_description AS description,tra_object_content AS content, tra_object_slug AS slug FROM tra_object WHERE  tra_object_id = " . $row['id'] . " AND tra_object_type='prp_property_value'  $live $live_tra_object ORDER BY language";
  898. //                    $resultTranslateValues = mysqli_query($this->dbConnection, $queryTranslateValues);
  899. //
  900. //                    while ($rowTranslateValues = mysqli_fetch_assoc($resultTranslateValues)) {
  901. //
  902. //                        $allowedLanguages = ['cs', 'sk', 'en'];
  903. //                        if (in_array($rowTranslateValues['language'], $allowedLanguages)) {
  904. //                            $row['translate'][$rowTranslateValues['language']]['label'] = str_replace('"', '\\"', $rowTranslateValues['label']);
  905. //                            $row['translate'][$rowTranslateValues['language']]['title'] = str_replace('"', '\\"', $rowTranslateValues['title']);
  906. //
  907. //                            $row['translate'][$rowTranslateValues['language']]['description'] = str_replace('"', '\\"', strip_tags($rowTranslateValues['description']));
  908. //                            $row['translate'][$rowTranslateValues['language']]['content'] = str_replace('"', '\\"', strip_tags($rowTranslateValues['content']));
  909. //
  910. //                            $row['translate'][$rowTranslateValues['language']]['description_source'] = htmlspecialchars($rowTranslateValues['description'], ENT_QUOTES, 'UTF-8');
  911. //                            $row['translate'][$rowTranslateValues['language']]['content_source'] = htmlspecialchars($rowTranslateValues['content'], ENT_QUOTES, 'UTF-8');
  912. //                            $row['translate'][$rowTranslateValues['language']]['slug'] = $rowTranslateValues['slug'];
  913. //                        }
  914. //
  915. //                    }
  916. //
  917. //                    $this->changeStringToNumber($row);
  918. //                    $pole[$this->id ]['value'][$i] = $row;
  919. //                    $i++;
  920. //                }
  921. //            }
  922.  
  923.  
  924.             if ($this->type == "prp_property") {
  925.  
  926.                 $prpPropertyBlackList = ["decimal_scale", "text_length_min", "decimal_precision",
  927.                     "text_trim", "range_min", "range_max"];
  928.                 $this->remove_elements_from_black_list($pole[$this->id], $prpPropertyBlackList);
  929.  
  930.  
  931.                 $query = "SELECT u.* FROM prp_unit_assigned ua JOIN prp_unit u ON (u.id=ua.prp_unit_id) WHERE prp_property_id = " . $this->id;
  932.                 $result = mysqli_query($this->dbConnection, $query);
  933.                 $i = 0;
  934.                 while ($row = mysqli_fetch_assoc($result)) {
  935.                     $this->remove_prefix($row, "prp_unit_");
  936.  
  937.                     $this->remove_elements_from_black_list($row, $propertyBlackList);
  938.                     // $this->remove_elements_from_black_list($row, $objectBlackList);
  939.                     $this->remove_elements_from_black_list($row, $innerBlackList);
  940.  
  941.  
  942.                     $this->changeStringToNumber($row);
  943.                     $pole[$this->id ]['units'][$i] = $row;
  944.                     $i++;
  945.                 }
  946.             }
  947.  
  948.  
  949.  
  950.             $this->changeStringToNumber($pole[$origin_id]);
  951.             $this->arrayData = $pole;
  952.  
  953.         }
  954.         catch(\Exception $e)
  955.         {
  956.             throw new DatabaseCacheUpdateException("DatabaseCacheManager, buildJson exception: " . $e->getMessage());
  957.         }
  958.  
  959.     }
  960.  
  961.  
  962.     public function cleanArrayData(&$array)
  963.     {
  964.         foreach($array as $key => &$value) {
  965.             if(is_array($value)) {
  966.                 $value = $this->cleanArrayData($value);
  967.             }
  968.             else {
  969.                 if($value != null)
  970.                 {
  971.                     $value = htmlspecialchars($value, ENT_QUOTES);
  972.                     $value = str_replace('\\', '', $value);
  973.                     $value = str_replace('\\/\\', '', $value);
  974.                     $value = str_replace("\t", "\\t", $value);
  975.                     $value = str_replace("\r", "\\r", $value);
  976.                     $value = str_replace("\n", "\\n", $value);
  977.                     $value = str_replace("\f", "\\f", $value);
  978.                 }
  979.             }
  980.         }
  981.  
  982.         return $array;
  983.     }
  984.  
  985.  
  986.     private function updateCache()
  987.     {
  988.        try {
  989.            $this->arrayData = $this->cleanArrayData($this->arrayData);      //clean for json encode
  990.            // Ulozeni hodnoty do cache
  991.            if (self::STORE_TYPE == 'multi') {
  992.  
  993.                throw new \Exception("Unsupported store type MULTI.");
  994.  
  995.                $key = array_keys($this->arrayData);
  996.                for ($ckl = 0; $ckl < sizeof($key); $ckl++) {
  997.                    $pom = array();
  998.                    $pom = $this->arrayData[$key[$ckl]];
  999.  
  1000.                    $pom_json = json_encode($pom, JSON_UNESCAPED_UNICODE);
  1001.  
  1002.                    $query = "INSERT INTO cac_cache (cac_cache_type, cac_cache_id, cache,cache_status) VALUES ('$this->type', " . $key[$ckl] . ", '$pom_json', 'generated')
  1003.                            ON DUPLICATE KEY UPDATE cache='$pom_json', cache_status='generated'";
  1004.                    $result = mysqli_query($this->dbConnectionCache, $query);
  1005.  
  1006.                    if(!$result) {
  1007.                        throw new \Exception("Update cache query failed: " . mysqli_error($this->dbConnectionCache));
  1008.                    }
  1009.  
  1010.                }
  1011.            } else {
  1012.  
  1013.                if(isset($this->arrayData[$this->id]) == FALSE) {
  1014.                    throw new \Exception("DatabaseCacheManager error - empty array for id to store to cache: " . $this->id);
  1015.                }
  1016.  
  1017.                $this->arrayData[$this->id]["changed"] = date("Y-m-d H:i:s");
  1018.                $json = $this->getJsonData();
  1019.                $verifyArray = json_decode($json);
  1020.                if (json_last_error() !== JSON_ERROR_NONE) {
  1021.                    $json = "";      //{} - "" wont be saved
  1022.                }
  1023.  
  1024.                $query = "INSERT INTO cac_cache (cac_cache_type, cac_cache_id, cache,cache_status) VALUES ('$this->type', " . $this->id . ", '$json', 'generated')
  1025.                            ON DUPLICATE KEY UPDATE cache='$json', cache_status='generated'";
  1026.                $result = mysqli_query($this->dbConnectionCache, $query);
  1027.  
  1028.                if(!$result) {
  1029.                    throw new \Exception("Update cache [" . $this->id . "] query failed: " . mysqli_error($this->dbConnectionCache));
  1030.                }
  1031.            }
  1032.        }
  1033.         catch(\Exception $e) {
  1034.             //\Tracy\Debugger::log("DatabaseCacheManager, updateCache exception: " . $e->getMessage());
  1035.             return FALSE;
  1036.         }
  1037.  
  1038.         return TRUE;
  1039.     }
  1040.  
  1041.  
  1042.     public function deleteCache()
  1043.     {
  1044.         $this->needRebuild = TRUE;
  1045.         $query = "UPDATE $this->type SET cache='' WHERE id='$this->id'";
  1046.         $result = mysqli_query($this->dbConnection, $query);
  1047.  
  1048.         return $result == FALSE ? FALSE : TRUE;
  1049.     }
  1050.  
  1051.  
  1052.     public function getJsonData()
  1053.     {
  1054.         if($this->needRebuild) {
  1055.             $this->buildJsonData();
  1056.         }
  1057.  
  1058.         if(isset($this->arrayData[$this->id]) == FALSE) {
  1059.             throw new \Exception("Unset ID in arrayData.");
  1060.         }
  1061.  
  1062.         return json_encode($this->arrayData[$this->id], JSON_UNESCAPED_UNICODE);
  1063.     }
  1064.  
  1065.  
  1066.     public function getArrayData()
  1067.     {
  1068.         if($this->needRebuild) {
  1069.             $this->buildJsonData();
  1070.         }
  1071.  
  1072.         return $this->arrayData;
  1073.     }
  1074.  
  1075.  
  1076.     public function setId($id)
  1077.     {
  1078.         $this->needRebuild = TRUE;
  1079.         $this->id = $id;
  1080.     }
  1081.  
  1082.  
  1083.     public function getId()
  1084.     {
  1085.         return $this->id;
  1086.     }
  1087.  
  1088.  
  1089.     public function setType($type)
  1090.     {
  1091.         $this->needRebuild = TRUE;
  1092.         $this->type = $type;
  1093.     }
  1094.  
  1095.  
  1096.     public function getType($type)
  1097.     {
  1098.         return $this->type;
  1099.     }
  1100.  
  1101.  
  1102.     public function setLiveRecord($bool)
  1103.     {
  1104.         $this->live_record = $bool;
  1105.     }
  1106.  
  1107.  
  1108.     public function getLiveRecord()
  1109.     {
  1110.         return $this->live_record;
  1111.     }
  1112.  
  1113.  
  1114.     protected function remove_element(&$array, $key) // pass array by reference
  1115.     {
  1116.         unset($array[$key]);
  1117.     }
  1118.  
  1119.  
  1120.     /**
  1121.      * Odstrani všechny prvky, které se nachází na blacklistu
  1122.      */
  1123.     protected function remove_elements_from_black_list(&$array, $blackList)
  1124.     {
  1125.         foreach ($array as $key => $value) {
  1126.             if (in_array($key, $blackList)) {
  1127.                 $this->remove_element($array, $key);
  1128.             }
  1129.         }
  1130.     }
  1131.  
  1132.  
  1133.     /**
  1134.      * @param $array
  1135.      * @param $old_key
  1136.      * @param $new_key
  1137.      *  Vymění starý klíč za nový
  1138.      */
  1139.     protected function change_key(&$array, $old_key, $new_key) {
  1140.  
  1141.         if ( array_key_exists( $old_key, $array ) )
  1142.         {
  1143.             $keys = array_keys( $array );
  1144.             $keys[ array_search( $old_key, $keys ) ] = $new_key;
  1145.             $array = array_combine( $keys, $array );
  1146.         }
  1147.     }
  1148.  
  1149.  
  1150.     /**
  1151.      * @param       $array
  1152.      * @param       $prefix
  1153.      * @param array $no_process
  1154.      * Odstraní zadaný prefix ze všech prvků pole, pokud existuje
  1155.      * Třetí parametr obsahuje prvky, u kterých prefix zůstává
  1156.      */
  1157.     protected function remove_prefix(&$array, $prefix, $no_process = [])
  1158.     {
  1159.         foreach ($array as $key => $value) {
  1160.             if (!in_array($key, $no_process)) {
  1161.                 $pom = str_replace($prefix,"",$key);
  1162.                 if ($key != $pom) {
  1163.                     $this->change_key($array, $key, $pom );
  1164.                 }
  1165.             }
  1166.         }
  1167.     }
  1168.  
  1169.  
  1170.     protected function utf8_encode_recursive ($array)
  1171.     {
  1172.         $result = array();
  1173.         foreach ($array as $key => $value)
  1174.         {
  1175.             if (is_array($value))
  1176.             {
  1177.                 $result[$key] = $this->utf8_encode_recursive($value);
  1178.             }
  1179.             else if (is_string($value))
  1180.             {
  1181.                 $result[$key] = utf8_encode($value);
  1182.             }
  1183.             else
  1184.             {
  1185.                 $result[$key] = $value;
  1186.             }
  1187.         }
  1188.         return $result;
  1189.     }
  1190.  
  1191.  
  1192.     public function getObjectsToRebuild($limit, $cache = NULL)
  1193.     {
  1194.         $objects = [];
  1195.  
  1196.         $list = "'rebuild', 'empty', 'waiting'";
  1197.         $cacheTypeList = "'cms_structure', 'cms_article', 'cat_category', 'cat_trademark', 'prp_property_value', 'prp_property', 'pro_catalog'";
  1198.  
  1199.         if($cache)
  1200.             $query = "SELECT id, cac_cache_id, cac_cache_type, cache FROM cac_cache WHERE cache_status IN ($list) AND active = 'enabled' AND cac_cache_type IN ($cacheTypeList) LIMIT $limit";
  1201.         else
  1202.             $query = "SELECT id, cac_cache_id, cac_cache_type FROM cac_cache WHERE cache_status IN ($list) AND active = 'enabled' AND cac_cache_type IN ($cacheTypeList) LIMIT $limit";
  1203.  
  1204.         //$query = "SELECT id, cac_cache_id, cac_cache_type FROM cac_cache WHERE cache_status IN ($list) LIMIT $limit";
  1205.         $result = mysqli_query($this->dbConnectionCache, $query);
  1206.  
  1207.         echo "\r\n";
  1208.         echo 'Total rows selected: ' . $result->num_rows;
  1209.         echo "\r\n";
  1210.  
  1211.         // query ok
  1212.         if($result != false)
  1213.         {
  1214.             while($row = $result->fetch_assoc()){
  1215.                 $objects[] = $row;
  1216.             }
  1217.         }
  1218.         else
  1219.         {
  1220.             throw new \Exception('getObjectsToRebuild exception');
  1221.         }
  1222.  
  1223.  
  1224.         return $objects;
  1225.     }
  1226.  
  1227.     public function getObjectsWithCacheToUpdateByIds($ids)
  1228.     {
  1229.         $objects = [];
  1230.  
  1231.         $query = "SELECT id, cac_cache_id, cac_cache_type, cache FROM cac_cache WHERE id IN (".implode(',', $ids).")";
  1232.  
  1233.         $result = mysqli_query($this->dbConnectionCache, $query);
  1234.  
  1235.  
  1236.         // query ok
  1237.         if($result != false)
  1238.         {
  1239.             while($row = $result->fetch_assoc()){
  1240.                 $objects[] = $row;
  1241.             }
  1242.         }
  1243.         else
  1244.         {
  1245.             throw new \Exception('getObjectsWithCacheToUpdate exception');
  1246.         }
  1247.  
  1248.  
  1249.         return $objects;
  1250.     }
  1251.  
  1252.  
  1253.     public function getTestObjectsToRebuild($limit, $cache = NULL)
  1254.     {
  1255.         $objects = [];
  1256.  
  1257.         $query = "select id, cac_cache_id, cac_cache_type from cac_cache where cac_cache_type = 'cat_category' LIMIT $limit";
  1258.  
  1259.         $result = mysqli_query($this->dbConnectionCache, $query);
  1260.  
  1261.         echo "\r\n";
  1262.         echo 'Total rows selected:' . $result->num_rows;
  1263.  
  1264.  
  1265.         // query ok
  1266.         if($result != false)
  1267.         {
  1268.             while($row = $result->fetch_assoc()){
  1269.                 $objects[] = $row;
  1270.             }
  1271.         }
  1272.         else
  1273.         {
  1274.             throw new \Exception('getTestObjectsToRebuild exception');
  1275.         }
  1276.  
  1277.  
  1278.         return $objects;
  1279.     }
  1280.  
  1281.  
  1282.     public function updateCacheStatusAndReport($status, $ids, $report = NULL)
  1283.     {
  1284.         $status = "'$status'";
  1285.  
  1286.         $this->dbConnectionCache->autocommit(FALSE);
  1287.  
  1288.         try
  1289.         {
  1290.             $this->dbConnectionCache->begin_transaction();
  1291.  
  1292.             echo "Update starts ...";
  1293.             echo "\r\n";
  1294.  
  1295.             if(!$report)
  1296.             {
  1297.                 $query = "UPDATE cac_cache SET cache_status = $status WHERE id IN (".implode(',', $ids).")";
  1298.             }
  1299.             else
  1300.             {
  1301.                 $query = "UPDATE cac_cache SET cache_status = $status, cache_report = $report WHERE id IN (".implode(',', $ids).")";
  1302.             }
  1303.  
  1304.             mysqli_query($this->dbConnectionCache, $query);
  1305.  
  1306.             if(mysqli_error($this->dbConnectionCache)) {
  1307.                 echo mysqli_error($this->dbConnectionCache);
  1308.                 throw new \Exception("Update transaction was not executed correctly, command rollbacked" . mysqli_error($this->dbConnectionCache));
  1309.             }
  1310.  
  1311.             $affectedRows = $this->dbConnectionCache->affected_rows;
  1312.  
  1313.             $this->dbConnectionCache->commit();
  1314.         }
  1315.         catch(\Exception $e)
  1316.         {
  1317.             $this->dbConnectionCache->rollback();
  1318.  
  1319.             $affectedRows = -1;
  1320.  
  1321.             throw new \Exception("Update transaction was not executed correctly, command rollbacked");
  1322.         }
  1323.  
  1324.         return $affectedRows;
  1325.  
  1326.     }
  1327.  
  1328.     public function changeStringToNumber(&$array){
  1329.         $blackList = ["title", "label", "description", "content", "value_title", "value_label", "value_description", "value_content"];
  1330.         foreach($array as $key => $value)
  1331.         {
  1332.             if(is_numeric($value) && !in_array($key, $blackList))
  1333.             {
  1334.                 $array[$key] = (float)$value;
  1335.             }
  1336.         }
  1337.  
  1338.  
  1339.     }
  1340.  
  1341. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement