PageRenderTime 63ms CodeModel.GetById 32ms RepoModel.GetById 0ms app.codeStats 0ms

/wp-content/plugins/wp-rss-poster/include/wrp_dojob.php

https://bitbucket.org/silverlogic/dms
PHP | 416 lines | 263 code | 56 blank | 97 comment | 27 complexity | ff10cd1be997b28f4594162ba4874884 MD5 | raw file
Possible License(s): GPL-2.0, JSON, AGPL-1.0, LGPL-2.1
  1. <?php
  2. //function for PHP error handling
  3. function wrp_joberrorhandler($errno, $errstr, $errfile, $errline) {
  4. global $wrp_dojob_message, $jobwarnings, $joberrors;
  5. //genrate timestamp
  6. if (!function_exists('memory_get_usage')) { // test if memory functions compiled in
  7. $timestamp="<span style=\"background-color:c3c3c3;\" title=\"[Line: ".$errline."|File: ".basename($errfile)."\">".date_i18n('Y-m-d H:i.s').":</span> ";
  8. } else {
  9. $timestamp="<span style=\"background-color:c3c3c3;\" title=\"[Line: ".$errline."|File: ".basename($errfile)."|Mem: ".wrp_formatBytes(@memory_get_usage(true))."|Mem Max: ".wrp_formatBytes(@memory_get_peak_usage(true))."|Mem Limit: ".ini_get('memory_limit')."]\">".date_i18n('Y-m-d H:i.s').":</span> ";
  10. }
  11. switch ($errno) {
  12. case E_NOTICE:
  13. case E_USER_NOTICE:
  14. $massage=$timestamp."<span>".$errstr."</span>";
  15. break;
  16. case E_WARNING:
  17. case E_USER_WARNING:
  18. $jobwarnings += 1;
  19. $massage=$timestamp."<span style=\"background-color:yellow;\">".__('[WARNING]','wpematico')." ".$errstr."</span>";
  20. break;
  21. case E_ERROR:
  22. case E_USER_ERROR:
  23. $joberrors += 1;
  24. $massage=$timestamp."<span style=\"background-color:red;\">".__('[ERROR]','wpematico')." ".$errstr."</span>";
  25. break;
  26. case E_DEPRECATED:
  27. case E_USER_DEPRECATED:
  28. $massage=$timestamp."<span>".__('[DEPRECATED]','wpematico')." ".$errstr."</span>";
  29. break;
  30. case E_STRICT:
  31. $massage=$timestamp."<span>".__('[STRICT NOTICE]','wpematico')." ".$errstr."</span>";
  32. break;
  33. case E_RECOVERABLE_ERROR:
  34. $massage=$timestamp."<span>".__('[RECOVERABLE ERROR]','wpematico')." ".$errstr."</span>";
  35. break;
  36. default:
  37. $massage=$timestamp."<span>[".$errno."] ".$errstr."</span>";
  38. break;
  39. }
  40. if (!empty($massage)) {
  41. $wrp_dojob_message .= $massage."<br />\n";
  42. if ($errno==E_ERROR or $errno==E_CORE_ERROR or $errno==E_COMPILE_ERROR) {//Die on fatal php errors.
  43. die("Fatal Error:" . $errno);
  44. }
  45. //300 is most webserver time limit. 0= max time! Give script 5 min. more to work.
  46. @set_time_limit(300);
  47. //true for no more php error hadling.
  48. return true;
  49. } else {
  50. return false;
  51. }
  52. }
  53. /**
  54. * WRP_DOJOB PHP class for WordPress
  55. *
  56. */
  57. class wrp_dojob{
  58. private $jobid=0;
  59. private $posts=0;
  60. private $job;
  61. public function __construct($jobid) {
  62. global $wpdb,$wrp_dojob_message, $jobwarnings, $joberrors;
  63. $jobwarnings=0;
  64. $joberrors=0;
  65. @ini_get('safe_mode','Off'); //disable safe mode
  66. @ini_set('ignore_user_abort','Off'); //Set PHP ini setting
  67. ignore_user_abort(true); //user can't abort script (close windows or so.)
  68. $this->job = wrp_get_data($jobid); //set job id
  69. //set function for PHP user defineid error handling
  70. if (defined(WP_DEBUG) and WP_DEBUG)
  71. set_error_handler('wrp_joberrorhandler',E_ALL | E_STRICT);
  72. else
  73. set_error_handler('wrp_joberrorhandler',E_ALL & ~E_NOTICE);
  74. //check max script execution tme
  75. if (ini_get('safe_mode') or strtolower(ini_get('safe_mode'))=='on' or ini_get('safe_mode')=='1')
  76. trigger_error(sprintf(__('PHP Safe Mode is on!!! Max exec time is %1$d sec.','wrp'),ini_get('max_execution_time')),E_USER_WARNING);
  77. // check function for memorylimit
  78. if (!function_exists('memory_get_usage')) {
  79. ini_set('memory_limit', apply_filters( 'admin_memory_limit', '256M' )); //Wordpress default
  80. trigger_error(sprintf(__('Memory limit set to %1$s ,because can not use PHP: memory_get_usage() function to dynamically increase the Memory!','wrp'),ini_get('memory_limit')),E_USER_WARNING);
  81. }
  82. //run job parts
  83. //$data = $this->job;
  84. //var_dump($this->job);
  85. //$rss_url = $data['rss_url'];
  86. //var_dump($rss_url);
  87. $count = 0;
  88. $count = $this->processFeed($this->job, $this->job['rss_url']); #- ---- Proceso todos los feeds
  89. $this->posts += $count;
  90. $this->job_end(); //call regualar job end
  91. }
  92. /**
  93. * Processes a feed
  94. *
  95. * @param $campaign array Campaign data
  96. * @param $feed URL string Feed
  97. * @return The number of items added to database
  98. */
  99. private function processFeed(&$campaign, &$feed) {
  100. @set_time_limit(0);
  101. // Log
  102. trigger_error(sprintf(__('Processing feed %1s.','wrp'),$feed),E_USER_NOTICE);
  103. // Access the feed
  104. $simplepie = fetchFeed($feed, false, $campaign['number']);
  105. // Get posts (last is first)
  106. $items = array();
  107. $count = 0;
  108. foreach($simplepie->get_items() as $item) {
  109. /* if($feed->hash == $this->getItemHash($item)) { // a la primer coincidencia ya vuelve
  110. if($count == 0) $this->log('No new posts');
  111. break;
  112. }
  113. */
  114. if($this->isDuplicate($campaign, $feed, $item)) {
  115. trigger_error(__('Filtering duplicated posts.','wrp'),E_USER_NOTICE);
  116. break;
  117. }
  118. $count++;
  119. array_unshift($items, $item);
  120. if($count == $campaign['number']) {
  121. trigger_error(sprintf(__('Campaign fetch limit reached at %1s.','wrp'),$campaign['number']),E_USER_NOTICE);
  122. break;
  123. }
  124. }
  125. // Processes post stack
  126. foreach($items as $item) {
  127. $this->processItem($campaign, $simplepie, $item);
  128. //$lasthash = $this->getItemHash($item);
  129. }
  130. // If we have added items, let's update the hash
  131. if($count) {
  132. trigger_error(sprintf(__('%s posts added','wrp'),$count),E_USER_NOTICE);
  133. }
  134. return $count;
  135. }
  136. private function isDuplicate(&$campaign, &$feed, &$item) {
  137. // Agregar variables para chequear duplicados solo de esta campa?a o de cada feed ( grabados en post_meta) o por titulo y permalink
  138. global $wpdb, $wp_locale, $current_blog;
  139. $table_name = $wpdb->prefix . "posts";
  140. $title = $item->get_title();// . $item->get_permalink();
  141. $query="SELECT post_title,id FROM $table_name
  142. WHERE post_title = '".$title."'
  143. AND ((`post_status` = 'published') OR (`post_status` = 'publish' ) OR (`post_status` = 'draft' ) OR (`post_status` = 'private' ))";
  144. //GROUP BY post_title having count(*) > 1" ;
  145. $row = $wpdb->get_row($query);
  146. trigger_error(sprintf(__('Checking duplicated title \'%1s\'','wrp'),$title).': '.((!! $row) ? __('Yes') : __('No')) ,E_USER_NOTICE);
  147. return !! $row;
  148. }
  149. /**
  150. * Processes an item
  151. *
  152. * @param $campaign object Campaign database object
  153. * @param $feed object Feed database object
  154. * @param $item object SimplePie_Item object
  155. */
  156. function processItem(&$campaign, &$feed, &$item) {
  157. global $wpdb;
  158. trigger_error(sprintf(__('Processing item %1s','wrp'),$item->get_title()),E_USER_NOTICE);
  159. // Item content
  160. //$content = $this->parseItemContent($campaign, $feed, $item);
  161. $link = $item->get_permalink();
  162. if(false !== strpos($link,'news.google.com')){
  163. $link=urldecode(substr($link,strpos($link,'url=')+4));
  164. }elseif(false !== strpos($link,'/**')){
  165. $link=urldecode(substr($link,strpos($link,'/**')+3));
  166. }
  167. $content = wrp_full_feed($link, $campaign, $item);
  168. if(!empty($campaign['exclude'])){
  169. $pos = strpos($content, $campaign['exclude']);
  170. $content = substr_replace($content, '', $pos, -1);
  171. }
  172. if($campaign['cache_image'] == 'true') {
  173. $content = $this->processImageCache($content);
  174. }
  175. // Template parse
  176. if ($campaign['enable_template'] == 'true'){
  177. $vars = array(
  178. '{content}',
  179. '{title}',
  180. '{permalink}',
  181. '{feedurl}',
  182. '{feedtitle}',
  183. '{feeddescription}',
  184. '{feedlogo}'
  185. );
  186. $replace = array(
  187. $content,
  188. $item->get_title(),
  189. $item->get_link(),
  190. $feed->feed_url,
  191. $feed->get_title(),
  192. $feed->get_description(),
  193. $feed->get_image_url()
  194. );
  195. $content = str_ireplace($vars, $replace, ($campaign['template']) ? stripslashes($campaign['template']) : '{content}');
  196. }
  197. // Item date
  198. /* if($campaign->feeddate && ($item->get_date('U') > (current_time('timestamp', 1) - $campaign->frequency) && $item->get_date('U') < current_time('timestamp', 1)))
  199. $date = $item->get_date('U');
  200. else */
  201. //$date = null;
  202. switch($campaign['publish_date']){
  203. case 'immediately':
  204. $date = time();
  205. break;
  206. case 'rss':
  207. $date = $item->get_date('U');
  208. break;
  209. }
  210. // Categories
  211. $categories = json_decode($campaign['category']); //$this->getCampaignData($campaign->id, 'categories');
  212. // Meta
  213. $meta = array(
  214. 'wpe_campaignid' => $this->jobid, //campaign['jobid'],
  215. 'wpe_feed' => $feed,
  216. 'wpe_sourcepermalink' => $item->get_permalink()
  217. );
  218. // Create post
  219. $postid = $this->insertPost($wpdb->escape($item->get_title()), $wpdb->escape($content), $date, $categories, $campaign['status'], $campaign['author']);
  220. /*
  221. // If pingback/trackbacks
  222. if($campaign['campaign_allowpings']) {
  223. trigger_error(__('Processing item pingbacks','wpematico'),E_USER_NOTICE);
  224. require_once(ABSPATH . WPINC . '/comment.php');
  225. pingback($content, $postid);
  226. }
  227. */
  228. }
  229. function processImageCache($content){
  230. $images = $this->parseImages($content);
  231. $urls = $images[2];
  232. if(sizeof($urls)) { // Si hay alguna imagen en el feed
  233. trigger_error(__('Uploading images.','wrp'),E_USER_NOTICE);
  234. foreach($urls as $imagen_src) {
  235. $bits = @file_get_contents($imagen_src);
  236. $name = substr(strrchr($imagen_src, "/"),1);
  237. $afile = wp_upload_bits( $name, NULL, $bits);
  238. if(!$afile['error'])
  239. $content = str_replace($imagen_src, $afile['url'], $content);
  240. else { // Si no la pudo subir intento con mi funcion
  241. trigger_error('wp_upload_bits error:'.print_r($afile,true).', trying custom function.',E_USER_WARNING);
  242. $upload_dir = wp_upload_dir();
  243. $imagen_dst = $upload_dir['path'] . str_replace('/','',strrchr($imagen_src, '/'));
  244. $imagen_dst_url = $upload_dir['url']. '/' . str_replace('/','',strrchr($imagen_src, '/'));
  245. if(in_array(str_replace('.','',strrchr($imagen_dst, '.')),explode(',','jpg,gif,png,tif,bmp'))) { // -------- Controlo extensiones permitidas
  246. trigger_error('imagen_src='.$imagen_src.' <b>to</b> imagen_dst='.$imagen_dst.'<br>',E_USER_NOTICE);
  247. $newfile = $this->guarda_imagen($imagen_src, $imagen_dst);
  248. }
  249. if($newfile) $content = str_replace($imagen_src, $imagen_dst_url, $content);
  250. }
  251. }
  252. }
  253. return $content;
  254. }
  255. /**
  256. * Writes a post to blog * *
  257. * @param string $title Post title
  258. * @param string $content Post content
  259. * @param integer $timestamp Post timestamp
  260. * @param array $category Array of categories
  261. * @param string $status 'draft', 'published' or 'private'
  262. * @param integer $authorid ID of author.
  263. * @param boolean $allowpings Allow pings
  264. * @param boolean $comment_status 'open', 'closed', 'registered_only'
  265. * @param array $meta Meta key / values
  266. * @return integer Created post id
  267. */
  268. function insertPost($title, $content, $timestamp = null, $category = null, $status = 'publish', $authorid = null, $allowpings = true, $comment_status = 'open', $meta = array()) {
  269. $date = ($timestamp) ? gmdate('Y-m-d H:i:s', $timestamp + (get_option('gmt_offset') * 3600)) : null;
  270. $postid = wp_insert_post(array(
  271. 'post_title' => $title,
  272. 'post_content' => $content,
  273. 'post_content_filtered' => $content,
  274. 'post_category' => $category,
  275. 'post_status' => $status,
  276. 'post_author' => $authorid,
  277. 'post_date' => $date,
  278. 'comment_status' => $comment_status,
  279. 'ping_status' => ($allowpings) ? "open" : "closed"
  280. ));
  281. /*
  282. foreach($meta as $key => $value)
  283. $this->insertPostMeta($postid, $key, $value);
  284. */
  285. return $postid;
  286. }
  287. private function job_end() {
  288. trigger_error(sprintf(__('Job done in %1s sec.','wrp'),'10'),E_USER_NOTICE);
  289. }
  290. public function __destruct() {
  291. global $wrp_dojob_message;
  292. return $wrp_dojob_message;
  293. }
  294. /**
  295. * Adjunta un archivo ya subido al postid dado
  296. */
  297. function insertfileasattach($filename,$postid) {
  298. $wp_filetype = wp_check_filetype(basename($filename), null );
  299. $attachment = array(
  300. 'post_mime_type' => $wp_filetype['type'],
  301. 'post_title' => preg_replace('/\.[^.]+$/', '', basename($filename)),
  302. 'post_content' => '',
  303. 'post_status' => 'inherit'
  304. );
  305. $attach_id = wp_insert_attachment( $attachment, $filename, $postid );
  306. trigger_error(__('Attaching file:').$filename,E_USER_NOTICE);
  307. if (!$attach_id)
  308. trigger_error(__('Sorry, your attach could not be inserted. Something wrong happened.').print_r($filename,true),E_USER_WARNING);
  309. // you must first include the image.php file for the function wp_generate_attachment_metadata() to work
  310. require_once(ABSPATH . "wp-admin" . '/includes/image.php');
  311. $attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
  312. wp_update_attachment_metadata( $attach_id, $attach_data );
  313. }
  314. /* Guardo imagen en mi servidor
  315. EJEMPLO
  316. guarda_imagen("http://ablecd.wz.cz/vendeta/fuhrer/hitler-pretorians.jpg","/usr/home/miweb.com/web/iimagen.jpg");
  317. Si el archivo destino ya existe guarda una copia de la forma "filename[n].ext"
  318. ***************************************************************************************/
  319. function guarda_imagen ($url_origen,$archivo_destino){
  320. $mi_curl = curl_init ($url_origen);
  321. if(!$mi_curl) {
  322. return false;
  323. }else{
  324. $i = 1;
  325. while (file_exists( $archivo_destino )) {
  326. $file_extension = strrchr($archivo_destino, '.'); //Will return .JPEG substr($url_origen, strlen($url_origen)-4, strlen($url_origen));
  327. $file_name = substr($archivo_destino, 0, strlen($archivo_destino)-strlen($file_extension));
  328. $archivo_destino = $file_name."[$i]".$file_extension;
  329. $i++;
  330. }
  331. $fs_archivo = fopen ($archivo_destino, "w");
  332. // if(is_writable($fs_archivo)) {
  333. curl_setopt ($mi_curl, CURLOPT_FILE, $fs_archivo);
  334. curl_setopt ($mi_curl, CURLOPT_HEADER, 0);
  335. curl_exec ($mi_curl);
  336. curl_close ($mi_curl);
  337. fclose ($fs_archivo);
  338. return $archivo_destino;
  339. // }
  340. }
  341. }
  342. /**
  343. * insertPostMeta * *
  344. */
  345. function insertPostMeta($postid, $key, $value) {
  346. global $wpdb;
  347. $result = $wpdb->query( "INSERT INTO $wpdb->postmeta (post_id,meta_key,meta_value ) "
  348. . " VALUES ('$postid','$key','$value') ");
  349. return $wpdb->insert_id;
  350. }
  351. /**
  352. * Devuelve todas las imagenes del contenido
  353. */
  354. function parseImages($text){
  355. preg_match_all('/<img(.+?)src=\"(.+?)\"(.*?)>/', $text, $out);
  356. return $out;
  357. }
  358. }
  359. ?>