/[drupal]/contributions/modules/affiliates/affiliates.module
ViewVC logotype

Diff of /contributions/modules/affiliates/affiliates.module

Parent Directory Parent Directory | Revision Log Revision Log | View Revision Graph Revision Graph | View Patch Patch

revision 1.1 by kbahey, Mon Nov 27 02:22:17 2006 UTC revision 1.2 by kbahey, Sat Jan 10 17:28:47 2009 UTC
# Line 0  Line 1 
1    <?php
2    // $Id: affiliates.module,v 1.1.4.5.2.7 2009/01/05 01:45:17 kbahey Exp $
3    
4    // Portions Copyright 2006 http://2bits.com
5    define ('AFFILIATE_BUTTONS_DIRECTORY_RELATIVE_FILES', '/affiliates');
6    
7    define('AFFILIATE_HOMEPAGE_PROFILE',              'affiliate_homepage_profile');
8    define('AFFILIATE_BLOCK_TEXT',                    'affiliate_block_text');
9    define('AFFILIATE_STATS_TEXT',                    'affiliate_stats_text');
10    define('AFFILIATE_TOP_USERS_PAGE',                'affiliate_top_users_page');
11    define('AFFILIATE_TOP_USERS_BLOCK',               'affiliate_top_users_block');
12    define('AFFILIATE_TOP_USERS_COUNT_PAGE',          'affiliate_top_users_count_page');
13    define('AFFILIATE_TOP_USERS_COUNT_BLOCK',         'affiliate_top_users_count_block');
14    define('AFFILIATE_TOP_USERS_PERIOD_INTERVAL',     'affiliate_top_users_period_interval');
15    define('AFFILIATE_TOP_CLIMBERS_PAGE',             'affiliate_top_climbers_page');
16    define('AFFILIATE_TOP_CLIMBERS_BLOCK',            'affiliate_top_climbers_block');
17    define('AFFILIATE_TOP_CLIMBERS_COUNT_PAGE',       'affiliate_top_climbers_count_page');
18    define('AFFILIATE_TOP_CLIMBERS_COUNT_BLOCK',      'affiliate_top_climbers_count_block');
19    define('AFFILIATE_TOP_CLIMBERS_PERIOD_INTERVAL',  'affiliate_top_climbers_period_interval');
20    define('AFFILIATE_CLICK_IGNORE_INTERVAL',         'affiliate_click_ignore_interval');
21    define('AFFILIATE_CRON_INTERVAL',                 'affiliate_cron_interval');
22    define('AFFILIATE_INTRODUCTION',                  'affiliate_introduction');
23    define('AFFILIATE_USERPOINTS_TID',                'affiliate_userpoints_tid');
24    
25    function affiliates_help($section) {
26      switch ($section) {
27        case 'admin/help#affiliates':
28        case 'admin/modules#description':
29          return t('A module that allows affiliate click-throughs to be tracked.');
30      }
31    }
32    
33    function affiliates_perm() {
34    //The view own stats permission isn't currently used. Leaving it here for future reference though.
35    //  return array('administer affiliates', 'view own affiliate stats', 'affiliate click');
36      return array('administer affiliates', 'affiliate click');
37    }
38    
39    function affiliates_menu() {
40        $items['admin/settings/affiliates'] = array(
41          'title' => t('Affiliates'),
42          'description' => t('affiliates settings.'),
43          'page callback' => 'drupal_get_form',
44          'page arguments' => array('affiliates_admin_settings'),
45          'access arguments' => array('administer site configuration'),
46        );
47    
48        $items['affiliates/admin'] = array(
49          'title' => 'Affiliates',
50          'access arguments' => array('administer affiliates'),
51          'page callback' => 'affiliates_ad_button_list',
52        );
53    
54        $items['affiliates/admin/list/buttons'] = array(
55          'title' => 'List Buttons',
56          'access arguments' => array('administer affiliates'),
57          'page callback' => 'affiliates_ad_button_list',
58          'type' => MENU_LOCAL_TASK,
59          'weight' => 1,
60        );
61    
62         $items['affiliates/admin/list/categories'] = array(
63          'title' => 'List Categories',
64          'access arguments' => array('administer affiliates'),
65          'page callback' => 'affiliates_ad_category_list',
66          'type' => MENU_LOCAL_TASK,
67          'weight' => 1,
68        );
69    
70        $items['affiliates/admin/add/button'] = array(
71          'title' => t('Add Button'),
72          'access arguments' => array('administer affiliates'),
73          'page callback' => 'affiliates_affiliate',
74          'type' => MENU_LOCAL_TASK,
75          'weight' => 5,
76        );
77    
78        $items['affiliates/admin/add/category'] = array(
79          'title' => t('Add Category'),
80          'access arguments' => array('administer affiliates'),
81          'page callback' => 'affiliates_affiliate',
82          'type' => MENU_LOCAL_TASK,
83          'weight' => 5,
84        );
85    
86        $items['affiliates/admin/edit/button'] = array(
87          'title' => 'Edit button',
88          'access arguments' => array('administer affiliates'),
89          'page callback' => 'affiliates_affiliate',
90          'type' => MENU_HIDE,
91        );
92    
93         $items['affiliates/admin/edit/category'] = array(
94          'title' => 'Edit Category',
95          'access arguments' => array('administer affiliates'),
96          'page callback' => 'affiliates_affiliate',
97          'type' => MENU_HIDE,
98        );
99    
100        $items['affiliates/admin/delete/button'] = array(
101          'title' => t('Delete affiliate button'),
102          'access arguments' => array('administer affiliates'),
103          'page callback' => 'affiliates_affiliate',
104          'type' => MENU_HIDE,
105        );
106    
107        $items['affiliates/admin/delete/category'] = array(
108          'title' => t('Delete affiliate category'),
109          'access arguments' => array('administer affiliates'),
110          'page callback' => 'affiliates_affiliate',
111          'type' => MENU_HIDE,
112        );
113    
114        $items['aff'] = array(
115          'page callback' => 'affiliates_click',
116          'access arguments' => array('access content'),
117          'type' => MENU_HIDE,
118        );
119    
120        $items['affiliates/top_users'] = array(
121          'title' => t('Top Affiliates'),
122          'page callback' => 'affiliates_top_users',
123          'access arguments' => array('access content'),
124          'type' => MENU_HIDE,
125        );
126    
127         $items['affiliates/top_climbers'] = array(
128          'title' => t('Top Affiliate Climbers'),
129          'page callback' => 'affiliates_top_climbers',
130          'access arguments' => array('access content'),
131          'type' => MENU_HIDE,
132        );
133    
134        $items['affiliates'] = array(
135          'title' => t('Affiliates Home'),
136          'page callback' => 'affiliates_list',
137          'access arguments' => array('access content'),
138        );
139      return $items;
140    }
141    
142    function affiliates_admin_settings() {
143     $form['affiliates_settings'] = array(
144        '#type' => 'fieldset',
145        '#title' => t('Affiliates settings'),
146        '#collapsible' => FALSE,
147        '#collapsed' => FALSE,
148      );
149    
150      $form['affiliates_settings']['configuration'] = array(
151        '#type' => 'fieldset',
152        '#title' => t('Configuration'),
153        '#collapsible' => TRUE,
154        '#collapsed' => FALSE,
155      );
156    
157      $form['affiliates_settings']['configuration']['top_users'] = array(
158        '#type' => 'fieldset',
159        '#title' => t('Top Users'),
160        '#collapsible' => TRUE,
161        '#collapsed' => TRUE,
162      );
163    
164      $form['affiliates_settings']['configuration']['top_users'][AFFILIATE_TOP_USERS_COUNT_PAGE] = array(
165        '#type'          => 'select',
166        '#title'         => t('Top Users Count For Page'),
167        '#default_value' => variable_get(AFFILIATE_TOP_USERS_COUNT_PAGE, 5),
168        '#options'       => array(5 => 5, 10 => 10, 25 => 25, 50 => 50, 100 => 100),
169        '#description'   => t('Number of users to show in top users page.'),
170      );
171    
172      $form['affiliates_settings']['configuration']['top_users'][AFFILIATE_TOP_USERS_COUNT_BLOCK] = array(
173        '#type'          => 'select',
174        '#title'         => t('Top Users Count For Block'),
175        '#default_value' => variable_get(AFFILIATE_TOP_USERS_COUNT_BLOCK, 5),
176        '#options'       => array(5 => 5, 10 => 10, 25 => 25, 50 => 50, 100 => 100),
177        '#description'   => t('Number of users to show in top users block.'),
178      );
179    
180      $form['affiliates_settings']['configuration']['top_users'][AFFILIATE_TOP_USERS_PERIOD_INTERVAL] = array(
181        '#type'          => 'select',
182        '#title'         => t('Period for top users block and page'),
183        '#default_value' => variable_get(AFFILIATE_TOP_USERS_PERIOD_INTERVAL, 259200),
184        '#options'       => drupal_map_assoc(
185          array(86400, 172800, 259200, 259200, 432000, 604800, 1209600, 2592000), 'format_interval'),
186        '#description'   => t('How long will the "period" be as shown in the top users page.'),
187      );
188    
189       $form['affiliates_settings']['configuration']['top_climbers'] = array(
190        '#type' => 'fieldset',
191        '#title' => t('Top Climbers'),
192        '#collapsible' => TRUE,
193        '#collapsed' => TRUE,
194      );
195    
196      $form['affiliates_settings']['configuration']['top_climbers'][AFFILIATE_TOP_CLIMBERS_COUNT_PAGE] = array(
197        '#type'          => 'select',
198        '#title'         => t('Top Climbers Count For Page'),
199        '#default_value' => variable_get(AFFILIATE_TOP_CLIMBERS_COUNT_PAGE, 5),
200        '#options'       => array(5 => 5, 10 => 10, 25 => 25, 50 => 50, 100 => 100),
201        '#description'   => t('Number of users to show in top climbers page.'),
202      );
203    
204      $form['affiliates_settings']['configuration']['top_climbers'][AFFILIATE_TOP_CLIMBERS_COUNT_BLOCK] = array(
205        '#type'          => 'select',
206        '#title'         => t('Top Climbers Count For Block'),
207        '#default_value' => variable_get(AFFILIATE_TOP_CLIMBERS_COUNT_BLOCK, 5),
208        '#options'       => array(5 => 5, 10 => 10, 25 => 25, 50 => 50, 100 => 100),
209        '#description'   => t('Number of users to show in top climbers block.'),
210      );
211    
212      $form['affiliates_settings']['configuration']['top_climbers'][AFFILIATE_TOP_CLIMBERS_PERIOD_INTERVAL] = array(
213        '#type'          => 'select',
214        '#title'         => t('Period for top climbers block and page'),
215        '#default_value' => variable_get(AFFILIATE_TOP_CLIMBERS_PERIOD_INTERVAL, 259200),
216        '#options'       => drupal_map_assoc(
217          array(86400, 172800, 259200, 259200, 432000, 604800, 1209600, 2592000), 'format_interval'),
218        '#description'   => t('How long will the "period" be as shown in the top climbers page.'),
219      );
220    
221      $form['affiliates_settings']['configuration'][AFFILIATE_CLICK_IGNORE_INTERVAL] = array(
222        '#type'          => 'select',
223        '#title'         => t('IP Click Ignore'),
224        '#default_value' => variable_get(AFFILIATE_CLICK_IGNORE_INTERVAL, 86400),
225        '#options'       => drupal_map_assoc(array(3600, 10800, 21600, 32400, 43200, 86400, 172800, 259200, 604800, 1209600, 2419200), 'format_interval'),
226        '#description'   => t('Ignore clicks from the same IP address for this time interval.'),
227      );
228    
229      $form['affiliates_settings']['configuration'][AFFILIATE_CRON_INTERVAL] = array(
230        '#type'          => 'select',
231        '#title'         => t('Top User Refresh Interval'),
232        '#default_value' => variable_get(AFFILIATE_CRON_INTERVAL, 86400),
233        '#options'       => drupal_map_assoc(
234          array(300, 600, 1800, 3600, 10800, 21600, 32400, 43200, 86400, 172800, 259200, 604800), 'format_interval'),
235        '#description'   => t('How often to refresh the top users data. Requires cron to be running at a more frequent rate than this value to really take effect.'),
236      );
237    
238      $form['affiliates_settings']['content'] = array(
239        '#type' => 'fieldset',
240        '#title' => t('Content'),
241        '#collapsible' => TRUE,
242        '#collapsed' => TRUE,
243      );
244    
245      $form['affiliates_settings']['content'][AFFILIATE_STATS_TEXT] = array(
246        '#type'          => 'textarea',
247        '#title'         => t('User Text'),
248        '#default_value' => variable_get(AFFILIATE_STATS_TEXT, 'Copy and paste the source below to link to us and get affiliate credit.'),
249        '#cols'          => 70,
250        '#rows'          => 4,
251        '#description'   => t('Text to instruct users to copy/paste to earn affiliate credits.'),
252      );
253    
254      $form['affiliates_settings']['content'][AFFILIATE_INTRODUCTION] = array(
255        '#type' => 'textarea',
256        '#title' => t('Affiliates introduction'),
257        '#default_value' => variable_get(AFFILIATE_INTRODUCTION,""),
258        '#size' => 70,
259        '#rows' => 4,
260        '#description' => t('The introduction text on the affiliate page.'),
261      );
262    
263       $form['affiliates_settings']['revenue'] = array(
264        '#type' => 'fieldset',
265        '#title' => t('Revenue'),
266        '#collapsible' => TRUE,
267        '#collapsed' => TRUE,
268      );
269    
270       $form['affiliates_settings']['revenue'][AFFILIATE_HOMEPAGE_PROFILE] = array(
271        '#type'          => 'select',
272        '#title'         => t('Home Page Profile Field'),
273        '#default_value' => variable_get(AFFILIATE_HOMEPAGE_PROFILE, 0),
274        '#options'       => _get_profile_fields(),
275        '#description'   => t('Select the profile field that users put their home page in. This will be displayed in the top users block and page.'),
276      );
277    
278    
279      return system_settings_form($form['affiliates_settings']);
280    }
281    
282    function affiliates_cron() {
283      $last_run = variable_get('cron_last', time());
284      $interval = variable_get(AFFILIATE_CRON_INTERVAL, 86400);
285    
286      if (time() >= $interval) {
287        // Refresh the top users data
288        _create_summary_data(variable_get(AFFILIATE_TOP_USERS_COUNT_PAGE, 5));
289    
290        // Generate the page
291        _get_top_users_page();
292        _get_top_climbers_page();
293    
294        // Generate the blocks
295        _get_top_users_block('total');
296        _get_top_users_block('period');
297        _get_top_climbers_block();
298    
299      }
300    }
301    
302    function affiliates_affiliate() {
303      $affiliate = array();
304      $op = arg(2);
305      $level = arg(3);
306      $id = (int)arg(4);
307    
308      switch($op) {
309        case 'add':
310           if ($level == 'category') {
311            $output = drupal_get_form('affiliate_form_category_add_edit');
312           }
313           else {
314           $output = drupal_get_form('affiliate_form_button_add_edit');
315           }
316          break;
317    
318        case 'edit':
319          if ($level == 'category') {
320            $affiliate_category = _get_affiliate_category($id);
321            $output = drupal_get_form('affiliate_form_category_add_edit', $affiliate_category);
322          }
323          else {
324            $affiliate_button = _get_affiliate_button($id);
325            $output = drupal_get_form('affiliate_form_button_add_edit', $affiliate_button);
326          }
327          break;
328    
329        case 'delete':
330          if ($level == 'category') {
331            $output = drupal_get_form('affiliate_form_category_delete', $id);
332          }
333          else {
334             $output = drupal_get_form('affiliate_form_button_delete', $id);
335          }
336          break;
337      }
338    
339      return $output;
340    }
341    
342    function affiliate_form_button_delete($id) {
343      $form['affiliate']['message'] = array(
344        '#type'  => 'markup',
345        '#value' => t('Are you sure you?'),
346      );
347      $form['affiliate']['delete'] = array(
348        '#type'  => 'submit',
349        '#value' => t('Delete'),
350      );
351      return $form;
352    }
353    
354    function affiliate_form_button_add_edit(&$form_state, $affiliate = array()) {
355    
356      $form['affiliate'] = array(
357        '#type'  => 'fieldset',
358        '#title' => t('Add a button'),
359      );
360    
361      $form['affiliate']['label'] = array(
362        '#type'          => 'textfield',
363        '#title'         => t('Label'),
364        '#default_value' => $affiliate->label,
365        '#size'          => 30,
366        '#maxlength'     => 30,
367        '#required' => TRUE,
368      );
369    
370      $form['affiliate']['points'] = array(
371        '#type'          => 'textfield',
372        '#title'         => t('Points'),
373        '#default_value' => $affiliate->points,
374        '#size'          => 3,
375        '#maxlength'     => 3,
376        '#required' => TRUE,
377      );
378    
379      $form['affiliate']['type'] = array(
380        '#type'          => 'select',
381        '#title'         => t('Type'),
382        '#default_value' => $affiliate->type,
383        '#options'       => array(
384          'image' => 'Image',
385          'text'  => 'Text',
386          ),
387      );
388    
389      $form['affiliate']['cat_id'] = array(
390        '#type'          => 'select',
391        '#title'         => t('Category'),
392        '#default_value' => $affiliate->cat_id,
393        '#options'       => _get_categories(),
394      );
395    
396       $form['affiliate']['image'] = array(
397            '#type' => 'file',
398            '#title' => t('Upload a button'),
399            '#size' => 40,
400            '#description' => t('Please upload a button.<br /><br /><b>OR</b> specify the button URL:')
401      );
402    
403      $form['affiliate']['anchor'] = array(
404        '#type'          => 'textfield',
405        '#title'         => t('Hosted button URL'),
406        '#default_value' => $affiliate->anchor,
407        '#size'          => 40,
408        '#maxlength'     => 120,
409        '#description' => t('If your button is hosted elsewhere, enter the URL here.')
410      );
411    
412      $form['affiliate']['redirect'] = array(
413        '#type'          => 'textfield',
414        '#title'         => t('Redirect to URL'),
415        '#default_value' => $affiliate->redirect,
416        '#size'          => 40,
417        '#maxlength'     => 80,
418        '#description' => t('If no redirect is specified, the home page will be used.')
419      );
420    
421      $form['affiliate']['order_by'] = array(
422        '#type'          => 'textfield',
423        '#title'         => t('Order'),
424        '#default_value' => $affiliate->order_by,
425        '#size'          => 10,
426        '#maxlength'     => 5,
427        '#required' => TRUE,
428      );
429    
430      $form['affiliate']['status'] = array(
431        '#type'          => 'select',
432        '#title'         => t('Status'),
433        '#default_value' => $affiliate->status,
434        '#options'       =>  _get_status_desc(),
435      );
436    
437      $form['affiliate']['submit'] = array(
438        '#type'  => 'submit',
439        '#value' => t('Save'),
440      );
441      $form['#attributes'] = array('enctype' => "multipart/form-data");
442      return $form;
443    
444    }
445    
446    function affiliate_form_button_add_edit_validate($form, &$form_state) {
447      $form_values = $form_state['values'];
448      $op = arg(2);
449      if ($op == 'delete') {
450        // no need to validate anything
451        return;
452      }
453    
454      if (!$form_values['label']) {
455        form_set_error('', t('You must enter a label'));
456      }
457      if (!is_numeric($form_values['points'])) {
458        form_set_error('', t('You must enter a numeric value for points'));
459      }
460      if (!$form_values['type']) {
461        form_set_error('', t('You must select a type'));
462      }
463      if (!$form_values['cat_id']) {
464        form_set_error('', t('You must select a category'));
465      }
466       if (!$form_values['anchor'] && empty($_FILES['files']['name']['image'])) {
467        form_set_error('', t('You must either upload an button or enter the URL of the hosted button '));
468      }
469      if (!is_numeric($form_values['order_by'])) {
470        form_set_error('', t('You must enter a numeric order value'));
471      }
472    //  if (!$form_values['redirect']) {
473    //    form_set_error('', t('You must enter a redirect url'));
474    //  }
475      if (!$form_values['status']) {
476        form_set_error('', t('You must select a valid status'));
477      }
478    }
479    
480    function affiliate_form_button_add_edit_submit($form, &$form_state) {
481      global $base_url;
482      $form_values = $form_state['values'];
483      $op = arg(2);
484      $id = arg(4);
485      $FILE_DIRECTORY_PATH  = variable_get('file_directory_path', 'files');
486       if (!empty($_FILES['files']['name']['image']) && substr_count($_FILES['files']['type']['image'], "image")) {
487         $directory = $FILE_DIRECTORY_PATH . AFFILIATE_BUTTONS_DIRECTORY_RELATIVE_FILES ;
488          if (file_check_directory($directory, $mode = 1, $form_item = NULL)) {
489             chmod($directory, 0777) ;
490          }
491          file_copy($_FILES['files']['tmp_name']['image'], $directory.'/'.$_FILES['files']['name']['image'], $replace = FILE_EXISTS_ERROR) ;
492       }
493       $button_url = $_FILES['files']['name']['image'] ? $base_url .'/'. $directory .'/'. $_FILES['files']['name']['image'] : $form_values['anchor'];
494    
495      switch($op) {
496        case 'add':
497          db_query("INSERT INTO {affiliates_ads}
498            (label, points, anchor, type, cat_id, order_by, redirect, status)
499            VALUES
500            ('%s', %d, '%s', '%s', %d, %d, '%s', '%s')",
501            $form_values['label'],
502            $form_values['points'],
503            $button_url,
504            $form_values['type'],
505            $form_values['cat_id'],
506            $form_values['order_by'],
507            $form_values['redirect'],
508            'a');
509        drupal_set_message('Affiliate button has been added.');
510        break;
511    
512        case 'edit':
513          $ad_id = (int)arg(4);
514          db_query("UPDATE {affiliates_ads} SET
515            label    = '%s',
516            points   = %d,
517            anchor   = '%s',
518            type     = '%s',
519            cat_id   = %d,
520            order_by = %d,
521            redirect = '%s',
522            status   = '%s'
523            WHERE ad_id = %d",
524            $form_values['label'],
525            $form_values['points'],
526            $button_url,
527            $form_values['type'],
528            $form_values['cat_id'],
529            $form_values['order_by'],
530            $form_values['redirect'],
531            $form_values['status'],
532            $ad_id);
533          drupal_set_message('Affiliate button has been saved.');
534          break;
535      }
536      drupal_goto('affiliates/admin');
537    }
538    
539    function affiliate_form_button_delete_submit($form, &$form_state) {
540      $form_values = $form_state['values'];
541      $op = arg(2);
542      $id = arg(4);
543    
544      db_query("DELETE FROM {affiliates_ads} WHERE ad_id = %d", $id);
545      drupal_set_message('Affiliate button has been deleted.');
546      drupal_goto('affiliates/admin/list/buttons');
547    }
548    
549    function affiliate_form_category_add_edit(&$form_state, $affiliate_category = array()) {
550    
551      $form['affiliate'] = array(
552        '#type'  => 'fieldset',
553        '#title' => t('Add a category'),
554      );
555    
556      $form['affiliate']['cat_name'] = array(
557        '#type' => 'textfield',
558        '#title' => t('Category name'),
559        '#required' => TRUE,
560        '#default_value' => $affiliate_category->cat_name,
561        '#size'          => 30,
562        '#maxlength'     => 30,
563      );
564      $form['affiliate']['weight'] = array(
565        '#type' => 'textfield',
566        '#title' => t('Relative weight'),
567        '#default_value' => $affiliate_category->weight,
568        '#size'          => 3,
569        '#maxlength'     => 3,
570        '#required' => FALSE,
571        '#description' => t("Relative weight. Higher weights have higher positions on the affiliates page"),
572      );
573      $form['affiliate']['active'] = array(
574        '#type' => 'radios',
575        '#title' => t('Category active'),
576        '#default_value' => $affiliate_category->active,
577        '#options' => array('Y' =>'yes','N' =>'no'),
578      );
579    
580      $form['affiliate']['submit'] = array(
581        '#type' => 'submit',
582        '#value' => t('Create an affiliate category'),
583      );
584    
585      return $form;
586    }
587    
588    function affiliate_form_category_add_edit_submit($form, &$form_state) {
589      $form_values = $form_state['values'];
590      $op = arg(2);
591    
592      switch($op) {
593        case 'add':
594          db_query("INSERT INTO {affiliates_cats}
595            (cat_name, active, weight)
596            VALUES
597            ('%s', '%s', %d)",
598            $form_values['cat_name'],
599            $form_values['active'],
600            $form_values['weight']
601            );
602          drupal_set_message('Affiliate category has been added.');
603          break;
604    
605        case 'edit':
606          $cat_id = (int)arg(4);
607          db_query("UPDATE {affiliates_cats} SET
608            cat_name  = '%s',
609            active  = '%s',
610            weight  = %d
611            WHERE cat_id = %d",
612            $form_values['cat_name'],
613            $form_values['active'],
614            $form_values['weight'],
615            $cat_id);
616          drupal_set_message('Affiliate category has been saved.');
617          break;
618      }
619      drupal_goto('affiliates/admin/list/categories');
620    }
621    
622    function affiliate_form_category_delete($id) {
623      $form['affiliate']['message'] = array(
624        '#type'  => 'markup',
625        '#value' => t('Are you sure you want to delete this affiliate category and all of its buttons?'),
626      );
627      $form['affiliate']['delete'] = array(
628        '#type'  => 'submit',
629        '#value' => t('Delete'),
630      );
631      return $form;
632    }
633    
634    function affiliate_form_category_delete_submit($form, &$form_state) {
635      $form_values = $form_state['values'];
636      $op = arg(2);
637      $cat_id = arg(4);
638    
639      db_query("DELETE FROM {affiliates_cats}   WHERE cat_id = %d", $cat_id);
640      db_query("DELETE FROM {affiliates_ads} WHERE cat_id = %d", $cat_id);
641      drupal_set_message('Affiliate category has been deleted and all of its buttons.');
642      drupal_goto('affiliates/admin/list/categories');
643    }
644    
645    function affiliates_ad_button_list($cat_id = NULL) {
646      $header = array(
647        array('data' => t('ID'),       'field' => 'ad_id'),
648        array('data' => t('Label'),    'field' => 'label'),
649        array('data' => t('Points'),   'field' => 'points', 'sort' => 'desc'),
650        array('data' => t('Type'),     'field' => 'type'),
651        array('data' => t('Category'), 'field' => 'cat_name'),
652        array('data' => t('Status'),   'field' => 'status'),
653        array('data' => t('Operations')),
654      );
655    
656      $status = _get_status_desc();
657      $sql = "SELECT aa.*, ac.cat_name, ac.cat_id
658        FROM {affiliates_ads} aa, {affiliates_cats} ac
659        WHERE aa.cat_id = ac.cat_id";
660      $sql .=  !is_null($cat_id) ?  " AND ac.cat_id = " . $cat_id : "" ;
661      $sql .= tablesort_sql($header);
662    
663      $result = pager_query($sql, 50);
664      while ($data = db_fetch_object($result)) {
665        $rows[] = array(
666                array('data' => $data->ad_id),
667                array('data' => $data->label),
668                array('data' => $data->points),
669                array('data' => $data->type),
670                array('data' => $data->cat_name),
671                array('data' => $status[$data->status]),
672                array('data' =>
673            l('edit',   'affiliates/admin/edit/button/'   . $data->ad_id) . " " .
674            l('delete', 'affiliates/admin/delete/button/' . $data->ad_id)
675            ),
676        );
677      }
678      if (!$rows) {
679        $rows[] = array(array('data' => t('No buttons.'), 'colspan' => '4'));
680      }
681      $pager = theme('pager', NULL, 50, 0);
682      if (!empty($pager)) {
683        $rows[] = array(array('data' => $pager, 'colspan' => '4'));
684      }
685      print theme('page', theme('table', $header, $rows), t('Affiliates'));
686    }
687    
688    function affiliates_ad_category_list() {
689      $header = array(
690        array('data' => t('Name'), 'field' => 'cat_name'),
691        array('data' => t('Active'), 'field' => 'active'),
692        array('data' => t('Weight'), 'field' => 'weight', 'sort' => 'desc'),
693        array('data' => t('Action'), NULL),
694      );
695    
696      $status = _get_status_desc();
697      $sql = "SELECT cat_id, cat_name, active, weight FROM {affiliates_cats}" . tablesort_sql($header);
698    
699      $result = pager_query($sql, 50);
700      while ($data = db_fetch_object($result)) {
701        $rows[] = array(
702                array('data' => $data->cat_name),
703                array('data' => $data->active),
704                array('data' => $data->weight),
705                array('data' =>
706            l('show buttons',   'affiliates/admin/list/buttons/'   . $data->cat_id) . " " .
707            l('edit', 'affiliates/admin/edit/category/' . $data->cat_id) . " " .
708            l('delete', 'affiliates/admin/delete/category/' . $data->cat_id)
709            ),
710        );
711      }
712      if (!$rows) {
713        $rows[] = array(array('data' => t('No categories.'), 'colspan' => '4'));
714      }
715      $pager = theme('pager', NULL, 50, 0);
716      if (!empty($pager)) {
717        $rows[] = array(array('data' => $pager, 'colspan' => '4'));
718      }
719      print theme('page', theme('table', $header, $rows), t('Affiliates'));
720    }
721    
722    function _get_top_users_page() {
723    
724      $limit = variable_get(AFFILIATE_TOP_USERS_COUNT_PAGE, 5);
725      $homepage_profile = variable_get(AFFILIATE_HOMEPAGE_PROFILE, '');
726    
727      $result = db_query("SELECT s.user_id, u.name, s.total_points, s.period_points, pv.value AS homepage
728        FROM {affiliates_summary} s INNER JOIN {users} u ON u.uid = s.user_id
729        LEFT JOIN {profile_values} pv ON (u.uid = pv.uid AND pv.fid = %d)
730        GROUP BY s.user_id
731        ORDER BY total_points DESC LIMIT %d", $homepage_profile, $limit);
732    
733      $rank = 1;
734      while ($data = db_fetch_object($result)) {
735        $name = ($data->homepage) ? l($data->name, $data->homepage) : $data->name;
736        $rows[] = array(
737          array('data' => $rank++),
738          array('data' => $name),
739          array('data' => $data->total_points),
740          array('data' => $data->period_points),
741          array('data' => l('view profile', 'user/' . $data->user_id)),
742        );
743      }
744    
745      if (!$rows) {
746        $rows[] = array(array('data' => t('No clicks yet'), 'colspan' => '2'));
747      }
748    
749      $header = array('Rank', 'User', 'Total', 'Period', 'Profile');
750    
751      $output = theme('table', $header, $rows);
752    
753      cache_set(AFFILIATE_TOP_USERS_PAGE, $output);
754    }
755    
756    
757    
758    function _get_top_users_block($type = 'total') {
759      $field = 'total_points';
760      if ($type  == 'period') {
761        $field = 'period_points';
762      }
763    
764      $limit = variable_get(AFFILIATE_TOP_USERS_COUNT_BLOCK, 5);
765      $homepage_profile = variable_get(AFFILIATE_HOMEPAGE_PROFILE, '');
766    
767      $result = db_query("SELECT s.user_id, u.name, s." . $field . " AS points, pv.value AS homepage
768        FROM {affiliates_summary} s INNER JOIN {users} u ON u.uid = s.user_id
769        LEFT JOIN {profile_values} pv ON (u.uid = pv.uid AND pv.fid = %d)
770        GROUP BY s.user_id
771        ORDER BY points DESC LIMIT %d", $homepage_profile, $limit);
772    
773      while ($data = db_fetch_object($result)) {
774        $name = ($data->homepage) ? l($data->name, $data->homepage) : $data->name;
775        $rows[] = array(
776          array('data' => $name),
777          array('data' => $data->points),
778          array('data' => l('view', 'user/' . $data->user_id)),
779        );
780      }
781    
782      if (!$rows) {
783        $rows[] = array(array('data' => t('No clicks yet'), 'colspan' => '3'));
784      }
785    
786      $output = theme('table', array(), $rows);
787      cache_set(AFFILIATE_TOP_USERS_BLOCK . $type, $output);
788    }
789    
790    function _get_top_climbers_page() {
791    
792      $limit = variable_get(AFFILIATE_TOP_CLIMBERS_COUNT_PAGE, 5);
793      $homepage_profile = variable_get(AFFILIATE_HOMEPAGE_PROFILE, '');
794    
795      $result=db_query('SELECT s.user_id, u.name , (s.period_points - s.previous_period_points) AS period_climb, pv.value AS homepage
796        FROM {affiliates_summary} s INNER JOIN {users} u ON u.uid = s.user_id
797        LEFT JOIN {profile_values} pv ON (u.uid = pv.uid AND pv.fid = %d)
798        GROUP BY s.user_id
799        ORDER BY period_climb DESC LIMIT %d', $homepage_profile, $limit);
800    
801      $rank = 1;
802      while ($data = db_fetch_object($result)) {
803        $name = ($data->homepage) ? l($data->name, $data->homepage) : $data->name;
804        $rows[] = array(
805          array('data' => $rank++),
806          array('data' => $name),
807          array('data' => $data->period_climb),
808          array('data' => l('view profile', 'user/' . $data->user_id)),
809        );
810      }
811    
812      if (!$rows) {
813        $rows[] = array(array('data' => t('No clicks yet'), 'colspan' => '2'));
814      }
815    
816      $header = array('Rank', 'User', 'Climb', 'Profile');
817    
818      $output = theme('table', $header, $rows);
819    
820      cache_set(AFFILIATE_TOP_CLIMBERS_PAGE, $output);
821    }
822    
823    function _get_top_climbers_block() {
824    
825      $limit = variable_get(AFFILIATE_TOP_CLIMBERS_COUNT_BLOCK, 5);
826      $homepage_profile = variable_get(AFFILIATE_HOMEPAGE_PROFILE, '');
827    
828        $result=db_query('SELECT s.user_id, u.name , (s.period_points - s.previous_period_points) AS period_climb, pv.value AS homepage
829        FROM {affiliates_summary} s INNER JOIN {users} u ON u.uid = s.user_id
830        LEFT JOIN {profile_values} pv ON (u.uid = pv.uid AND pv.fid = %d)
831        GROUP BY s.user_id
832        ORDER BY period_climb DESC LIMIT %d', $homepage_profile, $limit);
833    
834       while ($data = db_fetch_object($result)) {
835        $name = ($data->homepage) ? l($data->name, $data->homepage) : $data->name;
836        $rows[] = array(
837          array('data' => $name),
838          array('data' => $data->period_climb),
839          array('data' => l('view', 'user/' . $data->user_id)),
840        );
841      }
842    
843      if (!$rows) {
844        $rows[] = array(array('data' => t('No clicks yet'), 'colspan' => '3'));
845      }
846    
847      $output = theme('table', array(), $rows);
848      cache_set(AFFILIATE_TOP_CLIMBERS_BLOCK, $output);
849    }
850    
851    
852    function _create_summary_data($limit = 5) {
853    
854      $period = time() - variable_get(AFFILIATE_TOP_USERS_PERIOD_INTERVAL, 86400);
855      $last_period = time() -  (2 * variable_get(AFFILIATE_TOP_USERS_PERIOD_INTERVAL, 86400));
856    
857      // Drop the table
858      db_query("DROP TABLE IF EXISTS {affiliates_summary}");
859    
860      // Create it again
861      db_query("CREATE TABLE {affiliates_summary} (
862        user_id       INT(10),
863        total_points  INT(10),
864        period_points INT(10),
865        previous_period_points INT(10),
866        PRIMARY KEY (user_id));");
867    
868      // Populate it with the users and total clicks
869      db_query("INSERT INTO {affiliates_summary}
870        SELECT a.user_id, SUM(aa.points) as lp, 0, 0
871        FROM {affiliates} a, {affiliates_ads} aa
872        WHERE aa.ad_id = a.ad_id AND a.user_id != 0
873        GROUP BY a.user_id
874        ORDER BY lp DESC
875        LIMIT %d", $limit);
876    
877      // Some SQL wizardry to update the period
878      db_query("UPDATE {affiliates_summary} s,
879        (
880          SELECT a.user_id, SUM(aa.points) AS lp
881          FROM {affiliates} a, {affiliates_ads} aa
882          WHERE a.click_time >= %d
883          AND a.ad_id = aa.ad_id
884          GROUP BY a.user_id
885          LIMIT %d
886          ) q
887        SET s.period_points = lp
888        WHERE q.user_id = s.user_id", $period, $limit);
889    
890        // Additional SQL wizardry to update the previous period
891      db_query("UPDATE {affiliates_summary} s,
892        (
893          SELECT a.user_id, SUM(aa.points) AS lp
894          FROM {affiliates} a, {affiliates_ads} aa
895          WHERE a.click_time >= %d
896          AND a.click_time < %d
897          AND a.ad_id = aa.ad_id
898          GROUP BY a.user_id
899          LIMIT %d
900          ) q
901        SET s.previous_period_points = lp
902        WHERE q.user_id = s.user_id", $last_period,$period, $limit);
903    }
904    
905    function affiliates_user($op, &$edit, &$account, $category = false) {
906      global $user;
907    
908      switch ($op) {
909        case 'view':
910          $items = array();
911    
912          if ($user->uid != $account->uid) {
913            // someone else viewing their points
914            $points = db_result(db_query("SELECT SUM(aa.points) AS points
915              FROM {affiliates} a, {affiliates_ads} aa
916              WHERE aa.ad_id = a.ad_id
917              AND a.user_id = %d", $account->uid));
918    
919            $items[] = array(
920              'title' => t('Affiliate points'),
921              'value' => $account->name . " has earned " . number_format($points) . " points.",
922            );
923          }
924        return array(t('Affiliate') => $items);
925      }
926    }
927    
928    function affiliates_list() {
929      global $user, $base_url;
930      $output = "<br/>" . nl2br(variable_get(AFFILIATE_INTRODUCTION,'')) . "<br/>";
931    
932      if ($user->uid) {
933        $output .= '<br/>' . variable_get(AFFILIATE_STATS_TEXT, 'Copy and paste the source below to link to us and get affiliate credit.');
934        $output .= '<br/>' . "You have " . _get_user_points($user->uid) . " points.";
935      }
936    
937      $cat_name = '';
938    
939      $result = db_query("SELECT aa.*, ac.cat_name
940        FROM {affiliates_ads} aa INNER JOIN {affiliates_cats} ac
941        ON ac.cat_id = aa.cat_id
942        WHERE status = 'A'
943        ORDER BY ac.weight ASC, aa.order_by ASC");
944    
945      while ($row = db_fetch_object($result)) {
946        if ($row->cat_name != $cat_name) {
947          // If the cat_name is different, we've entered a new category and should print it.
948          $output .= "<h2>" . $row->cat_name . "</h2>";
949          $cat_name = $row->cat_name;
950        }
951    
952        if ($row->type == "image") {
953          // If the type specified is an image (rather than a text link), print image so users can preview
954          // what they're going to be adding to their site.
955          $output .= "\n<img src=\"" . $row->anchor . "\"/><br/>";
956        }
957        else {
958          // Print text code.
959          $output .= "anchor: " . $row->anchor . "<br/>";
960        }
961    
962        // Now add the textarea for copying the code.
963        $output .= "<textarea rows=\"7\" cols=\"50\">";
964        $output .= "<a href=\"" . $base_url . "/aff/" . $user->uid . "/" . (int)$row->ad_id . "\">";
965    
966        if ($row->type == "image") {
967          $output .= "\n<img border=\"0\"";
968          $output .= " alt=\"" . variable_get('site_name', $base_url);
969          $output .= "\" title=\"" . variable_get('site_name', $base_url) . "\" src=\"" . $row->anchor . "\"/>";
970        }
971        else {
972          $output .= $row->anchor;
973        }
974    
975        $output .= "</a></textarea><br/>\n";
976        //Now add the label assigned through the admin interface.
977        $output .= $row->label . " : " . $row->points . " points<br/><br/>";
978      }
979    
980      print theme('page', $output);
981    }
982    
983    function affiliates_top_users() {
984      // This is generated in affiliates_cron() because it stands to be a pretty beefy query and won't scale otherwise.
985      $obj = cache_get(AFFILIATE_TOP_USERS_PAGE);
986      print theme('page', $obj->data);
987    }
988    
989    function affiliates_top_climbers() {
990      // This is generated in affiliates_cron() because it stands to be a pretty beefy query and won't scale otherwise.
991      $obj = cache_get(AFFILIATE_TOP_CLIMBERS_PAGE);
992      print theme('page', $obj->data);
993    }
994    
995    function affiliates_click() {
996      $cookie_value = md5(microtime());
997      $timeout_flag = true;
998    
999      $uid = (int)arg(1);
1000      $ad_id = (int)arg(2);
1001    
1002      $timeout_flag = _check_timeout_query();
1003      //If there's no cookie, proceed.
1004      if (!$_COOKIE['aff']) {
1005        setcookie('aff', $cookie_value, time() + 86400);
1006      }
1007    
1008      if ((!$timeout_flag) && user_access('affiliate click')) {
1009        //Only log the hit if it looks like this isn't a cheater and the user has permissions.
1010        db_query("INSERT INTO {affiliates} (
1011          user_id, cookie_id, ip, referer, ad_id, click_time)
1012          VALUES
1013          (%d, '%s', '%s', '%s', %d, %d)",
1014          $uid, $cookie_value, $_SERVER['REMOTE_ADDR'], filter_xss($_SERVER['HTTP_REFERER']), $ad_id, time());
1015    
1016        // Record it in the userpoints
1017        if (module_exists('userpoints')) {
1018          $points = (int)db_result(db_query("SELECT points FROM {affiliates_ads} WHERE ad_id = %d", $ad_id));
1019          $params = array(
1020              'points'      => $points,
1021            'uid'         => $uid,
1022            'operation'   => 'affilate click',
1023            'tid'         => variable_get(AFFILIATE_USERPOINTS_TID, 0),
1024            'reference'   => 'affiliates'
1025          );
1026          userpoints_userpointsapi($params);
1027        }
1028      }
1029    
1030      $redirect = db_result(db_query("SELECT redirect FROM {affiliates_ads} WHERE ad_id = %d", $ad_id));
1031    
1032      if ($redirect) {
1033        header("Location: " . $redirect);
1034      }
1035      else {
1036        // Redirect to the home page if there is no redirect
1037        drupal_goto();
1038      }
1039    }
1040    
1041    function affiliates_userpoints($op, $points = 0, $uid = 0, $event = 0) {
1042      global $base_url;
1043      switch($op) {
1044        case 'setting':
1045          $group = 'affiliates';
1046          $form[$group] = array(
1047            '#type' => 'fieldset',
1048            '#collapsible' => TRUE,
1049            '#collapsed' => TRUE,
1050            '#title' => t('!Points for Affiliates', userpoints_translation()),
1051          );
1052    
1053    //This form item is commented out as the value does not modify anything currently. It could be used later on as a modifier.
1054    //      $form[$group][AFFILIATE_USERPOINTS] = array(
1055    //        '#type' => 'textfield',
1056    //        '#title' => t('!Points for Affiliates clicks', userpoints_translation()),
1057    //        '#default_value' => variable_get(AFFILIATE_USERPOINTS, 1),
1058    //        '#size' => 5,
1059    //        '#maxlength' => 5,
1060    //      );
1061    
1062          $form[$group][AFFILIATE_USERPOINTS_TID] = array(
1063            '#type'          => 'select',
1064            '#title'         => t('Category'),
1065            '#default_value' => variable_get(AFFILIATE_USERPOINTS_TID, 0),
1066            '#options'       => userpoints_get_categories(),
1067            '#description'   => t('Points for Affilates button click-throughs will be assigned to this category. You can modify what categories are available by modifying the <a href="!url"><b>Userpoints taxonomy</b></a>. Points values are set in the <a href="' . $base_url . '/affiliates/admin"><b>Affiliates Admin</b></a> section on a per button basis.',
1068             array('!url' => url('admin/content/taxonomy/'. variable_get(USERPOINTS_CATEGORY_DEFAULT_VID, '')))),
1069          );
1070    
1071          return $form;
1072      }
1073    }
1074    
1075    function affiliates_block($op = 'list', $delta = 0) {
1076      global $user, $base_url;
1077    
1078      switch($op) {
1079        case 'list':
1080          $block[0]['info'] = t('Top Affiliates');
1081          $block[1]['info'] = t('Top Affiliates For Period');
1082          $block[2]['info'] = t('Top Affiliate climbers For Period');
1083          break;
1084    
1085        case 'view':
1086          switch($delta) {
1087            case 0:
1088              $block['subject'] = t('Top Affiliates');
1089    
1090              $output .= '<br/>' . t('Check out these leading affiliates!');
1091              if ($obj = cache_get(AFFILIATE_TOP_USERS_BLOCK . 'total')) {
1092                $output .= '<br/>' . $obj->data;
1093              }
1094              else {
1095                $output .= '<br/>' . t('No clicks yet.');
1096              }
1097              $output .= "<br/><a href=\"" . $base_url . "/affiliates/top_users\">more &raquo;</a>";
1098    
1099              if ($user->uid) {
1100                $output .= "<br/><br/>You have " . _get_user_points($user->uid) . " points.";
1101              }
1102    
1103             $block['content'] = $output;
1104             break;
1105    
1106            case 1:
1107              $block['subject'] = t('Top Affiliates For Period');
1108    
1109              $output .= '<br/>' . t('Leading affiliates for the last @period', array('@period' => format_interval(variable_get(AFFILIATE_TOP_USERS_PERIOD_INTERVAL, 259200))));
1110              if ($obj = cache_get(AFFILIATE_TOP_USERS_BLOCK . 'period')) {
1111                $output .= '<br/>' . $obj->data;
1112              }
1113              else {
1114                $output .= '<br/>' . t('No clicks yet.');
1115              }
1116    
1117             $block['content'] = $output;
1118             break;
1119    
1120              case 2:
1121              $block['subject'] = t('Top Affiliate Climbers For Period');
1122    
1123              $output .= '<br/>' . t('Leading affiliate climbers over the last two  @period periods', array('@period' => format_interval(variable_get(AFFILIATE_TOP_CLIMBERS_PERIOD_INTERVAL, 259200))));
1124              if ($obj = cache_get(AFFILIATE_TOP_CLIMBERS_BLOCK)) {
1125                $output .= '<br/>' . $obj->data;
1126              }
1127              else {
1128                $output .= '<br/>' . t('No clicks yet.');
1129              }
1130    
1131             $block['content'] = $output;
1132             break;
1133    
1134          }
1135          break;
1136      }
1137    
1138      return $block;
1139    }
1140    
1141    function _get_user_points($uid = 0) {
1142      $points = 0;
1143    
1144      if ($uid) {
1145        $points = (int)db_result(db_query('SELECT SUM(aa.points) AS points FROM {affiliates} a, {affiliates_ads} aa
1146        WHERE a.user_id = %d
1147        AND aa.ad_id = a.ad_id LIMIT 1', $uid));
1148      }
1149    
1150      return $points;
1151    }
1152    
1153    function _check_timeout_query() {
1154      // Timeout allows one click per IP per day. Hope there aren't too many people going over a proxy.
1155      return (int)db_result(db_query("SELECT count(*) FROM {affiliates} WHERE ip = '%s' AND %d < (click_time + %d)",
1156        $_SERVER['REMOTE_ADDR'], time(), variable_get(AFFILIATE_CLICK_IGNORE_INTERVAL, 86400)));
1157    }
1158    
1159    function _get_profile_fields() {
1160      $profile = array(0 => 'None');
1161    
1162      $result = db_query("SELECT fid, title FROM {profile_fields} ORDER BY fid");
1163      while ($row = db_fetch_object($result)) {
1164        $profile[$row->fid] = $row->title;
1165      }
1166    
1167      return $profile;
1168    }
1169    
1170    function _get_status_desc() {
1171      return array(
1172        'a' => 'Active',
1173        'i' => 'Inactive',
1174        'h' => 'Hidden',
1175        );
1176    }
1177    
1178    function _get_categories() {
1179      $cats = array();
1180    
1181      $result = db_query("SELECT cat_id, cat_name FROM {affiliates_cats} WHERE active = 'Y' ORDER BY cat_name ASC");
1182      while ($row = db_fetch_object($result)) {
1183        $cats[$row->cat_id] = $row->cat_name;
1184      }
1185      return $cats;
1186    }
1187    
1188    function _get_affiliate_button($ad_id = 0) {
1189      return db_fetch_object(db_query('SELECT * FROM {affiliates_ads} WHERE ad_id = %d', $ad_id));
1190    }
1191    
1192    function _get_affiliate_category($cat_id = 0) {
1193      return db_fetch_object(db_query('SELECT * FROM {affiliates_cats} WHERE cat_id = %d', $cat_id));
1194    }
1195    

Legend:
Removed from v.1.1  
changed lines
  Added in v.1.2

  ViewVC Help
Powered by ViewVC 1.1.3