source: branches/1.2/content/plugins/autoreader/autoreader_settings.php @ 1324

Revision 1324, 41.6 KB checked in by shibuya246, 3 years ago (diff)

[branch 1.2] latest updates, added dashboard, fixed duplicate id on editing, added saving job to cron

Line 
1<?php
2/**
3 * File: plugins/autoreader/autoreader_settings.php
4 * Purpose: The functions for autoreader.
5 *
6 * PHP version 5
7 *
8 * LICENSE: Hotaru CMS is free software: you can redistribute it and/or
9 * modify it under the terms of the GNU General Public License as
10 * published by the Free Software Foundation, either version 3 of
11 * the License, or (at your option) any later version.
12 *
13 * Hotaru CMS is distributed in the hope that it will be useful, but WITHOUT
14 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
15 * FITNESS FOR A PARTICULAR PURPOSE.
16 *
17 * You should have received a copy of the GNU General Public License along
18 * with Hotaru CMS. If not, see http://www.gnu.org/licenses/.
19 *
20 * @category  Content Management System
21 * @package   HotaruCMS
22 * @author    shibuya246 <blog@shibuya246.com>
23 * @copyright Copyright (c) 2009, Hotaru CMS
24 * @license   http://www.gnu.org/copyleft/gpl.html GNU General Public License
25 * @link      http://www.hotarucms.org/
26 * *
27 * Ported from original WP Plugin WP-O-Matic
28 * Description: Enables administrators to create posts automatically from RSS/Atom feeds.
29 * Author: Guillermo Rauch
30 * Plugin URI: http://devthought.com/wp-o-matic-the-wordpress-rss-agreggator/
31 * Version: 1.0RC4-6
32 *
33 * Additions for Image cache, original url link, category search, tags, thumbnail, short excertps, code change for hotaru by shibuya246
34 */
35
36  require_once(PLUGINS . 'autoreader/inc/tools.class.php' );
37  require_once(PLUGINS . 'autoreader/helper/form.helper.php' );
38  require_once(PLUGINS . 'autoreader/helper/tag.helper.php');
39
40 
41class AutoreaderSettings
42{
43     /**
44     * Admin settings for the Tweet This plugin
45     */
46    public function settings($h)
47    {
48        // include language file
49        $h->includeLanguage();
50
51        $template_call = $h->cage->post->testAlnumLines('autoreader_template');
52
53       
54
55        switch($template_call) {
56            case 'autoreader_list': {
57                $h->displayTemplate($template_call);
58            }
59
60            default : {
61
62                // show header
63                echo "<h1>" . $h->lang["autoreader_settings_header"] . "</h1>\n";
64                ?>
65
66                <div id="admin_plugin_menu">
67                    <ul class="dropdown">
68                        <li><a name="autoreader_dashboard" href="#">Dashboard</a></li>
69                        <li><a name="autoreader_list" href="#">Campaigns</a>
70                            <ul class="sub_menu">
71                                <li><a name="autoreader_add" href="#">Add Campaign</a>
72                                    <ul class="sub_menu">
73                                        <li><a name="autoreader_add" href="#">Add Campaign</a></li>
74                                        <li><a name="autoreader_list" href="#">List Campaigns</a></li>
75                                     </ul>
76                                </li>
77                                <li><a name="autoreader_list" href="#">List Campaigns</a></li>
78                            </ul>
79                        </li>
80                        <li><a name="autoreader_options" href="#">Options</a></li>
81                    </ul>
82                </div>
83
84                <div id="admin_plugin_content">
85
86                </div>
87
88                <?php
89                // Get settings from database if they exist...
90                $autoreader_settings = $h->getSerializedSettings();
91            }
92        }
93    }
94
95    /**
96     * Get Option Settings, update if required
97     *
98     *
99     */
100    public function getOptionSettings($h, $options = null)
101    {
102        print "---" . $h->plugin->folder;
103        $autoreader_settings = $h->getSerializedSettings();
104     
105        if ($h->cage->post->testAlpha('action') == "save" ) {
106            $array = array('saved' => 'true');
107            $autoreader_settings['wpo_log'] = $h->cage->post->testAlnumLines('option_logging');
108            $autoreader_settings['wpo_log_stdout'] =  $h->cage->post->testAlnumLines('option_log_stdout');
109            $autoreader_settings['wpo_unixcron'] =  $h->cage->post->testAlnumLines('option_unixcron');
110            $autoreader_settings['wpo_croncode'] =  $h->cage->post->testAlnumLines('option_croncode');
111            $autoreader_settings['wpo_cacheimage'] = $h->cage->post->testAlnumLines('option_cachimage');
112            $autoreader_settings['wpo_cachepath'] = $h->cage->post->testAlnumLines('option_cachepath');
113
114            $h->updateSetting('autoreader_settings', serialize($autoreader_settings));
115        }
116        else { $array = $autoreader_settings; }
117       
118        return $array;
119    }
120
121
122
123   /**
124   * Retrieves campaigns from database
125   *
126   *
127   */
128  public function getCampaigns($h, $args = '')
129  {       
130    $where ="";
131        if(! empty($search))
132          $where .= " AND title LIKE '%{$search}%' ";
133     $orderby =""; $ordertype=""; $limit="";
134        //if($unparsed)
135        //  $where .= " AND active = 1 AND (frequency + UNIX_TIMESTAMP(lastactive)) < ". (current_time('timestamp', true) - get_option('gmt_offset') * 3600) . " ";
136
137        $sql = "SELECT * FROM {$this->db['campaign']} WHERE 1 = 1 $where "
138         . ""; //ORDER BY $orderby $ordertype $limit";
139
140    //print $sql; 
141    return $h->db->get_results($sql); 
142  }
143
144
145    /**
146   * Retrieves feeds for a certain campaign
147   *
148   * @param   integer   $id     Campaign id
149   */
150  function getCampaignFeeds($h,$id)
151  {
152    return $h->db->get_results("SELECT * FROM {$this->db['campaign_feed']} WHERE campaign_id = $id");
153  }
154
155
156  /**
157   * Retrieves all posts for a certain campaign
158   *
159   * @param   integer   $id     Campaign id
160   */
161  function getCampaignPosts($h, $id)
162  {
163    return $h->db->get_results("SELECT post_id FROM {$this->db['campaign_post']} WHERE campaign_id = $id ");
164  }
165
166  /**
167   * Adds a feed by url and campaign id
168   *
169   *
170   */
171  function addCampaignFeed($h, $id, $feed)
172  {
173
174    $simplepie = $this->fetchFeed($feed, true);
175    $url = $h->db->escape($simplepie->subscribe_url());
176
177    // If it already exists, ignore it
178    if(! $h->db->get_var("SELECT id FROM {$this->db['campaign_feed']} WHERE campaign_id = $id AND url = '$url' "))
179    {
180      $h->db->query(WPOTools::insertQuery($this->db['campaign_feed'],
181        array('url' => $url,
182              'title' => $h->db->escape($simplepie->get_title()),
183              'description' => $h->db->escape($simplepie->get_description()),
184              'logo' =>$h->db->escape($simplepie->get_image_url()),
185              'campaign_id' => $id)
186      )); 
187
188      return  $h->db->insert_id;
189    }
190
191    return false;
192  }
193
194
195
196
197
198
199
200     /**
201       * List campaigns section
202       *
203       *
204       */
205      public function adminList($h)
206      {
207        if(isset($_REQUEST['q']))
208        {
209          $q = $_REQUEST['q'];
210          $campaigns = $this->getCampaigns('search=' . $q);
211        } else
212          $campaigns = $this->getCampaigns('orderby=CREATED_ON');
213       
214      }
215
216      /**
217       * Add campaign section
218       *
219       *
220       */
221      public function adminAdd($h)
222      {
223        $data = $this->campaign_structure;
224        $data_add = $h->cage->post->testAlnumLines('campaign_add');
225
226        if(isset($data_add))
227        {         
228          if($this->errno)
229            $data = $this->campaign_data;
230          else
231            $addedid = $this->adminProcessAdd();
232        }
233
234        $author_usernames = $this->getBlogUsernames();
235        $campaign_add = true;
236       // include(WPOTPL . 'edit.php');
237      }
238
239
240      /**
241   * Edit campaign section
242   *
243   *
244   */
245  function adminEdit($h)
246  {
247     $id = $h->cage->get->testInt('id');
248    if(!$id) die("Can't be called directly");
249
250//    if(isset($_REQUEST['campaign_edit']))
251//    {
252//      check_admin_referer('wpomatic-edit-campaign');
253//
254//      $data = $this->campaign_data;
255//      $submitted = true;
256//
257//      if(! $this->errno)
258//      {
259//        $this->adminProcessEdit($h, $id);
260//        $edited = true;
261//        $data = $this->getCampaignData($h, $id);
262//      }
263//    } else
264      $data = $this->getCampaignData($h, $id);
265
266   // $author_usernames = $this->getBlogUsernames();
267    $campaign_edit = true;
268
269   // include(WPOTPL . 'edit.php');
270    return $data;
271  }
272
273  function adminEditCategories($h, $data, $parent = 0, $level = 0, $categories = 0)
274  {
275        if ( !$categories )       
276        $args = array("orderby"=>"category_order", "order"=>"ASC");
277                $categories = $h->getCategories($args);
278   
279        if ( $categories ) {
280
281        require_once(LIBS . 'Category.php');
282        $catObj = new Category();
283        $depth = 1;
284
285                echo "<ul class='categories_widget'>\n";
286        foreach ($categories as $cat) {
287            $cat_level = 1;    // top level category.           
288            if ($cat->category_safe_name != "all") {
289                echo '<li class="required pad'.$depth.'">';
290                if ($cat->category_parent > 1) {
291                    $depth = $catObj->getCatLevel($h, $cat->category_id, $cat_level, $categories);
292                    for($i=1; $i<$depth; $i++) {
293                        echo "--- ";
294                    }
295                }
296                $category = stripslashes(html_entity_decode(urldecode($cat->category_name), ENT_QUOTES,'UTF-8'));               
297                echo radiobutton_tag('campaign_categories[]', $cat->category_id, in_array($cat->category_id, $data['categories']), 'id=category_' .$cat->category_id);
298                echo "&nbsp;" . label_for('category_' .  $cat->category_id, $category) .  "</li>\n";
299            }
300        }
301        echo "</ul>\n";
302        } else {
303                return false;
304        }
305
306  }
307
308  /**
309   * Resets a campaign (sets post count to 0, forgets last parsed post)
310   *
311   *
312   * @todo Make it ajax-compatible here and add javascript code
313   */
314  function adminReset($h)
315  {
316    $id = intval($_REQUEST['id']);
317
318    if(! defined('DOING_AJAX'))
319      check_admin_referer('reset-campaign_'.$id);
320
321    // Reset count and lasactive
322    $wpdb->query(WPOTools::updateQuery($this->db['campaign'], array(
323      'count' => 0,
324      'lastactive' => 0
325    ), "id = $id"));
326
327    // Reset feeds hashes, count, and lasactive
328    foreach($this->getCampaignFeeds($id) as $feed)
329    {
330      $wpdb->query(WPOTools::updateQuery($this->db['campaign_feed'], array(
331        'count' => 0,
332        'lastactive' => 0,
333        'hash' => ''
334      ), "id = {$feed->id}"));
335    }
336
337    if(defined('DOING_AJAX'))
338      die('1');
339    else
340      $this->adminList();
341  }
342
343  /**
344   * Deletes a campaign
345   *
346   *
347   */
348  function adminDelete($h)
349  {
350
351    $id = intval($_REQUEST['id']);
352
353    // If not called through admin-ajax.php
354    if(! defined('DOING_AJAX'))
355      check_admin_referer('delete-campaign_'.$id);
356
357    $h->db->query("DELETE FROM {$this->db['campaign']} WHERE id = $id");
358    $h->db->query("DELETE FROM {$this->db['campaign_feed']} WHERE campaign_id = $id");
359    $h->db->query("DELETE FROM {$this->db['campaign_word']} WHERE campaign_id = $id");
360    $h->db->query("DELETE FROM {$this->db['campaign_category']} WHERE campaign_id = $id");
361
362    if(defined('DOING_AJAX'))
363      die('1');
364    else
365      $this->adminList();
366  }
367
368  /**
369   * Options section
370   *
371   *
372   */
373  function adminOptions($h)
374  {
375
376    if(isset($_REQUEST['update']))
377    {
378      update_option('wpo_unixcron',     isset($_REQUEST['option_unixcron']));
379      update_option('wpo_log',          isset($_REQUEST['option_logging']));
380      update_option('wpo_log_stdout',   isset($_REQUEST['option_logging_stdout']));
381      update_option('wpo_cacheimages',  isset($_REQUEST['option_caching']));
382      update_option('wpo_cachepath',    rtrim($_REQUEST['option_cachepath'], '/'));
383
384      $updated = 1;
385    }
386
387    if(!is_writable($this->cachepath))
388      $not_writable = true;
389
390    include(WPOTPL . 'options.php');
391  }
392
393
394 /**
395   * Called by cron.php to update the site
396   *
397   *
398   */
399  function runCron($h, $log = true)
400  {
401    $this->log($h, 'Running cron job');
402    $this->processAll($h);
403  }
404
405  /**
406   * Finds a suitable command to run cron
407   *
408   * @return string command
409   **/
410  function getCommand()
411  {
412    $commands = array(
413      @WPOTools::getBinaryPath('curl'),
414      @WPOTools::getBinaryPath('wget'),
415      @WPOTools::getBinaryPath('lynx', ' -dump'),
416      @WPOTools::getBinaryPath('ftp')
417    );
418
419    return WPOTools::pick($commands[0], $commands[1], $commands[2], $commands[3], '<em>{wget or similar command here}</em>');
420  }
421
422  /**
423   * Determines what the title has to link to
424   *
425   * @return string new text
426   **/
427  function filterPermalink($h, $url)
428  {
429    // if from admin panel
430    if($this->admin)
431      return $url;
432
433    if(get_the_ID())
434    {
435        $campaignid = (int) get_post_meta(get_the_ID(), 'wpo_campaignid', true);
436
437        if($campaignid)
438        {
439          $campaign = $this->getCampaignById($campaignid);
440          if($campaign->linktosource)
441            return get_post_meta(get_the_ID(), 'wpo_sourcepermalink', true);
442        }
443
444        return $url;
445    }
446  }
447
448
449
450
451    /**
452   * Processes all campaigns
453   *
454   */
455  function processAll($h)
456  {
457    @set_time_limit(0);
458
459    $campaigns = $this->getCampaigns($h, 'unparsed=1');
460
461    foreach($campaigns as $campaign)
462    {
463      $this->processCampaign($h, $campaign);
464    }
465  }
466
467  /**
468   * Processes a campaign
469   *
470   * @param   object    $campaign   Campaign database object
471   * @return  integer   Number of processed items
472   */
473  function processCampaign($h, &$campaign)
474  {
475    @set_time_limit(0);
476    ob_implicit_flush();
477
478    // Get campaign
479    $campaign = is_numeric($campaign) ? $this->getCampaignById($h,$campaign) : $campaign;
480
481    // Log
482    $this->log($h, 'Processing campaign ' . $campaign->title . ' (ID: ' . $campaign->id . ')');
483
484    // Get feeds
485    $count = 0;
486    $feeds = $this->getCampaignFeeds($h, $campaign->id);
487
488    foreach($feeds as $feed)
489      $count += $this->processFeed($h, $campaign, $feed);
490    $h->db->query(WPOTools::updateQuery($this->db['campaign'], array(
491      'count' => $campaign->count + $count,
492      'lastactive' => time() //('mysql', true)
493    ), "id = {$campaign->id}"));
494
495    return $count;
496  }
497
498  /**
499   * Processes a feed
500   *
501   * @param   $campaign   object    Campaign database object
502   * @param   $feed       object    Feed database object
503   * @return  The number of items added to database
504   */
505
506  function processFeed($h, &$campaign, &$feed)
507  {   
508
509    @set_time_limit(0);
510
511    // Log
512    $this->log($h, 'Processing feed ' . $feed->title . ' (ID: ' . $feed->id . ')');
513
514    // Access the feed
515    $simplepie = $this->fetchFeed($feed->url, false, $campaign->max);
516
517    // Get posts (last is first)
518    $items = array();
519    $count = 0;
520
521    foreach($simplepie->get_items() as $item)
522    {
523      if($feed->hash == $this->getItemHash($item))
524      {
525        if($count == 0) $this->log($h, 'No new posts');
526        break;
527      }
528
529      if($this->isDuplicate($h, $campaign, $feed, $item))
530      {
531        $this->log($h, 'Filtering duplicate post');
532        break;
533      }
534
535      $count++;
536      array_unshift($items, $item);
537
538      if($count == $campaign->max)
539      {
540        $this->log($h, 'Campaign fetch limit reached at ' . $campaign->max);
541        break;
542      }
543    }
544
545    // Processes post stack
546    foreach($items as $item)
547    {
548      $this->processItem($h, $campaign, $feed, $item);
549      $lasthash = $this->getItemHash($item);
550    }
551
552    // If we have added items, let's update the hash
553    if($count)
554    {
555      $h->db->query(WPOTools::updateQuery($this->db['campaign_feed'], array(
556        'count' => $count,
557        'lastactive' => time(),//current_time('mysql', true),
558        'hash' => $lasthash
559      ), "id = {$feed->id}"));
560
561      $this->log($h, $count . ' posts added' );
562    }
563
564    return $count;
565  }
566
567
568 /**
569   * Processes an item
570   *
571   * @param   $item       object    SimplePie_Item object
572   */
573  function getItemHash($item)
574  {   
575    return sha1($item->get_title() . $item->get_permalink());
576  }
577
578
579   /**
580   * Processes an item
581   *
582   * @param   $campaign   object    Campaign database object
583   * @param   $feed       object    Feed database object
584   * @param   $item       object    SimplePie_Item object
585   */
586  function processItem($h, &$campaign, &$feed, &$item)
587  {
588    $this->log($h, 'Processing item');
589
590    // Item content
591    $content = $this->parseItemContent($h, $campaign, $feed, $item);
592
593    // Item date
594   /* if($campaign->feeddate && ($item->get_date('U') > (current_time('timestamp', 1) - $campaign->frequency) && $item->get_date('U') < current_time('timestamp', 1)))
595      $date = $item->get_date('U');
596    else
597      $date = null;*/
598
599           if($campaign->feeddate)
600         $date = $item->get_date('U');
601    else
602      $date = null;
603
604    // Categories
605    $categories = $this->getCampaignData($h, $campaign->id, 'categories');
606
607    // Meta
608    $permalink=$item->get_permalink();
609    $root=$_SERVER['HTTP_HOST'];
610
611//              $posturl=file_get_contents("http://$root/wp-content/plugins/wp-o-matic/original_url.php?blog=$permalink");
612
613//    $posturl = $this->get_sourceurl($permalink);
614$posturl =  $permalink;
615
616
617    $meta = array(
618      'wpo_campaignid' => $campaign->id,
619      'wpo_feedid' => $feed->id,
620      'wpo_sourcepermalink' =>$posturl,
621//        'wpo_website' => $wpo_website
622    );
623 
624 
625        //tags
626    $post_tags=$item->get_categories();
627
628        $tag_list="";
629        if($post_tags)
630         {
631                foreach($post_tags as $post_tag)
632                 $tag_list.=$post_tag->term.",";
633         $tag_list = trim($tag_list,',');
634         }
635     
636    // Create post
637    $postid = $this->insertPost($h, $h->db->escape($item->get_title()), $h->db->escape($content), $date, $categories, $tag_list, $campaign->posttype, $campaign->authorid, $campaign->allowpings, $campaign->comment_status, $meta);
638
639   
640    /*
641    // If pingback/trackbacks
642    if($campaign->dopingbacks)
643    {
644      $this->log('Processing item pingbacks');
645
646      require_once(ABSPATH . WPINC . '/comment.php');
647        pingback($content, $postid);
648    }
649*/
650
651    // Save post to log database
652    $h->db->query(WPOTools::insertQuery($this->db['campaign_post'], array(
653      'campaign_id' => $campaign->id,
654      'feed_id' => $feed->id,
655      'post_id' => $postid,
656      'hash' => $this->getItemHash($item)
657    )));
658  }
659
660
661
662 /**
663   * Processes an item
664   *
665   * @param   $campaign   object    Campaign database object
666   * @param   $feed       object    Feed database object
667   * @param   $item       object    SimplePie_Item object
668   */
669  function isDuplicate($h, &$campaign, &$feed, &$item)
670  {
671    $hash = $this->getItemHash($item);
672    $row = $h->db->get_row("SELECT * FROM {$this->db['campaign_post']} "
673                          . "WHERE campaign_id = {$campaign->id} AND feed_id = {$feed->id} AND hash = '$hash' ");
674    return !! $row;
675  }
676
677
678 /**
679   * Writes a post to blog
680   *
681   *
682   * @param   string    $title            Post title
683   * @param   string    $content          Post content
684   * @param   integer   $timestamp        Post timestamp
685   * @param   array     $category         Array of categories
686   * @param   string    $status           'draft', 'published' or 'private'
687   * @param   integer   $authorid         ID of author.
688   * @param   boolean   $allowpings       Allow pings
689   * @param   boolean   $comment_status   'open', 'closed', 'registered_only'
690   * @param   array     $meta             Meta key / values
691   * @return  integer   Created post id
692   */
693  function insertPost($h, $title, $content, $timestamp = null, $category = null, $tags= null, $status = 'pending', $authorid = null, $allowpings = true, $comment_status = 'open', $meta = array())
694  {
695    $date = ($timestamp) ? gmdate('Y-m-d H:i:s', $timestamp + (get_option('gmt_offset') * 3600)) : null;
696
697    $h->post = new Post();
698
699    $h->post->title =  $title;
700    $h->post->url = make_url_friendly($title);
701    $h->post->content = $content;
702    $h->post->type = 'news';
703    $h->post->category = "";
704    $h->post->tags = $tags;
705    $h->post->author = $h->currentUser->id;
706    $h->post->status = $status;
707
708    $h->addPost();
709
710
711   /* $postid = wp_insert_post(array(
712        'post_title'                => $title,
713                'post_content'                  => $content,
714                'post_content_filtered'         => $content,
715                'post_category'           => $category,
716                'post_status'             => $status,
717                'post_author'             => $authorid,
718                'post_date'               => $date,
719                'comment_status'          => $comment_status,
720                'ping_status'             => $allowpings
721    ));
722
723                foreach($meta as $key => $value)
724                        $this->insertPostMeta($postid, $key, $value);
725*/
726        $postid = $h->post->vars['last_insert_id'];
727
728                return $postid;
729  }
730
731  /**
732   * insertPostMeta
733   *
734   *
735   */
736        function insertPostMeta($h, $postid, $key, $value) {
737
738                $result = $h->db->query( "INSERT INTO $h->db->postmeta (post_id,meta_key,meta_value ) "
739                                                        . " VALUES ('$postid','$key','$value') ");
740                                       
741                return $h->db->insert_id;
742        }
743
744
745
746
747
748
749
750
751
752
753
754
755
756/**
757   * Checks submitted campaign edit form for errors
758   *
759   *
760   * @return array  errors
761   */
762  function adminCampaignRequest($h)
763  {
764    $data_active = $h->cage->post->testAlnumLines('campaign_active');
765    $data_template = $h->cage->post->testAlnumLines('campaign_templatechk');
766    $data_cacheimages = $h->cage->post->keyExists('campaign_cacheimages');
767    $data_feeddate = $h->cage->post->keyExists('campaign_feeddate');
768    $data_allowpings = $h->cage->post->keyExists('campaign_allowpings');
769    $data_dopingbacks = $h->cage->post->keyExists('campaign_dopingbacks');
770    $data_linktosource =  $h->cage->post->testInt('campaign_linktosource');
771
772    # Main data
773    $this->campaign_data = $this->campaign_structure;
774    $this->campaign_data['main'] = array(
775        'title'         => $h->cage->post->testAlnumLines('campaign_title'),
776        'active'        => (isset( $data_active)),
777        'slug'          => $h->cage->post->testAlnumLines('campaign_slug'),
778        'template'      => (isset($data_template))
779                            ? $data = $h->cage->post->testAlnumLines('campaign_template') : null,
780        'frequency'     => intval($h->cage->post->testInt('campaign_frequency_d')) * 86400
781                          + intval($h->cage->post->testInt('campaign_frequency_h')) * 3600
782                          + intval($h->cage->post->testInt('campaign_frequency_m')) * 60,
783        'cacheimages'   => (int) isset( $data_cacheimages),
784        'feeddate'      => (int) isset( $data_feeddate),
785        'posttype'      => $h->cage->post->testAlpha('campaign_posttype'),
786        'author'        => $h->cage->post->testAlpha('campaign_author'),
787        'comment_status' => $h->cage->post->testAlpha('campaign_commentstatus'),
788        'allowpings'    => (int) isset($data_allowpings),
789        'dopingbacks'   => (int) isset( $data_dopingbacks),
790        'max'           => intval($h->cage->post->testInt('campaign_max')),
791        'linktosource'  => (int) isset($data_linktosource)
792    );
793
794    // New feeds
795   
796    $results=($h->cage->post->getRaw('campaign_feed/new'));
797   
798    foreach( $results as $i => $feed)
799    {
800      $feed = trim($feed);
801
802      if(!empty($feed))
803      {
804        if(!isset($this->campaign_data['feeds']['new']))
805          $this->campaign_data['feeds']['new'] = array();
806
807        $this->campaign_data['feeds']['new'][$i] = $feed;
808      }
809    }
810
811    // Existing feeds to delete
812    if(isset($data['campaign_feed']['delete']))
813    {
814      $this->campaign_data['feeds']['delete'] = array();
815
816      foreach($data['campaign_feed']['delete'] as $feedid => $yes)
817        $this->campaign_data['feeds']['delete'][] = intval($feedid);
818    }
819
820    // Existing feeds.
821    if(isset($data['id']))
822    {
823      $this->campaign_data['feeds']['edit'] = array();
824      foreach($this->getCampaignFeeds(intval($data['id'])) as $feed)
825        $this->campaign_data['feeds']['edit'][$feed->id] = $feed->url;
826    }
827
828    // Categories
829    if(isset($data['campaign_categories']))
830    {
831      foreach($data['campaign_categories'] as $category)
832      {
833        $id = intval($category);
834        $this->campaign_data['categories'][] = $category;
835      }
836    }
837
838    # New categories
839    if(isset($data['campaign_newcat']))
840    {
841      foreach($data['campaign_newcat'] as $k => $on)
842      {
843        $catname = $data['campaign_newcatname'][$k];
844        if(!empty($catname))
845        {
846          if(!isset($this->campaign_data['categories']['new']))
847            $this->campaign_data['categories']['new'] = array();
848
849          $this->campaign_data['categories']['new'][] = $catname;
850        }
851      }
852    }
853
854   // Rewrites
855    if(isset($data['campaign_word_origin']))
856    {
857      foreach($data['campaign_word_origin'] as $id => $origin_data)
858      {
859        $rewrite = isset($data['campaign_word_option_rewrite'])
860                && isset($data['campaign_word_option_rewrite'][$id]);
861        $relink = isset($data['campaign_word_option_relink'])
862                && isset($data['campaign_word_option_relink'][$id]);
863
864        if($rewrite || $relink)
865        {
866          $rewrite_data = trim($data['campaign_word_rewrite'][$id]);
867          $relink_data = trim($data['campaign_word_relink'][$id]);
868
869          // Relink data field can't be empty
870          if(($relink && !empty($relink_data)) || !$relink)
871          {
872            $regex = isset($data['campaign_word_option_regex'])
873                  && isset($data['campaign_word_option_regex'][$id]);
874
875            $data = array();
876            $data['origin'] = array('search' => $origin_data, 'regex' => $regex);
877
878            if($rewrite)
879              $data['rewrite'] = $rewrite_data;
880
881            if($relink)
882              $data['relink'] = $relink_data;
883
884            $this->campaign_data['rewrites'][] = $data;
885          }
886        }
887      }
888    }
889
890    $errors = array('basic' => array(), 'feeds' => array(), 'categories' => array(),
891                    'rewrite' => array(), 'options' => array());
892
893    # Main
894    if(empty($this->campaign_data['main']['title']))
895    {
896      $errors['basic'][] = 'You have to enter a campaign title';
897      $this->errno++;
898    }
899
900    # Feeds
901    $feedscount = 0;
902
903    if(isset($this->campaign_data['feeds']['new'])) $feedscount += count($this->campaign_data['feeds']['new']);
904    if(isset($this->campaign_data['feeds']['edit'])) $feedscount += count($this->campaign_data['feeds']['edit']);
905    if(isset($this->campaign_data['feeds']['delete'])) $feedscount -= count($this->campaign_data['feeds']['delete']);
906
907    if(!$feedscount)
908    {
909      $errors['feeds'][] ='You have to enter at least one feed';
910      $this->errno++;
911    } else {
912      if(isset($this->campaign_data['feeds']['new']))
913      {
914        foreach($this->campaign_data['feeds']['new'] as $feed)
915        {
916          $simplepie = $this->fetchFeed($feed, true);
917          if($simplepie->error())
918          {
919            $errors['feeds'][] = 'Feed <strong>' . $feed . '</strong> could not be parsed (SimplePie said: ' . $simplepie->error() . ')';
920            $this->errno++;
921          }
922        }
923      }
924    }
925
926    # Categories
927    if(! sizeof($this->campaign_data['categories']))
928    {
929      $errors['categories'][] ='Select at least one category';
930      $this->errno++;
931    }
932
933    # Rewrite
934    if(sizeof($this->campaign_data['rewrites']))
935    {
936      foreach($this->campaign_data['rewrites'] as $rewrite)
937      {
938        if($rewrite['origin']['regex'])
939        {
940          if(false === @preg_match($rewrite['origin']['search'], ''))
941          {
942            $errors['rewrites'][] = 'There\'s an error with the supplied RegEx expression';
943            $this->errno++;
944          }
945        }
946      }
947    }
948
949    # Options
950//    if(! get_userdatabylogin($this->campaign_data['main']['author']))
951//    {
952//      $errors['options'][] = __('Author username not found', 'wpomatic');
953//      $this->errno++;
954//    }
955
956    if(! $this->campaign_data['main']['frequency'])
957    {
958      $errors['options'][] ='Selected frequency is not valid';
959      $this->errno++;
960    }
961
962    if(! ($this->campaign_data['main']['max'] === 0 || $this->campaign_data['main']['max'] > 0))
963    {
964      $errors['options'][] ='Max items should be a valid number (greater than zero)';
965      $this->errno++;
966    }
967
968    if($this->campaign_data['main']['cacheimages'] && !is_writable($this->cachepath))
969    {
970      $errors['options'][] = 'Cache path (in <a href="' . $this->adminurl . '&s=options">Options</a>) must be writable before enabling image caching.';
971      $this->errno++;
972    }
973
974    $this->errors = $errors;
975    return $errors;
976    //print_r ( $this->errors);
977    //exit;
978  }
979
980  /**
981   * Creates a campaign, and runs processEdit. If processEdit fails, campaign is removed
982   *
983   * @return campaign id if created successfully, errors if not
984   */
985  function adminProcessAdd($h)
986  {   
987    // Insert a campaign with dumb data
988    $h->db->query(WPOTools::insertQuery($this->db['campaign'], array('lastactive' => 0, 'count' => 0)));
989    $cid = $h->db->insert_id;
990
991    // Process the edit
992    $this->campaign_data['main']['lastactive'] = 0;
993    $this->adminProcessEdit($h,$cid);
994    return $cid;
995  }
996
997   /**
998   * Cleans everything for the given id, then redoes everything
999   *
1000   * @param integer $id           The id to edit
1001   */
1002  function adminProcessEdit($h,$id)
1003  {
1004    // If we need to execute a tool action we stop here
1005    if($this->adminProcessTools($h)) return;
1006
1007    // Delete all to recreate
1008    $h->db->query("DELETE FROM {$this->db['campaign_word']} WHERE campaign_id = $id");
1009    $h->db->query("DELETE FROM {$this->db['campaign_category']} WHERE campaign_id = $id");
1010
1011    // Process categories
1012    # New
1013    if(isset($this->campaign_data['categories']['new']))
1014    {
1015      foreach($this->campaign_data['categories']['new'] as $category)
1016        $this->campaign_data['categories'][] = wp_insert_category(array('cat_name' => $category));
1017
1018      unset($this->campaign_data['categories']['new']);
1019
1020     // print "new campaign";
1021    }
1022
1023    # All
1024    foreach($this->campaign_data['categories'] as $category)
1025    {
1026      // Insert
1027      $wpdb->query(WPOTools::insertQuery($this->db['campaign_category'],
1028        array('category_id' => $category,
1029              'campaign_id' => $id)
1030      ));
1031    }
1032
1033    // Process feeds
1034    # New
1035    if(isset($this->campaign_data['feeds']['new']))
1036    {
1037      foreach($this->campaign_data['feeds']['new'] as $feed)
1038        $this->addCampaignFeed($h, $id, $feed);
1039    }
1040
1041    # Delete
1042    if(isset($this->campaign_data['feeds']['delete']))
1043    {
1044      foreach($this->campaign_data['feeds']['delete'] as $feed)
1045        $wpdb->query("DELETE FROM {$this->db['campaign_feed']} WHERE id = $feed ");
1046    }
1047
1048    // Process words
1049    foreach($this->campaign_data['rewrites'] as $rewrite)
1050    {
1051      $wpdb->query(WPOTools::insertQuery($this->db['campaign_word'],
1052        array('word' => $rewrite['origin']['search'],
1053              'regex' => $rewrite['origin']['regex'],
1054              'rewrite' => isset($rewrite['rewrite']),
1055              'rewrite_to' => isset($rewrite['rewrite']) ? $rewrite['rewrite'] : '',
1056              'relink' => isset($rewrite['relink']) ? $rewrite['relink'] : null,
1057              'campaign_id' => $id)
1058      ));
1059    }
1060
1061    // Main
1062    $main = $this->campaign_data['main'];
1063
1064    // Fetch author id
1065    $main['authorid'] = $h->getUserIdFromName($this->campaign_data['main']['author']);
1066    unset($main['author']);
1067
1068    // Query
1069    $query = WPOTools::updateQuery($this->db['campaign'], $main, 'id = ' . intval($id));
1070    $h->db->query($query);
1071
1072   //get data ready to pass to cron plugin
1073   $timestamp = time();
1074   $recurrence = "hourly"; //$this->campaign_data['campaign_frequency_d'];
1075   $hook = "autoreader_runcron";
1076   $args = array('id'=> $id);
1077   $cron_data = array('timestamp'=>$timestamp, 'recurrence'=>$recurrence, 'hook'=>$hook, 'args'=>$args);
1078   $h->pluginHook('cron_update_job', 'cron', $cron_data); 
1079
1080   // campaign_frequency_d
1081   // campaign_frequency_h
1082   // campaign_frequency_m
1083  }
1084
1085  /**
1086   * Processes edit campaign tools actions
1087   *
1088   *
1089   */
1090  function adminProcessTools($h)
1091  {
1092    $id = $h->cage->post->testAlnum('id');
1093
1094    if($h->cage->post->testAlnumLines('tool_removeall'))
1095    {
1096      $posts = $this->getCampaignPosts($id);
1097
1098      foreach($posts as $post)
1099      {
1100        $h->db->query("DELETE FROM {$wpdb->posts} WHERE ID = {$post->post_id} ");
1101      }
1102
1103      // Delete log
1104      $h->db->query("DELETE FROM {$this->db['campaign_post']} WHERE campaign_id = {$id} ");
1105
1106      // Update feed and campaign posts count
1107       $h->db->query(WPOTools::updateQuery($this->db['campaign'], array('count' => 0), "id = {$id}"));
1108       $h->db->query(WPOTools::updateQuery($this->db['campaign_feed'], array('hash' => 0, 'count' => 0), "campaign_id = {$id}"));
1109
1110      $this->tool_success = __('All posts removed', 'wpomatic');
1111      return true;
1112    }
1113
1114    if(isset($_REQUEST['tool_changetype']))
1115    {
1116      $this->adminUpdateCampaignPosts($h, $id, array(
1117        'post_status' => $h->db->escape($_REQUEST['campaign_tool_changetype'])
1118      ));
1119
1120      $this->tool_success = __('Posts status updated', 'wpomatic');
1121      return true;
1122    }
1123
1124    if(isset($_REQUEST['tool_changeauthor']))
1125    {
1126//      $author = get_userdatabylogin($_REQUEST['campaign_tool_changeauthor']);
1127        //if ($h->currentUser->
1128
1129      if($author)
1130      {
1131        $authorid = $author->ID;
1132        $this->adminUpdateCampaignPosts($h, $id, array('post_author' => $authorid));
1133      } else {
1134        $this->errno = 1;
1135        $this->errors = array('tools' => array(print('Author' . attribute_escape($_REQUEST['campaign_tool_changeauthor'])).  ' not found' ));
1136      }
1137
1138      $this->tool_success = 'Posts status updated';
1139      return true;
1140    }
1141
1142    return false;
1143  }
1144
1145  function adminUpdateCampaignPosts($h,$id, $properties)
1146  {
1147    $posts = $this->getCampaignPosts($h, $id);
1148
1149    foreach($posts as $post)
1150       $h->db->query(WPOTools::updateQuery($h->db->posts, $properties, "ID = {$post->id}"));
1151  }
1152
1153  /**
1154   * Parses an item content
1155   *
1156   * @param   $campaign       object    Campaign database object
1157   * @param   $feed           object    Feed database object
1158   * @param   $item           object    SimplePie_Item object
1159   */
1160  function parseItemContent($h, &$campaign, &$feed, &$item)
1161  {
1162    $content = $item->get_content();
1163
1164    // Caching
1165    if ($campaign->cacheimages)   // set override here for all campaigns  get_option('wpo_cacheimages')
1166    {
1167      $images = WPOTools::parseImages($content);
1168      $urls = $images[2];
1169
1170      if(sizeof($urls))
1171      {
1172        $this->log($h, 'Caching images');
1173
1174        foreach($urls as $url)
1175        {
1176          $newurl = $this->cacheRemoteImage($url);
1177          if($newurl)
1178            $content = str_replace($url, $newurl, $content);
1179        }
1180      }
1181    }
1182
1183    // cut images here
1184    preg_replace("/<img[^>]+\>/i", "", $content);
1185
1186   
1187
1188    // Template parse
1189    $vars = array(
1190      '{content}',
1191      '{title}',
1192      '{permalink}',
1193      '{feedurl}',
1194      '{feedtitle}',
1195      '{feedlogo}',
1196      '{campaigntitle}',
1197      '{campaignid}',
1198      '{campaignslug}'
1199    );
1200
1201    $replace = array(
1202      $content,
1203      $item->get_title(),
1204      $item->get_link(),
1205      $feed->url,
1206      $feed->title,
1207      $feed->logo,
1208      $campaign->title,
1209      $campaign->id,
1210      $campaign->slug
1211    );
1212
1213    $content = str_ireplace($vars, $replace, ($campaign->template) ? $campaign->template : '{content}');
1214
1215    // Rewrite
1216    $rewrites = $this->getCampaignData($h, $campaign->id, 'rewrites');
1217    foreach($rewrites as $rewrite)
1218    {
1219      $origin = $rewrite['origin']['search'];
1220
1221      if(isset($rewrite['rewrite']))
1222      {
1223        $reword = isset($rewrite['relink'])
1224                    ? '<a href="'. $rewrite['relink'] .'">' . $rewrite['rewrite'] . '</a>'
1225                    : $rewrite['rewrite'];
1226
1227        if($rewrite['origin']['regex'])
1228        {
1229          $content = preg_replace($origin, $reword, $content);
1230        } else
1231          $content = str_ireplace($origin, $reword, $content);
1232      } else if(isset($rewrite['relink']))
1233        $content = str_ireplace($origin, '<a href="'. $rewrite['relink'] .'">' . $origin . '</a>', $content);
1234    }
1235
1236    return $content;
1237  }
1238
1239  /**
1240   * Cache remote image
1241   *
1242   * @return string New url
1243   */
1244  function cacheRemoteImage($h, $url)
1245  {
1246    $contents = @file_get_contents($url);
1247
1248    $url=explode("?", $url );
1249        $url=$url[0];
1250    $filename = substr(md5(time()), 0, 5) . '_' . basename($url);
1251
1252    $cachepath = $this->cachepath;
1253
1254    if(is_writable($cachepath) && $contents)
1255    {
1256      file_put_contents($cachepath . '/' . $filename, $contents);
1257      return $this->pluginpath . '/' . get_option('wpo_cachepath') . '/' . $filename;
1258    }
1259
1260    return false;
1261  }
1262
1263/**
1264   * Parses a feed with SimplePie
1265   *
1266   * @param   boolean     $stupidly_fast    Set fast mode. Best for checks
1267   * @param   integer     $max              Limit of items to fetch
1268   * @return  SimplePie_Item    Feed object
1269   **/
1270  function fetchFeed($url, $stupidly_fast = false, $max = 0)
1271  {
1272    # SimplePie     
1273    if(! class_exists('SimplePie'))
1274      require_once( LIBS . 'extensions/SimplePie/simplepie.inc' );
1275 
1276    $feed = new SimplePie();
1277    $feed->enable_order_by_date(false); // thanks Julian Popov
1278    $feed->set_feed_url($url);
1279    $feed->set_item_limit($max);
1280    $feed->set_stupidly_fast($stupidly_fast);
1281    $feed->enable_cache(false);
1282    $feed->init();
1283    $feed->handle_content_type();
1284
1285    return $feed;
1286  }
1287
1288  /**
1289   * Returns all blog usernames (in form [user_login => display_name (user_login)] )
1290   *
1291   * @return array $usernames
1292   **/
1293  function getBlogUsernames()
1294  {
1295    $return = array();
1296    $users = get_users_of_blog();
1297
1298    foreach($users as $user)
1299    {
1300      if($user->display_name == $user->user_login)
1301        $return[$user->user_login] = "{$user->display_name}";
1302      else
1303        $return[$user->user_login] = "{$user->display_name} ({$user->user_login})";
1304    }
1305
1306    return $return;
1307  }
1308
1309
1310  /**
1311   * Returns all data for a campaign
1312   *
1313   *
1314   */
1315  function getCampaignData($h, $id, $section = null)
1316  {   
1317    $campaign = (array) $this->getCampaignById($h, $id);
1318//print_r ($campaign);
1319    if($campaign)
1320    {
1321      $campaign_data = $this->campaign_structure;
1322
1323      // Main
1324      if(!$section || $section == 'main')
1325      {
1326        $campaign_data['main'] = array_merge($campaign_data['main'], $campaign);
1327//        $userdata = get_userdata($campaign_data['main']['authorid']);
1328//        $campaign_data['main']['author'] = $userdata->user_login;
1329      }
1330
1331      // Categories
1332      if(!$section || $section == 'categories')
1333      {
1334        $categories = $h->db->get_results("SELECT * FROM {$this->db['campaign_category']} WHERE campaign_id = $id");
1335        if ($categories) {
1336        foreach($categories as $category)
1337          $campaign_data['categories'][] = $category->category_id;
1338        } else {
1339            }
1340      }
1341
1342      // Feeds
1343      if(!$section || $section == 'feeds')
1344      {
1345        $campaign_data['feeds']['edit'] = array();
1346
1347        $feeds = $this->getCampaignFeeds($h, $id);
1348        foreach($feeds as $feed)
1349          $campaign_data['feeds']['edit'][$feed->id] = $feed->url;
1350      }
1351
1352      // Rewrites
1353      if(!$section || $section == 'rewrites')
1354      {
1355        $rewrites = $h->db->get_results("SELECT * FROM {$this->db['campaign_word']} WHERE campaign_id = $id");
1356        if ($rewrites) {
1357            foreach($rewrites as $rewrite)
1358            {
1359              $word = array('origin' => array('search' => $rewrite->word, 'regex' => $rewrite->regex), 'rewrite' => $rewrite->rewrite_to, 'relink' => $rewrite->relink);
1360
1361              if(! $rewrite->rewrite) unset($word['rewrite']);
1362              if(empty($rewrite->relink)) unset($word['relink']);
1363
1364              $campaign_data['rewrites'][] = $word;
1365            }
1366        } 
1367      }
1368
1369      if($section)
1370        return $campaign_data[$section];
1371
1372      return $campaign_data;
1373    }
1374
1375    return false;
1376  }
1377
1378  /**
1379   * Retrieves logs from database
1380   *
1381   *
1382   */
1383  function getLogs($h, $args = '')
1384  {   
1385    extract(WPOTools::getQueryArgs($args, array('orderby' => 'created_on',
1386                                                'ordertype' => 'DESC',
1387                                                'limit' => null,
1388                                                'page' => null,
1389                                                'perpage' => null)));
1390    if(!is_null($page))
1391    {
1392      if($page == 0) $page = 1;
1393      $page--;
1394
1395      $start = $page * $perpage;
1396      $end = $start + $perpage;
1397      $limit = "LIMIT {$start}, {$end}";
1398    }
1399        return $h->db->get_results("SELECT * FROM {$this->db['log']} ORDER BY $orderby $ordertype $limit");
1400  }
1401
1402  /**
1403   * Retrieves a campaign by its id
1404   *
1405   *
1406   */
1407  function getCampaignById($h, $id)
1408  {
1409    $id = intval($id);
1410    return $h->db->get_row("SELECT * FROM {$this->db['campaign']} WHERE id = $id");
1411  }
1412
1413  /**
1414   * Retrieves a feed by its id
1415   *
1416   *
1417   */
1418  function getFeedById($h, $id)
1419  {
1420    $id = intval($id);
1421    return $h->db->get_row("SELECT * FROM {$this->db['campaign_feed']} WHERE id = $id");
1422  }
1423
1424
1425/**
1426   * Returns how many seconds left till reprocessing
1427   *
1428   * @return seconds
1429   **/
1430  function getCampaignRemaining(&$campaign, $gmt = 0)
1431  {
1432    return mysql2date('U', $campaign->lastactive) + $campaign->frequency - time() + (GMT_OFFSET * 3600);
1433  }
1434
1435
1436
1437 
1438
1439
1440
1441
1442
1443   /**
1444   * Tests a feed
1445   *
1446   *
1447   */
1448  function adminTestfeed($url)
1449  {
1450     
1451    //if(!isset($_REQUEST['url'])) return false;
1452
1453   // $url = $_REQUEST['url'];
1454    $feed = $this->fetchFeed($url, true);
1455    $works = ! $feed->error(); // if no error returned
1456
1457     if($works):
1458        $json_array = array('result'=>'ok', 'url'=>$feed->feed_url );
1459     else:
1460        $json_array = array('result'=>'fail', 'error'=>$works );
1461     endif ;
1462
1463     echo json_encode($json_array);
1464
1465  }
1466
1467
1468  /**
1469   * Forcedfully processes a campaign
1470   *
1471   *
1472   */
1473  function adminForcefetch($h)
1474  {
1475    $cid = $h->cage->post->testInt('id');
1476
1477    $this->forcefetched = $this->processCampaign($h,$cid);
1478   
1479    return $this->forcefetched;
1480  }
1481
1482
1483
1484
1485
1486
1487 /**
1488    * Saves a log message to database
1489    *
1490    *
1491    * @param string  $message  Message to save
1492    */
1493      function log($h, $message)
1494      {       
1495        $autoreader_settings = $h->getSerializedSettings('autoreader');
1496     
1497        if ($autoreader_settings['wpo_log_stdout'])
1498             echo $message;
1499
1500        if ($autoreader_settings['wpo_log'])
1501        {
1502          $message = $h->db->escape($message);
1503          $time = gmdate('Y-m-d H:i:s');// time(); // current_time('mysql', true);
1504          $h->db->query("INSERT INTO {$this->db['log']} (message, created_on) VALUES ('{$message}', '{$time}') ");
1505        }
1506      }
1507
1508
1509
1510}
1511
1512?>
Note: See TracBrowser for help on using the repository browser.