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

Revision 1334, 41.9 KB checked in by shibuya246, 3 years ago (diff)

[branch 1.2] latest changes for current version

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