PageRenderTime 64ms CodeModel.GetById 27ms RepoModel.GetById 0ms app.codeStats 0ms

/application.php

https://github.com/dprotopopov/tritumana
PHP | 882 lines | 710 code | 69 blank | 103 comment | 24 complexity | 3d4fb65097b2db0aeadb5d71fa2c0a0c MD5 | raw file
Possible License(s): GPL-2.0, LGPL-2.1, BSD-3-Clause, LGPL-2.0
  1. <?php
  2. //////////////////////////////////////////////////////////////////////////////
  3. // Разрабочик dmitry@protopopov.ru
  4. /** Include PHPExcel */
  5. require_once dirname(__FILE__) . '/bower_components/PHPExcel/Classes/PHPExcel.php';
  6. require_once( dirname(__FILE__) . '/defines.php' );
  7. require_once( dirname(__FILE__) . '/functions.php' );
  8. require_once( dirname(__FILE__) . '/configuration.php' );
  9. require_once( dirname(__FILE__) . '/database.php' );
  10. require_once( dirname(__FILE__) . '/insales.php' );
  11. require_once( dirname(__FILE__) . '/magento.php' );
  12. require_once( dirname(__FILE__) . '/factory.php' );
  13. class JApplication {
  14. private $config;
  15. private $db;
  16. public function __construct() {
  17. $this->config = JFactory::getConfig();
  18. $this->db = JFactory::getDbo();
  19. }
  20. protected static $instance;
  21. public static function getInstance()
  22. {
  23. // Only create the object if it doesn't exist.
  24. if (empty(self::$instance))
  25. {
  26. self::$instance = new JApplication;
  27. }
  28. return self::$instance;
  29. }
  30. private function drop_table_if_exists(){
  31. $queries = array();
  32. foreach(array(
  33. TABLE_MAGENTO_CATEGORY,
  34. TABLE_MAGENTO_PRODUCT,
  35. TABLE_INSALES_COLLECTION,
  36. TABLE_INSALES_PRODUCT,
  37. TABLE_CSV,
  38. TABLE_XLS,
  39. TABLE_URL,
  40. TABLE_PAGE_DOWNLOAD_QUEUE,
  41. TABLE_IMAGE_DOWNLOAD_QUEUE,
  42. TABLE_INSALES_COLLECTION_UPLOAD_QUEUE,
  43. TABLE_INSALES_PRODUCT_UPLOAD_QUEUE,
  44. TABLE_INSALES_IMAGE_UPLOAD_QUEUE,
  45. TABLE_MAGENTO_CATEGORY_UPLOAD_QUEUE,
  46. TABLE_MAGENTO_PRODUCT_UPLOAD_QUEUE,
  47. TABLE_MAGENTO_PRODUCT_DOWNLOAD_QUEUE,
  48. TABLE_MAGENTO_IMAGE_UPLOAD_QUEUE,
  49. TABLE_SETTINGS
  50. ) as $table) $queries[] = 'DROP TABLE IF EXISTS ' . $this->config->dbprefix . $table;
  51. return $queries;
  52. }
  53. private function create_table_if_not_exists(){
  54. $queries = array();
  55. $insaleskeys = array();
  56. $magentokeys = array();
  57. foreach($this->config->insales_product_joins as $key=>$value) {
  58. $insaleskeys[$key]=$this->config->insales_product_fields[$key];
  59. $insaleskeys[$value]=$this->config->csv_fields[$value];
  60. }
  61. foreach($this->config->magento_product_joins as $key=>$value) {
  62. $magentokeys[$key]=$this->config->magento_product_fields[$key];
  63. $magentokeys[$value]=$this->config->csv_fields[$value];
  64. }
  65. $specifications = array(
  66. TABLE_TASK_QUEUE => array(
  67. ID . ' INTEGER',
  68. CLAZZ . ' VARCHAR(100)',
  69. METHOD . ' VARCHAR(100)',
  70. 'PRIMARY KEY (' . ID . ')'
  71. ),
  72. TABLE_MAGENTO_CATEGORY => array(
  73. implode('_',array(CATEGORY,ID)) . ' INTEGER',
  74. implode('_',array(CATEGORY,NAME)) . ' VARCHAR(100)',
  75. 'PRIMARY KEY (' . implode('_',array(CATEGORY,ID)) . ')'
  76. ),
  77. TABLE_MAGENTO_PRODUCT => array(
  78. implode('_',array(PRODUCT,ID)) . ' VARCHAR(100)',
  79. implode('_',array(PRODUCT,SKU)) . ' VARCHAR(100)',
  80. SOURCE . ' TEXT',
  81. 'PRIMARY KEY (' . implode(',', $this->config->magento_product_keys) . ')',
  82. 'INDEX (' . implode(',', array_keys($this->config->magento_product_joins)) . ')'
  83. ),
  84. TABLE_INSALES_COLLECTION => array(
  85. implode('_',array(COLLECTION,ID)) . ' INTEGER',
  86. implode('_',array(COLLECTION,TITLE)) . ' VARCHAR(100)',
  87. 'PRIMARY KEY (' . implode('_',array(COLLECTION,ID)) . ')'
  88. ),
  89. TABLE_INSALES_PRODUCT => array(
  90. SOURCE . ' TEXT',
  91. 'PRIMARY KEY (' . implode(',', $this->config->insales_product_keys) . ')',
  92. 'INDEX (' . implode(',', array_keys($this->config->insales_product_joins)) . ')'
  93. ),
  94. TABLE_CSV => array(
  95. 'PRIMARY KEY (' . implode(',', $this->config->csv_keys) . ')',
  96. 'INDEX (' . implode(',', array_values($this->config->insales_product_joins)) . ')',
  97. 'INDEX (' . implode(',', array_values($this->config->magento_product_joins)) . ')'
  98. ),
  99. TABLE_XLS => array(
  100. 'PRIMARY KEY (' . implode(',', $this->config->xls_keys) . ')',
  101. 'INDEX (' . implode(',', array_keys($this->config->csv_joins)) . ')'
  102. ),
  103. TABLE_URL => array(
  104. 'PRIMARY KEY (' . implode(',', $this->config->url_keys) . ')',
  105. 'INDEX (' . implode(',', array_values($this->config->csv_joins)) . ')'
  106. ),
  107. TABLE_PAGE_DOWNLOAD_QUEUE => array(
  108. URL . ' VARCHAR(255)',
  109. LOADED . ' INTEGER',
  110. 'PRIMARY KEY (' . URL . ')'
  111. ),
  112. TABLE_IMAGE_DOWNLOAD_QUEUE => array(
  113. URL . ' VARCHAR(255)',
  114. FILE . ' VARCHAR(255)',
  115. LOADED . ' INTEGER',
  116. 'PRIMARY KEY (' . FILE . ')'
  117. ),
  118. TABLE_SETTINGS => array(
  119. NAME . ' VARCHAR(100)',
  120. VALUE . ' VARCHAR(100)',
  121. 'PRIMARY KEY (' . NAME . ')'
  122. ),
  123. TABLE_INSALES_COLLECTION_UPLOAD_QUEUE => array(
  124. METHOD . ' VARCHAR(50)',
  125. PATH . ' VARCHAR(100)',
  126. PARAMS . ' TEXT',
  127. STARTED . ' INTEGER',
  128. implode('_',array(COLLECTION,TITLE)) . ' VARCHAR(100)',
  129. 'PRIMARY KEY (' . implode('_',array(COLLECTION,TITLE)) . ')'
  130. ),
  131. TABLE_INSALES_PRODUCT_UPLOAD_QUEUE => array(
  132. METHOD . ' VARCHAR(50)',
  133. PATH . ' VARCHAR(100)',
  134. PARAMS . ' TEXT',
  135. STARTED . ' INTEGER',
  136. ID . ' INTEGER',
  137. implode('',array(IMAGE,1)) . ' VARCHAR(255)',
  138. implode('',array(IMAGE,2)) . ' VARCHAR(255)',
  139. implode('',array(IMAGE,3)) . ' VARCHAR(255)',
  140. implode('',array(IMAGE,4)) . ' VARCHAR(255)',
  141. implode('',array(IMAGE,5)) . ' VARCHAR(255)',
  142. implode('',array(IMAGE,6)) . ' VARCHAR(255)',
  143. 'PRIMARY KEY (' . implode(',', array_keys($insaleskeys)) . ')'
  144. ),
  145. TABLE_INSALES_IMAGE_UPLOAD_QUEUE => array(
  146. METHOD . ' VARCHAR(50)',
  147. PATH . ' VARCHAR(100)',
  148. PARAMS . ' TEXT',
  149. STARTED . ' INTEGER',
  150. IMAGE . ' VARCHAR(255)',
  151. 'PRIMARY KEY (image)'
  152. ),
  153. TABLE_MAGENTO_CATEGORY_UPLOAD_QUEUE => array(
  154. METHOD . ' VARCHAR(50)',
  155. implode('_',array(PARENT,ID)) . ' VARCHAR(50)',
  156. implode('_',array(CHILD,ID)) . ' VARCHAR(50)',
  157. PARAMS . ' TEXT',
  158. STARTED . ' INTEGER',
  159. implode('_',array(CATEGORY,NAME)) . ' VARCHAR(100)',
  160. 'PRIMARY KEY (' . implode('_',array(CATEGORY,NAME)) . ')'
  161. ),
  162. TABLE_MAGENTO_PRODUCT_UPLOAD_QUEUE => array(
  163. METHOD . ' VARCHAR(50)',
  164. implode('_',array(PRODUCT,ID)) . ' VARCHAR(50)',
  165. implode('_',array(PRODUCT,SKU)) . ' VARCHAR(50)',
  166. PARAMS . ' TEXT',
  167. STARTED . ' INTEGER',
  168. implode('',array(IMAGE,1)) . ' VARCHAR(255)',
  169. implode('',array(IMAGE,2)) . ' VARCHAR(255)',
  170. implode('',array(IMAGE,3)) . ' VARCHAR(255)',
  171. implode('',array(IMAGE,4)) . ' VARCHAR(255)',
  172. implode('',array(IMAGE,5)) . ' VARCHAR(255)',
  173. implode('',array(IMAGE,6)) . ' VARCHAR(255)',
  174. 'PRIMARY KEY (' . implode(',', array_keys($magentokeys)) . ')'
  175. ),
  176. TABLE_MAGENTO_PRODUCT_DOWNLOAD_QUEUE => array(
  177. METHOD . ' VARCHAR(50)',
  178. implode('_',array(PRODUCT,ID)) . ' VARCHAR(50)',
  179. implode('_',array(PRODUCT,SKU)) . ' VARCHAR(50)',
  180. STARTED . ' INTEGER',
  181. 'PRIMARY KEY (' . implode(',', array(implode('_',array(PRODUCT,ID)),implode('_',array(PRODUCT,SKU)))) . ')'
  182. ),
  183. TABLE_MAGENTO_IMAGE_UPLOAD_QUEUE => array(
  184. METHOD . ' VARCHAR(50)',
  185. implode('_',array(PRODUCT,ID)) . ' VARCHAR(50)',
  186. implode('_',array(PRODUCT,SKU)) . ' VARCHAR(50)',
  187. implode('_',array(IMAGE,FILE)) . ' VARCHAR(255)',
  188. PARAMS . ' TEXT',
  189. STARTED . ' INTEGER',
  190. IMAGE . ' VARCHAR(255)',
  191. 'PRIMARY KEY (' . IMAGE . ')'
  192. )
  193. );
  194. $list = array(TABLE_INSALES_PRODUCT_UPLOAD_QUEUE=>$insaleskeys,TABLE_MAGENTO_PRODUCT_UPLOAD_QUEUE=>$magentokeys);
  195. foreach(array(TABLE_MAGENTO_PRODUCT,TABLE_INSALES_PRODUCT,TABLE_CSV,TABLE_XLS,TABLE_URL) as $table) {
  196. $fields = implode('_',array($table,'fields')); $list[$table] = $this->config->$fields;
  197. }
  198. foreach($list as $table=>$keys) foreach($keys as $field=>$values) $specifications[$table][] = $field . ' ' . $values[0];
  199. foreach($specifications as $table=>$values) $queries[] = 'CREATE TABLE IF NOT EXISTS ' . $this->config->dbprefix . $table . '(' . implode(',', $values) . ') CHARACTER SET utf8 COLLATE utf8_general_ci';
  200. return $queries;
  201. }
  202. public function rebuild_database(){
  203. $start = microtime(true);
  204. set_time_limit(0);
  205. $this->db->connect();
  206. $this->db->multi_query(implode(';',array_merge($this->drop_table_if_exists(), $this->create_table_if_not_exists())));
  207. $this->db->free_multi_result($result);
  208. $this->db->disconnect();
  209. $duration = microtime(true) - $start;
  210. echo "<pre>Execution time: <b>$duration</b> sec.</pre>";
  211. }
  212. public function info(){
  213. set_time_limit(0);
  214. $this->db->connect();
  215. $columns = array();
  216. foreach(array(
  217. TABLE_MAGENTO_PRODUCT,
  218. TABLE_INSALES_PRODUCT,
  219. TABLE_CSV,
  220. TABLE_XLS,
  221. TABLE_URL
  222. ) as $table) {
  223. $columns[$table] = array();
  224. $fields = $table . '_fields';
  225. foreach($this->config->$fields as $field=>$values) $columns[$table][] = $field . ' ' . $values[0];
  226. }
  227. // Создаём таблицы в случае их отсутствия в базе данных
  228. $result = $this->db->multi_query(implode(';',$this->create_table_if_not_exists()));
  229. $this->db->free_multi_result($result);
  230. $result = $this->db->query('SELECT COUNT(*) FROM ' . $this->config->dbprefix . TABLE_IMAGE_DOWNLOAD_QUEUE . ' WHERE ' . LOADED . '="0"');
  231. $queue = $this->db->fetch_single($result);
  232. $this->db->free_result($result);
  233. $result = $this->db->query('SELECT COUNT(*) FROM ' . $this->config->dbprefix . TABLE_IMAGE_DOWNLOAD_QUEUE);
  234. $queue_total = $this->db->fetch_single($result);
  235. $this->db->free_result($result);
  236. echo "<pre>Image queue: <b>$queue/$queue_total</b> - $queue картинок в очереди ожидает загрузки , $queue_total - всего известных ссылок на картинки с сайта</pre>";
  237. $result = $this->db->query('SELECT COUNT(*) FROM ' . $this->config->dbprefix . TABLE_PAGE_DOWNLOAD_QUEUE . ' WHERE ' . LOADED . '<' . (time()-$this->config->pageupdatetime));
  238. $queue = $this->db->fetch_single($result);
  239. $this->db->free_result($result);
  240. $result = $this->db->query('SELECT COUNT(*) FROM ' . $this->config->dbprefix . TABLE_PAGE_DOWNLOAD_QUEUE);
  241. $queue_total = $this->db->fetch_single($result);
  242. $this->db->free_result($result);
  243. echo "<pre>Page queue: <b>$queue/$queue_total</b> - $queue страниц в очереди ожидает загрузки, $queue_total – всего известных ссылок на страницы сайта</pre>";
  244. foreach(array(
  245. INSALES=>TABLE_INSALES_PRODUCT_UPLOAD_QUEUE,
  246. MAGENTO=>TABLE_MAGENTO_PRODUCT_UPLOAD_QUEUE
  247. ) as $shop=>$table) {
  248. $result = $this->db->query('SELECT COUNT(*) FROM ' . $this->config->dbprefix . $table);
  249. $queue = $this->db->fetch_single($result);
  250. $this->db->free_result($result);
  251. echo "<pre>$shop queue: <b>$queue</b> - $queue карточек товаров в очереди ожидает загрузки на $shop</pre>";
  252. }
  253. foreach(array(
  254. INSALES=>TABLE_INSALES_IMAGE_UPLOAD_QUEUE,
  255. MAGENTO=>TABLE_MAGENTO_IMAGE_UPLOAD_QUEUE
  256. ) as $shop=>$table) {
  257. $result = $this->db->query('SELECT COUNT(*) FROM ' . $this->config->dbprefix . $table);
  258. $queue = $this->db->fetch_single($result);
  259. $this->db->free_result($result);
  260. echo "<pre>$shop image queue: <b>$queue</b> - $queue изображений товаров в очереди ожидает загрузки на $shop</pre>";
  261. }
  262. $result = $this->db->query('SELECT COUNT(*) FROM ' . $this->config->dbprefix . TABLE_URL );
  263. $count = $this->db->fetch_single($result);
  264. $this->db->free_result($result);
  265. echo "<pre>Url records downloaded: <b>$count</b> - количество карточек товаров уже имеется в базе данных по результатам парсинга страниц сайта</pre>";
  266. $result = $this->db->query('SELECT COUNT(*) FROM ' . $this->config->dbprefix . TABLE_XLS );
  267. $count = $this->db->fetch_single($result);
  268. $this->db->free_result($result);
  269. echo "<pre>Xls records downloaded: <b>$count</b> - количество загруженных строк из xls файла</pre>";
  270. $result = $this->db->query('SELECT COUNT(*) FROM ' . $this->config->dbprefix . TABLE_CSV );
  271. $count = $this->db->fetch_single($result);
  272. $this->db->free_result($result);
  273. echo "<pre>Csv records created: <b>$count</b> - количество созданых строк в csv файле</pre>";
  274. foreach(array(
  275. INSALES=>TABLE_INSALES_PRODUCT,
  276. MAGENTO=>TABLE_MAGENTO_PRODUCT
  277. ) as $shop=>$table) {
  278. $result = $this->db->query('SELECT COUNT(*) FROM ' . $this->config->dbprefix . $table );
  279. $count = $this->db->fetch_single($result);
  280. $this->db->free_result($result);
  281. echo "<pre>$shop records downloaded: <b>$count</b> - количество загруженных карточек товара из $shop</pre>";
  282. }
  283. $this->db->disconnect();
  284. }
  285. public function page_curl_cron(){
  286. $start = microtime(true);
  287. set_time_limit(0);
  288. $default = parse_url($this->config->url);
  289. $this->db->connect();
  290. // Очищаем таблицу от ненужных ссылок
  291. $queries = array();
  292. $queries[] = 'DELETE FROM ' . $this->config->dbprefix . TABLE_PAGE_DOWNLOAD_QUEUE . ' WHERE NOT ' . URL . ' LIKE "%' . $default['host'] . '%"';
  293. // Удаляем неправильные ссылки
  294. foreach(array("jpg","jpeg","gif","png","tiff","pdf","doc","xls","ppt","docx","xlsx","pptx","avi","mov","mpg","mpeg","swf","exe","msi","zip","swf") as $ext) $queries[] = 'DELETE FROM ' . $this->config->dbprefix . TABLE_PAGE_DOWNLOAD_QUEUE . ' WHERE ' . URL . ' LIKE "%.' . $ext .'%"';
  295. // Добавляем ссылку на сайт
  296. $queries[] = 'INSERT IGNORE ' . $this->config->dbprefix . TABLE_PAGE_DOWNLOAD_QUEUE . '(' . URL . ',' . LOADED . ') VALUES ("' . safe($this->config->url) . '",0)';
  297. $result = $this->db->multi_query(implode(';',$queries));
  298. $this->db->free_multi_result($result);
  299. // Получаем список ссылок для задания
  300. // В первую очередь обрабатываются ссылки, содержащие в себе слово product
  301. $records = array();
  302. $result = $this->db->query('SELECT * FROM ' . $this->config->dbprefix . TABLE_PAGE_DOWNLOAD_QUEUE . ' WHERE ' . LOADED . '<' . (time()-$this->config->pageupdatetime) .' AND ' . URL . ' LIKE "%product%" ORDER BY ' . LOADED . ' LIMIT ' . ($this->config->pagecronlimit - count($records)));
  303. while($row=$this->db->fetch_row($result)) $records[]=$row[URL];
  304. $this->db->free_result($result);
  305. $result = $this->db->query('SELECT * FROM ' . $this->config->dbprefix . TABLE_PAGE_DOWNLOAD_QUEUE . ' WHERE ' . LOADED . '<' . (time()-$this->config->pageupdatetime) .' AND NOT ' . URL . ' LIKE "%product%" ORDER BY ' . LOADED . ' LIMIT ' . ($this->config->pagecronlimit - count($records)));
  306. while($row=$this->db->fetch_row($result)) $records[]=$row[URL];
  307. $this->db->free_result($result);
  308. foreach($records as $url){
  309. $queries = array();
  310. $pid = -1;
  311. // The pcntl_fork() function creates a child process that differs from the parent process only in its PID and PPID.
  312. // Please see your system's fork(2) man page for specific details as to how fork works on your system.
  313. if($this->config->parallel) $pid = pcntl_fork();
  314. // $pid === -1 failed to fork
  315. // $pid == 0, this is the child thread
  316. // $pid != 0, this is the parent thread
  317. if ($pid > 0) continue;
  318. $html = file_get_contents($url);
  319. if(!$html) {
  320. // Исклучаем из дальнейшей загрузки отсутствующие страницы
  321. $queries[]='DELETE FROM ' . $this->config->dbprefix . TABLE_PAGE_DOWNLOAD_QUEUE . ' WHERE ' . URL . '="' . safe($url) . '"';
  322. // $pid === -1 failed to fork
  323. // $pid == 0, this is the child thread
  324. // $pid != 0, this is the parent thread
  325. $result = $this->db->multi_query(implode(';',$queries));
  326. $this->db->free_multi_result($result);
  327. if(!$pid) break;
  328. continue;
  329. }
  330. // http://stackoverflow.com/questions/3523409/domdocument-encoding-problems-characters-transformed/12846243#12846243
  331. // http://stackoverflow.com/questions/1148928/disable-warnings-when-loading-non-well-formed-html-by-domdocument-php
  332. $doc = new DOMDocument('1.0','utf-8');
  333. libxml_use_internal_errors(true);
  334. $doc->loadHTML($html);
  335. libxml_clear_errors();
  336. $xpath = new DOMXpath($doc);
  337. // Добавляем в поиск все ссылки на странице, на том же домене
  338. $links = array();
  339. $elements = $xpath->query('//a[@href]//@href');
  340. if (!is_null($elements)) {
  341. foreach ($elements as $element) {
  342. $parse = parse_url($element->nodeValue);
  343. if(isset($parse['fragment'])) unset($parse['fragment']);
  344. if(isset($parse['query'])) unset($parse['query']);
  345. $addr = explode('/',unparse_url($parse,$default));
  346. while(!$addr[count($addr)-1]) array_pop($addr);
  347. $links[implode('/',$addr)] = 0;
  348. }
  349. }
  350. foreach($links as $link=>$time) $queries[]='INSERT IGNORE ' . $this->config->dbprefix . TABLE_PAGE_DOWNLOAD_QUEUE . '(' . URL . ',' . LOADED . ') VALUES ("' . $link . '",' . $time . ')';
  351. // Обрабатываем поля на странице
  352. $fields = array();
  353. foreach($this->config->url_fields as $urlfield=>$values){
  354. $elements = $xpath->query($values[1]);
  355. $tokens = array();
  356. if (!is_null($elements)) {
  357. foreach ($elements as $element) $tokens[] = preg_replace($values[2], $values[3], $element->nodeValue);
  358. }
  359. $fields[$urlfield] = safe(trim(implode('',$tokens)));
  360. }
  361. // Обрабатываем транслит изображений
  362. for($i = 1; $i <= 6; $i++){
  363. $src = $fields[IMAGE . $i];
  364. if($src){
  365. $imageUrl = unparse_url(parse_url($src),$default);
  366. $type = explode(".", $imageUrl);
  367. $ext = strtolower($type[count($type)-1]);
  368. $file = $this->config->imagedir . $fields["translit"] . '_' . $i . '.' . $ext;
  369. $fields[IMAGE . $i] = $file;
  370. $queries[]='INSERT IGNORE ' . $this->config->dbprefix . TABLE_IMAGE_DOWNLOAD_QUEUE . '(' . URL . ',' . FILE . ',' . LOADED . ') VALUES ("' . safe($imageUrl) . '","' . safe($file) . '",0)';
  371. }
  372. }
  373. $queries[]='REPLACE ' . $this->config->dbprefix . TABLE_URL . '(' . implode(',', array_keys($fields)) . ') VALUES ("' . implode('","', array_values($fields)) . '")';
  374. $queries[]='REPLACE ' . $this->config->dbprefix . TABLE_PAGE_DOWNLOAD_QUEUE . '(' . URL . ',' . LOADED . ') VALUES ("' . safe($url) . '",' . time() . ')';
  375. $result = $this->db->multi_query(implode(';',$queries));
  376. $this->db->free_multi_result($result);
  377. echo "<pre><a href='$url' target='_blank'>$url</a> complite.</pre>";
  378. // $pid === -1 failed to fork
  379. // $pid == 0, this is the child thread
  380. // $pid != 0, this is the parent thread
  381. if(!$pid) break;
  382. }
  383. $this->db->disconnect();
  384. $duration = microtime(true) - $start;
  385. echo "<pre>Execution time: <b>$duration</b> sec.</pre>";
  386. }
  387. public function image_curl_cron(){
  388. $start = microtime(true);
  389. set_time_limit(0);
  390. //get watermark
  391. $watermark = $this->config->watermark;
  392. //get watermark size
  393. $watermarkSize = getimagesize($watermark);
  394. $watermarkWidth = $watermarkSize[0];
  395. $watermarkHeight = $watermarkSize[1];
  396. //get watermark extension
  397. $type = explode(".", $watermark);
  398. $ext = strtolower($type[count($type)-1]);
  399. $ext = (!in_array($ext, array("jpeg","png","gif"))) ? "jpeg" : $ext;
  400. //create watermark source
  401. $func = "imagecreatefrom".$ext;
  402. $watermarkSource = $func($watermark);
  403. $padding = 0; //padding from image border
  404. $this->db->connect();
  405. $queries = array();
  406. // Очищаем таблицу от ненужных ссылок
  407. // Удаляем неправильные ссылки
  408. foreach(array("html","htm","php","asp","pdf","doc","doc","xls","ppt","docx","xlsx","pptx","avi","mov","mpg","mpeg","swf","exe","msi","zip","swf") as $ext) $queries[] = 'DELETE FROM ' . $this->config->dbprefix . TABLE_IMAGE_DOWNLOAD_QUEUE . ' WHERE ' . URL . ' LIKE "%.' . $ext .'%"';
  409. $result = $this->db->multi_query(implode(';',$queries));
  410. $this->db->free_multi_result($result);
  411. // Получаем список ссылок для задания
  412. $result = $this->db->query('SELECT * FROM ' . $this->config->dbprefix . TABLE_IMAGE_DOWNLOAD_QUEUE . ' WHERE ' . LOADED . '="0" LIMIT ' . $this->config->imagecronlimit);
  413. $records = array(); while($row=$this->db->fetch_row($result)) $records[$row[FILE]]=$row[URL];
  414. $this->db->free_result($result);
  415. $query='REPLACE ' . $this->config->dbprefix . TABLE_IMAGE_DOWNLOAD_QUEUE . '(' . URL . ',' . FILE . ',' . LOADED . ') VALUES (?,?,?)';
  416. foreach($records as $file=>$url){
  417. // помечаем файл сразу как обработанный, чтобы не зависать на одной ошибке
  418. $this->db->execute($query, array($url,$file,time()));
  419. $pid = -1;
  420. // The pcntl_fork() function creates a child process that differs from the parent process only in its PID and PPID.
  421. // Please see your system's fork(2) man page for specific details as to how fork works on your system.
  422. if($this->config->parallel) $pid = pcntl_fork();
  423. // $pid === -1 failed to fork
  424. // $pid == 0, this is the child thread
  425. // $pid != 0, this is the parent thread
  426. if ($pid > 0) continue;
  427. $type = explode(".", $url);
  428. $ext = strtolower($type[count($type)-1]);
  429. $ext = (!in_array($ext, array("jpeg","png","gif"))) ? "jpeg" : $ext;
  430. $tempFile = $this->config->tempimagefilename . getmypid() . '.' . $ext;
  431. // http://stackoverflow.com/questions/1987579/how-to-remove-warning-messages-in-php
  432. error_reporting(E_ERROR | E_PARSE);
  433. unlink($tempFile);
  434. // Загрузка и сохранение файла на диске
  435. $image = file_get_contents($url);
  436. if(!$image) {
  437. // Исклучаем из дальнейшей загрузки отсутствующие страницы
  438. $this->db->execute('DELETE FROM ' . $this->config->dbprefix . TABLE_IMAGE_DOWNLOAD_QUEUE . ' WHERE ' . URL . '= ? AND ' . FILE . '= ?',array($url,$file));
  439. // $pid === -1 failed to fork
  440. // $pid == 0, this is the child thread
  441. // $pid != 0, this is the parent thread
  442. if(!$pid) break;
  443. continue;
  444. }
  445. file_put_contents($tempFile, $image);
  446. $size = getimagesize($tempFile);
  447. $width = $size[0];
  448. $height = $size[1];
  449. try {
  450. $func = "imagecreatefrom".$ext;
  451. $source = $func($tempFile);
  452. //create output resource
  453. $output = imagecreatetruecolor($width, $height);
  454. //to preserve PNG transparency
  455. //saving all full alpha channel information
  456. imagesavealpha($output, true);
  457. //setting completely transparent color
  458. $transparent = imagecolorallocatealpha($output, 0, 0, 0, 127);
  459. //filling created image with transparent color
  460. imagefill($output, 0, 0, $transparent);
  461. //copy source to destination
  462. imagecopyresampled( $output, $source, 0, 0, 0, 0,
  463. $width, $height, $width, $height);
  464. //let's make watermark 1/4 of image size
  465. $wanted_width = round($width/4);
  466. $wanted_height = round($height/4);
  467. if(($watermarkWidth/$wanted_width) < ($watermarkHeight/$wanted_height))
  468. {
  469. //resize by height
  470. $wanted_width = ($watermarkWidth*$wanted_height)/$watermarkHeight;
  471. }
  472. else
  473. {
  474. //resize by width
  475. $wanted_height = ($watermarkHeight*$wanted_width)/$watermarkWidth;
  476. }
  477. //bottom right
  478. $dst_x = $width - $padding - $wanted_width;
  479. $dst_y = $height-$padding-$wanted_height;
  480. //copy watermark
  481. imagecopyresampled( $output, $watermarkSource, $dst_x, $dst_y, 0, 0,
  482. $wanted_width, $wanted_height, $watermarkWidth, $watermarkHeight);
  483. $func = IMAGE.$ext;
  484. $func($output, $file);
  485. }
  486. catch (Exception $e)
  487. {
  488. }
  489. // http://stackoverflow.com/questions/1987579/how-to-remove-warning-messages-in-php
  490. error_reporting(E_ERROR | E_PARSE);
  491. unlink($tempFile);
  492. echo "<pre><a href='$url' target='_blank'>$url</a> complite.</pre>";
  493. // $pid === -1 failed to fork
  494. // $pid == 0, this is the child thread
  495. // $pid != 0, this is the parent thread
  496. if(!$pid) break;
  497. }
  498. $this->db->disconnect();
  499. $duration = microtime(true) - $start;
  500. echo "<pre>Execution time: <b>$duration</b> sec.</pre>";
  501. }
  502. // Удаление всех записей из таблицы
  503. private function clear_table($table){
  504. $start = microtime(true);
  505. set_time_limit(0);
  506. $this->db->connect();
  507. $this->db->execute('TRUNCATE ' . $this->config->dbprefix . $table);
  508. $this->db->disconnect();
  509. $duration = microtime(true) - $start;
  510. echo "<pre>Execution time: <b>$duration</b> sec.</pre>";
  511. }
  512. // Удаление всех записей из таблицы
  513. public function clear_csv(){ $this->clear_table(TABLE_CSV); }
  514. public function clear_xls(){ $this->clear_table(TABLE_XLS); }
  515. public function clear_url(){ $this->clear_table(TABLE_URL); }
  516. public function clear_page(){ $this->clear_table(TABLE_PAGE_DOWNLOAD_QUEUE); }
  517. public function clear_image(){ $this->clear_table(TABLE_IMAGE_DOWNLOAD_QUEUE); }
  518. public function clear_magento_product(){ $this->clear_table(TABLE_MAGENTO_PRODUCT); }
  519. public function clear_magento_category(){ $this->clear_table(TABLE_MAGENTO_CATEGORY); }
  520. public function clear_insales_product(){ $this->clear_table(TABLE_INSALES_PRODUCT); }
  521. public function clear_insales_collection(){ $this->clear_table(TABLE_INSALES_COLLECTION); }
  522. public function clear_settings(){ $this->clear_table(TABLE_SETTINGS); }
  523. public function clear_insales(){
  524. $start = microtime(true);
  525. set_time_limit(0);
  526. $this->db->connect();
  527. $queries = array();
  528. foreach(array(
  529. TABLE_INSALES_COLLECTION,
  530. TABLE_INSALES_PRODUCT,
  531. TABLE_INSALES_COLLECTION_UPLOAD_QUEUE,
  532. TABLE_INSALES_PRODUCT_UPLOAD_QUEUE,
  533. TABLE_INSALES_IMAGE_UPLOAD_QUEUE
  534. ) as $table) $queries[]='TRUNCATE ' . $this->config->dbprefix . $table;
  535. $result = $this->db->multi_query(implode(';',$queries));
  536. $this->db->free_multi_result($result);
  537. $this->db->disconnect();
  538. $duration = microtime(true) - $start;
  539. echo "<pre>Execution time: <b>$duration</b> sec.</pre>";
  540. }
  541. public function clear_magento(){
  542. $start = microtime(true);
  543. set_time_limit(0);
  544. $this->db->connect();
  545. $queries = array();
  546. foreach(array(
  547. TABLE_MAGENTO_PRODUCT,
  548. TABLE_MAGENTO_CATEGORY,
  549. TABLE_MAGENTO_PRODUCT_DOWNLOAD_QUEUE,
  550. TABLE_MAGENTO_CATEGORY_UPLOAD_QUEUE,
  551. TABLE_MAGENTO_PRODUCT_UPLOAD_QUEUE,
  552. TABLE_MAGENTO_IMAGE_UPLOAD_QUEUE
  553. ) as $table) $queries[]='TRUNCATE ' . $this->config->dbprefix . $table;
  554. $result = $this->db->multi_query(implode(';',$queries));
  555. $this->db->free_multi_result($result);
  556. $this->db->disconnect();
  557. $duration = microtime(true) - $start;
  558. echo "<pre>Execution time: <b>$duration</b> sec.</pre>";
  559. }
  560. public function import_url(){
  561. $start = microtime(true);
  562. set_time_limit(0);
  563. $duration = microtime(true) - $start;
  564. echo "<pre>Execution time: <b>$duration</b> sec.</pre>";
  565. }
  566. // Импорт записей из файла в таблицу
  567. public function import_xls(){
  568. $start = microtime(true);
  569. set_time_limit(0);
  570. $type = explode(".", $this->config->xls);
  571. $ext = strtolower($type[count($type)-1]);
  572. $tempFile = $this->config->tempxlsfilename . getmypid() . '.' . $ext;
  573. // http://stackoverflow.com/questions/1987579/how-to-remove-warning-messages-in-php
  574. error_reporting(E_ERROR | E_PARSE);
  575. unlink($tempFile);
  576. // Загрузка и сохранение файла на диске
  577. file_put_contents($tempFile, file_get_contents($this->config->xls));
  578. $inputFileType = PHPExcel_IOFactory::identify($tempFile);
  579. $reader = PHPExcel_IOFactory::createReader($inputFileType);
  580. $excel = $reader->load($tempFile);
  581. $sheet = $excel->getActiveSheet();
  582. $outline = array_fill(0,10,0);
  583. $this->db->connect();
  584. $query = 'REPLACE ' . $this->config->dbprefix . TABLE_XLS . '(' . implode(',',array_keys($this->config->xls_fields)) . ') VALUES (' . implode(',',array_fill(0,count($this->config->xls_fields),'?')) . ')';
  585. foreach($sheet->getRowIterator() as $rowIterator){
  586. $row = $rowIterator->getRowIndex();
  587. $outline[$sheet->getRowDimension($row)->getOutlineLevel()]=$row;
  588. $values = array(); foreach($this->config->xls_fields as $xlsfield) $values[] = trim(eval($xlsfield[1]));
  589. $this->db->execute($query,$values);
  590. }
  591. // Удаление строк с пустой ценой
  592. $this->db->execute('DELETE FROM ' . $this->config->dbprefix . TABLE_XLS . ' WHERE Column11=""');
  593. $this->db->disconnect();
  594. // http://stackoverflow.com/questions/1987579/how-to-remove-warning-messages-in-php
  595. error_reporting(E_ERROR | E_PARSE);
  596. unlink($tempFile);
  597. $duration = microtime(true) - $start;
  598. echo "<pre>Execution time: <b>$duration</b> sec.</pre>";
  599. }
  600. // Импорт записей из файла в таблицу
  601. public function import_csv(){
  602. $start = microtime(true);
  603. set_time_limit(0);
  604. // http://stackoverflow.com/questions/3895819/csv-export-import-with-phpexcel
  605. $inputFileType = PHPExcel_IOFactory::identify($this->config->csv);
  606. $reader = PHPExcel_IOFactory::createReader($inputFileType);
  607. $csv = $reader->load($this->config->csv);
  608. $sheet = $csv->getActiveSheet();
  609. $this->db->connect();
  610. $query = 'REPLACE ' . $this->config->dbprefix . TABLE_CSV . '(' . implode(',',array_keys($this->config->csv_fields)) . ') VALUES (' . implode(',',array_fill(0,count($this->config->csv_fields),'?')) . ')';
  611. foreach($sheet->getRowIterator() as $rowIterator){
  612. $row = $rowIterator->getRowIndex();
  613. if(!$row) continue; // Пропускаем строку заголовков колонок
  614. $values = array(); $col = 0;
  615. foreach($this->config->csv_fields as $csvfield) $values[] = $sheet->getCellByColumnAndRow($col++,$row)->getValue();
  616. $this->db->execute($query,$values);
  617. }
  618. $this->db->execute('DELETE FROM ' . $this->config->dbprefix . TABLE_CSV . ' WHERE Value12="0"');
  619. $this->db->disconnect();
  620. $duration = microtime(true) - $start;
  621. echo "<pre>Execution time: <b>$duration</b> sec.</pre>";
  622. }
  623. // Обновление записей в таблице
  624. public function update_csv(){
  625. $start = microtime(true);
  626. set_time_limit(0);
  627. $this->db->connect();
  628. $queries = array();
  629. $csv_fields = array(); foreach($this->config->csv_fields as $csvfield=>$values) if($values[2]) $csv_fields[$csvfield]=$values[2];
  630. $where = array(); foreach($this->config->csv_joins as $key=>$value) $where[] = TABLE_XLS . '.' . $key . '=' . TABLE_URL . '.' .$value;
  631. $queries[] = 'REPLACE ' . $this->config->dbprefix . TABLE_CSV . '(' . implode(',', array_keys($csv_fields)) . ') SELECT ' . implode(',', array_values($csv_fields)) . ' FROM ' . $this->config->dbprefix . TABLE_XLS . ' AS ' . TABLE_XLS . ' ' . $this->config->csv_join_type . ' ' . $this->config->dbprefix . TABLE_URL . ' AS ' . TABLE_URL . ' ON ' . implode(' AND ', $where);
  632. $queries[] = 'DELETE FROM ' . $this->config->dbprefix . TABLE_CSV . ' WHERE Value12="0"';
  633. $result = $this->db->multi_query(implode(';',$queries));
  634. $this->db->free_multi_result($result);
  635. $this->db->disconnect();
  636. $duration = microtime(true) - $start;
  637. echo "<pre>Execution time: <b>$duration</b> sec.</pre>";
  638. }
  639. // Экспорт записей в файл
  640. public function export_csv(){
  641. $start = microtime(true);
  642. set_time_limit(0);
  643. $addr = explode('/', $this->config->imagehost);
  644. // http://stackoverflow.com/questions/1987579/how-to-remove-warning-messages-in-php
  645. error_reporting(E_ERROR | E_PARSE);
  646. unlink($this->config->csv);
  647. $file = fopen($this->config->csv,"w");
  648. // http://www.skoumal.net/en/making-utf-8-csv-excel
  649. //add BOM to fix UTF-8 in Excel
  650. fputs($file, $bom =( chr(0xEF) . chr(0xBB) . chr(0xBF) ));
  651. // The fputcsv() function formats a line as CSV and writes it to an open file.
  652. $headers = array(); foreach($this->config->csv_fields as $field) $headers[] = $field[1];
  653. fputcsv($file,$headers,';'); // Добавляем строку с заголовками колонок
  654. $where = array(); foreach($this->config->csv_joins as $key=>$value) $where[] = TABLE_XLS . '.' . $key . '=' . TABLE_URL . '.' .$value;
  655. $this->db->connect();
  656. $result = $this->db->query('SELECT * FROM ' . $this->config->dbprefix . TABLE_XLS . ' AS ' . TABLE_XLS . ' ' . $this->config->csv_join_type . ' ' . $this->config->dbprefix . TABLE_URL . ' AS ' . TABLE_URL . ' ON ' . implode(' AND ', $where));
  657. while($row=$this->db->fetch_row($result)){
  658. for($i = 1; $i <= 6; $i++) if($row[IMAGE . $i]) {
  659. $addr[count($addr) - 1] = $row[IMAGE . $i];
  660. $row[IMAGE . $i] = implode('/', $addr);
  661. }
  662. $values = array(); foreach($this->config->csv_fields as $field) $values[] = $field[2]?$row[$field[2]]:'';
  663. // The fputcsv() function formats a line as CSV and writes it to an open file.
  664. fputcsv($file,$values,';');
  665. }
  666. $this->db->free_result($result);
  667. $this->db->disconnect();
  668. fclose($file);
  669. $duration = microtime(true) - $start;
  670. echo "<pre>Execution time: <b>$duration</b> sec.</pre>";
  671. }
  672. /*
  673. 1. Преобразование прайса www.tursportopt.ru/price/opt.xls в базовый формат каталога товаров
  674. 2. При формировании файла необходимо парсить по названию товара страницы на сайте поставщика, например: http://tursportopt.ru/category/kovea/
  675. 3. Скачиваем все картинки, параметры и описание
  676. 4. Параметры подставляем в соответсвующие столбцы в базовом файле
  677. 5. Картинки скачиваем на хостиг и добавляем прямую ссылку на файл в базовый excel. Не забываем про водный знак
  678. 6. Цена продажи = РРЦ (нужно, чтобы столбец можно было настраивать в конфиге)
  679. 7. Цена закупки = столбец D (нужно, чтобы столбец можно было настраивать в конфиге)
  680. */
  681. public function task1(){
  682. $start = microtime(true);
  683. set_time_limit(0);
  684. $this->db->connect();
  685. $result = $this->db->query('SELECT MAX(' . ID . ') FROM ' . $this->config->dbprefix . TABLE_TASK_QUEUE);
  686. $taskId = $this->db->fetch_single($result); $taskId=$taskId?$taskId+1:1;
  687. $this->db->free_result($result);
  688. $columns = array(ID,CLAZZ,METHOD);
  689. $query = 'REPLACE ' . $this->config->dbprefix . TABLE_TASK_QUEUE . '(' . implode(',',$columns) . ') VALUES (' . implode(',',array_fill(0,count($columns),'?')) . ')';
  690. $this->db->execute($query,array($taskId++,APPLICATION,'clear_xls'));
  691. $this->db->execute($query,array($taskId++,APPLICATION,'clear_csv'));
  692. $this->db->execute($query,array($taskId++,APPLICATION,'import_xls'));
  693. $this->db->execute($query,array($taskId++,APPLICATION,'update_csv'));
  694. $this->db->execute($query,array($taskId++,APPLICATION,'export_csv'));
  695. $this->db->disconnect();
  696. $duration = microtime(true) - $start;
  697. echo "<pre>Execution time: <b>$duration</b> sec.</pre>";
  698. }
  699. public function task(){
  700. // http://stackoverflow.com/questions/486181/php-suppress-output-within-a-function
  701. ob_start();
  702. $start = microtime(true);
  703. set_time_limit(0);
  704. $this->db->connect();
  705. $addr = explode('/', $this->config->imagehost);
  706. $queries = array();
  707. // Очистка временных таблиц
  708. foreach(array(TABLE_XLS) as $table) $queries[] = 'TRUNCATE ' . $this->config->dbprefix . $table;
  709. $result = $this->db->multi_query(implode(';',$queries));
  710. $this->db->free_multi_result($result);
  711. // Загрузка xls файла
  712. $type = explode(".", $this->config->xls);
  713. $ext = strtolower($type[count($type)-1]);
  714. $tempFile = $this->config->tempxlsfilename . getmypid() . '.' . $ext;
  715. // http://stackoverflow.com/questions/1987579/how-to-remove-warning-messages-in-php
  716. error_reporting(E_ERROR | E_PARSE);
  717. unlink($tempFile);
  718. // Загрузка и сохранение файла на диске
  719. file_put_contents($tempFile, file_get_contents($this->config->xls));
  720. $inputFileType = PHPExcel_IOFactory::identify($tempFile);
  721. $reader = PHPExcel_IOFactory::createReader($inputFileType);
  722. $excel = $reader->load($tempFile);
  723. $sheet = $excel->getActiveSheet();
  724. $outline = array_fill(0,10,0);
  725. $query = 'REPLACE ' . $this->config->dbprefix . TABLE_XLS . '(' . implode(',',array_keys($this->config->xls_fields)) . ') VALUES (' . implode(',',array_fill(0,count($this->config->xls_fields),'?')) . ')';
  726. foreach($sheet->getRowIterator() as $rowIterator){
  727. $row = $rowIterator->getRowIndex();
  728. $outline[$sheet->getRowDimension($row)->getOutlineLevel()]=$row;
  729. $values = array(); foreach($this->config->xls_fields as $xlsfield) $values[] = trim(eval($xlsfield[1]));
  730. $this->db->execute($query,$values);
  731. }
  732. // Удаление строк с пустой ценой
  733. $this->db->execute('DELETE FROM ' . $this->config->dbprefix . TABLE_XLS . ' WHERE Column11=""');
  734. // http://stackoverflow.com/questions/1987579/how-to-remove-warning-messages-in-php
  735. error_reporting(E_ERROR | E_PARSE);
  736. unlink($tempFile);
  737. $tempFile = $this->config->tempcsvfilename . getmypid() . '.' . 'csv';
  738. // http://stackoverflow.com/questions/1987579/how-to-remove-warning-messages-in-php
  739. error_reporting(E_ERROR | E_PARSE);
  740. unlink($tempFile);
  741. // http://stackoverflow.com/questions/16251625/how-to-create-and-download-a-csv-file-from-php-script
  742. $file = fopen($tempFile,"w");
  743. // http://www.skoumal.net/en/making-utf-8-csv-excel
  744. //add BOM to fix UTF-8 in Excel
  745. fputs($file, $bom =( chr(0xEF) . chr(0xBB) . chr(0xBF) ));
  746. // The fputcsv() function formats a line as CSV and writes it to an open file.
  747. $headers = array(); foreach($this->config->csv_fields as $field) $headers[] = $field[1];
  748. fputcsv($file,$headers,';'); // Добавляем строку с заголовками колонок
  749. $where = array(); foreach($this->config->csv_joins as $key=>$value) $where[] = TABLE_XLS . '.' . $key . '=' . TABLE_URL . '.' .$value;
  750. $result = $this->db->query('SELECT * FROM ' . $this->config->dbprefix . TABLE_XLS . ' AS ' . TABLE_XLS . ' ' . $this->config->csv_join_type . ' ' . $this->config->dbprefix . TABLE_URL . ' AS ' . TABLE_URL . ' ON ' . implode(' AND ', $where));
  751. while($row=$this->db->fetch_row($result)){
  752. for($i = 1; $i <= 6; $i++) if($row[IMAGE . $i]) {
  753. $addr[count($addr) - 1] = $row[IMAGE . $i];
  754. $row[IMAGE . $i] = implode('/', $addr);
  755. }
  756. $values = array(); foreach($this->config->csv_fields as $field) $values[] = $field[2]?$row[$field[2]]:'';
  757. // The fputcsv() function formats a line as CSV and writes it to an open file.
  758. fputcsv($file,$values,';');
  759. }
  760. $this->db->free_result($result);
  761. $this->db->disconnect();
  762. fclose($file);
  763. // http://stackoverflow.com/questions/486181/php-suppress-output-within-a-function
  764. ob_end_clean();
  765. ob_start();
  766. header('Accept-Ranges: bytes');
  767. header('Content-Type: application/csv; charset=UTF-8');
  768. header('Content-Disposition: attachement; filename="' . $this->config->csv . '"');
  769. header("Content-Length: " . filesize($tempFile));
  770. readfile($tempFile);
  771. ob_end_flush();
  772. // http://stackoverflow.com/questions/486181/php-suppress-output-within-a-function
  773. ob_start();
  774. // http://stackoverflow.com/questions/1987579/how-to-remove-warning-messages-in-php
  775. error_reporting(E_ERROR | E_PARSE);
  776. unlink($tempFile);
  777. $duration = microtime(true) - $start;
  778. echo "<pre>Execution time: <b>$duration</b> sec.</pre>";
  779. // http://stackoverflow.com/questions/486181/php-suppress-output-within-a-function
  780. ob_end_clean();
  781. }
  782. public function cron(){
  783. $start = microtime(true);
  784. set_time_limit(0);
  785. $this->db->connect();
  786. $result = $this->db->query('SELECT * FROM ' . $this->config->dbprefix . TABLE_TASK_QUEUE . ' ORDER BY ' . ID);
  787. $rows = $this->db->fetch_all_rows($result);
  788. $this->db->free_result($result);
  789. $this->db->disconnect();
  790. $query = 'DELETE FROM ' . $this->config->dbprefix . TABLE_TASK_QUEUE . ' WHERE ' . ID . '=?';
  791. foreach($rows as $row){
  792. $id = $row[ID];
  793. $clazz = $row[CLAZZ];
  794. $method = $row[METHOD];
  795. try
  796. {
  797. $instance = new $clazz();
  798. $instance->$method();
  799. }
  800. catch (Exception $e)
  801. {
  802. var_dump($e);
  803. }
  804. $values = array($id);
  805. echo "<pre>$clazz $method complite.</pre>";
  806. $this->db->connect();
  807. $this->db->execute($query,$values);
  808. $this->db->disconnect();
  809. }
  810. $duration = microtime(true) - $start;
  811. echo "<pre>Execution time: <b>$duration</b> sec.</pre>";
  812. }
  813. }