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

Contents of /contributions/modules/textlinkads/textlinkads.module

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


Revision 1.8 - (show annotations) (download) (as text)
Mon Jul 14 17:26:36 2008 UTC (16 months, 2 weeks ago) by mikejoconnor
Branch: MAIN
CVS Tags: HEAD
Branch point for: DRUPAL-6--2
Changes since 1.7: +360 -41 lines
File MIME type: text/x-php
mjo: Initial commit of inlinks support to the textlinkads module
1 <?php
2 // $Id: textlinkads.module,v 1.7 2008/06/20 16:18:17 mikejoconnor Exp $
3
4 define('TEXTLINKADS_VERSION', '$Id: textlinkads.module,v 1.7 2008/06/20 16:18:17 mikejoconnor Exp $');
5 //define('TEXTLINKADS_MODULE_PATH', drupal_get_path('module', 'textlinkads'));
6
7 function textlinkads_help($path, $arg) {
8 switch ($path) {
9 case 'admin/help#textlinkads':
10 $output = '<p>'. t('The Text-Link-Ads module allows you to sell advertising space on your site via %tla', array('%tla' => '<a href="http://www.text-link-ads.com/">Text-Link-Ads.com</a>')) .'</p>';
11 $output .= '<p>'. t('With the Text-Link-Ads module: <blockquote><p>YOU can choose to approve or deny any Text Link Ads sold prior to the links being published on your website. This ensures that only quality and relevant links appear on your website.</p><p>You make money. Sales, invoicing, and customer service are all handled by TLA. You can receive payment via check or PayPal. Payments are sent to publishers the first of every month with a $25 minimum payout.</p></blockquote>') .'</p>';
12 $output .= '<p>'. t('For more information see the Text-Link-Ads.com <a href="http://www.text-link-ads.com/publisher_program.php">Publisher Program page</a>.') .'</p>';
13 $output .= '<h2>'. t('Module features') .'</h2>';
14 $output .= '<ul><li>'. t('%Simplified_setup right on your site. All you need is your Website XML Key from Text-Link-Ads.com and you\'re ready to start publishing ads.', array('%Simplified_setup' => l(t('Simplified setup'), 'admin/settings/textlinkads'))) .'</li>';
15 $output .= '<li>'. t('A %built_in_tool to customize the looks of the ads, including borders, background color, link color and font size.', array('%built_in_tool' => l(t('built-in tool'), 'admin/settings/textlinkads'))) .'</li>';
16 $output .= '<li>'. t('Access to your %publisher_statistics from within your website. See your site details, including how much money you\'ve earned and how many links are being served.', array('%publisher_statistics' => l(t('publisher statistics'), 'textlinkads/stats'))) .'</li>';
17 $output .= '<li>'. t('Cron-based updates of your ads. The ad links are kept up to date via Drupal\'s cron functionality.') .'</li></ul>';
18 $output .= '<h2>'. t('Getting started') .'</h2>';
19 $output .= '<ol>';
20 $output .= '<li>'. t('Install the module by placing it in the modules directory and enabling it from the %admin_modules page. No database changes are necessary.', array('%admin_modules page' => l('admin/modules', 'admin/modules'))) .'</li>';
21 $output .= '<li>'. t('Sign up for a <a href="http://www.text-link-ads.com/log.php?logfunc=login&action=create_account">Text-Link-Ads.com publisher account</a> and make note of your <a href="http://www.text-link-ads.com/my_account.php?view=my_sites">Website XML Key</a>.') .'</li>';
22 $output .= '<li>'. t('Browse to the %admin_settings_textlinkads page on your site. Enter the <strong>Website XML Key</strong> in the field of the same name.', array('%admin_settings_textlinkads' => l('admin/settings/textlinkads', 'admin/settings/textlinkads'))) .'</li>';
23 $output .= '<li>'. t('On the same page, enter the <strong>Ad Block Heading</strong>. Your links will be available as a block. The value you enter will be the title of the block. You may leave this field blank.') .'</li>';
24 $output .= '<li>'. t('On the same page, use the <strong>Textlinkads Appearance Settings</strong> settings to customize the way your ad links look. Press <strong>Submit</strong> to save all of the settings for this page.') .'</li>';
25 $output .= '<li>'. t('Now you must enable the block that will show your ad links. Browse to the %blocks_administration_page and enable the block entitled <strong>text link ads advertisments</strong>', array('%blocks_administration_page' => l(t('blocks administration page'), 'admin/block'))) .'</li>';
26 $output .= '<li>'. t('Your site will communicate with the Text-Link-Ads.com site every time cron.php is run. If you have already configured cron jobs for your site ads will start appearing in the block as soon as the next cron run completes (note that Text-Link-Ads.com must sell some links for your site first). If you don\'t have cron tasks enabled follow the <a href="http://drupal.org/cron">directions found on Drupal.org</a> for doing so. You may also consider installing the <a href="http://drupal.org/project/poormanscron">Poormanscron module</a> to help. As a last resort, you can manually trigger cron by %clicking_this_link (will result in the screen going blank... that\'s normal).', array('%clicking_this_link' => l(t('clicking this link'), 'cron.php'))) .'</li>';
27 $output .= '<li>'. t('Once you have set everything up properly and Text-Link-Ads.com has sold some links on your site, you can %monitor_your_statistics_and_earnings from your Drupal site. All that is required is the same password that you use to log onto the Text-Link-Ads.com site. Enjoy!', array('%monitor_your_statistics_and_earnings' => l('monitor your statistics and earnings', 'textlinkads/stats'))) .'</li>';
28 $output .= '</ol>';
29 return $output;
30
31 case 'admin/settings/textlinkads':
32 return '<p>'. t('You are using version %version of the Text-Link-Ads module.', array('%version' => TEXTLINKADS_VERSION)) .'</p><p>'. t('For complete instructions on configuring this module, refer to the %help_pages.', array('%help_pages' => l(t('Help pages'), 'admin/help/textlinkads'))) .'</p>';
33 }
34 }
35
36 function textlinkads_perm() {
37 return array('administer text link ads', 'administer inlinks by node');
38 }
39
40 function textlinkads_cron() {
41 if ( variable_get('textlinkads_last_update', 0) < (time() - 3600) || strlen(textlinkads_get_links('text')) < 20) {
42 textlinkads_check_update();
43 }
44 }
45
46 function textlinkads_menu() {
47 $items = array();
48 $items['textlinkads/stats'] = array(
49 'title' => t('TextLinkAds stats'),
50 'page callback' => 'textlinkads_stats_page',
51 'access arguments' => array('administer text link ads'),
52 'type' => MENU_NORMAL_ITEM,
53 );
54
55 $items['textlinkads/update_now'] = array(
56 'page callback' => 'textlinkads_check_update',
57 'type' => MENU_NORMAL_ITEM,
58 'access arguments' => array('administer text link ads'),
59 );
60
61 $items['admin/settings/textlinkads'] = array(
62 'title' => t('TextLinkAds Settings'),
63 'description' => t('Settings for the TextLinkAds module'),
64 'page callback' => 'drupal_get_form',
65 'page arguments' => array('textlinkads_admin_settings'),
66 'access arguments' => array('administer site configuration'),
67 );
68 $items['textlinkads/sync'] = array(
69 'title' => 'Textlinkads Sync',
70 'page callback' => 'textlinkads_inlinks_sync',
71 'access arguments' => array('access content'),
72 'type' => MENU_CALLBACK
73 );
74 return $items;
75 }
76
77 function textlinkads_block($op = 'list', $delta = 0, $edit = array()) {
78 switch ($op) {
79 case 'list':
80 $blocks[0]['info'] = t('text link ads advertisments');
81 return $blocks;
82 case 'view':
83 switch ($delta) {
84 case 0:
85 $block = textlinkads_get_block();
86 break;
87 }
88 return $block;
89 }
90 }
91
92 function textlinkads_get_block() {
93 $block['content'] = textlinkads_content();
94 if (!empty($block['content'])) {
95 $block['subject'] = t(variable_get('textlinkads_ad_block_title', 'Advertisments'));
96 return $block;
97 }
98 }
99 function textlinkads_theme() {
100 return array(
101 'textlinkads_rss_ad' => array(
102 'arguments' => array('link'),
103 ),
104 'textlinkads_ads' => array(
105 'arguments' => array('link'),
106 ),
107 'textlinkads_stats' => array(
108 'arguments' => array('stats_data'),
109 ),
110 'textlinkads_themer_colors' => array(
111 'arguemnts' => array('form'),
112 ),
113 );
114 }
115
116 function textlinkads_content() {
117 $output = theme('textlinkads_ads', textlinkads_get_links('text'));
118 return $output;
119 }
120
121 function textlinkads_admin_settings() {
122
123 if (!empty($_POST)) {
124 variable_set('textlinkads_last_update', 0);
125 }
126 $types_enabled = variable_get('textlinkads_inlinks_nodes_enabled', array());
127 $types = array();
128 foreach(node_get_types() as $key => $value) {
129 $types[$key] = $value->name;
130 }
131 $form['textlinkads_inlinks'] = array (
132 '#type' => 'fieldset',
133 '#access' => true,
134 '#title' => t('Text-Link-Ads Inlink'),
135 '#collapsible' => true,
136 '#collapsed' => true,
137 'textlinkads_inlinks_nodes_enabled' =>
138 array (
139 '#type' => 'checkboxes',
140 '#title' => t('Enable Inlinks'),
141 '#default_value' => $types_enabled,
142 '#options' => $types,
143 ),
144 );
145 $form['textlinkads_website_xml_key'] = array(
146 '#type' => 'textfield',
147 '#title' => t('Website XML Key'),
148 '#default_value' => variable_get('textlinkads_website_xml_key', ''),
149 '#description' => t('You get your XML Site Key from the <a href="http://www.text-link-ads.com/my_account.php?view=my_sites">Get Ad Code page</a> on Text-Link-Ads.com. Each of your sites has its own code that looks something like this: <code>A4WWSAAOULU1XGHWU78G</code>.'),
150 );
151 $form['textlinkads_ad_block_title'] = array(
152 '#type' => 'textfield',
153 '#title' => t('Ad block Heading'),
154 '#default_value' => variable_get('textlinkads_ad_block_title', 'Advertisments'),
155 '#description' => t('Enter a heading for the Ad block. It is alright to leave it blank.'),
156 );
157
158 drupal_set_html_head(textlinkads_get_js());
159 drupal_add_js(drupal_get_path('module', 'textlinkads') .'/textlinkads.js');
160 $total_options = drupal_map_assoc(array(4, 6, 8, 10));
161 $row_options = drupal_map_assoc(array(1, 2, 3, 4, 8, 10));
162 $font_options = drupal_map_assoc(array(6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18));
163
164 $form['textlinkads_themer'] = array('#type' => 'fieldset', '#title' => t('Textlinkads Appearance Settings'));
165 $form['textlinkads_themer']['textlinkads_total'] = array(
166 '#type' => 'select',
167 '#options' => $total_options,
168 '#title' => t('Number of Ads'),
169 '#default_value' => variable_get('textlinkads_total', 4),
170 );
171 $form['textlinkads_themer']['textlinkads_rows'] = array(
172 '#type' => 'select',
173 '#options' => $row_options,
174 '#title' => t('Number of Rows of Ads'),
175 '#default_value' => variable_get('textlinkads_rows', 4),
176 );
177 $form['textlinkads_themer']['textlinkads_font'] = array(
178 '#type' => 'select',
179 '#options' => $font_options,
180 '#title' => t('Font Size'),
181 '#default_value' => variable_get('textlinkads_font', 12),
182 );
183
184 $form['textlinkads_themer']['textlinkads_colors'] = array('#type' => 'fieldset', '#title' => t('Colors'), '#theme' => 'textlinkads_themer_colors');
185 $form['textlinkads_themer']['textlinkads_colors']['textlinkads_border_color'] = array(
186 '#type' => 'textfield',
187 '#title' => t('Border'),
188 '#size' => 8,
189 '#maxlength' => 7,
190 '#default_value' => variable_get('textlinkads_border_color', '#000000'),
191 '#suffix' => '<a href="#" onclick="cp2.select(document.getElementById(\'edit-textlinkads-border-color\'),\'border_color_picker\');return false;" id="border_color_picker" name="border_color_picker">Pick Color</a>',
192 );
193 $form['textlinkads_themer']['textlinkads_colors']['textlinkads_no_border'] = array(
194 '#type' => 'checkbox',
195 '#title' => t('No Border'),
196 '#default_value' => variable_get('textlinkads_no_border', 0),
197 '#attributes' => array('onclick' => 'update_border_color()')
198 );
199 $form['textlinkads_themer']['textlinkads_colors']['textlinkads_bg_color'] = array(
200 '#type' => 'textfield',
201 '#title' => t('Background'),
202 '#size' => 8,
203 '#maxlength' => 7,
204 '#default_value' => variable_get('textlinkads_bg_color', '#ffffff'),
205 '#suffix' => '<a href="#" onclick="cp2.select(document.getElementById(\'edit-textlinkads-bg-color\'),\'bg_color_picker\');return false;" id="bg_color_picker" name="bg_color_picker">Pick Color</a>',
206 );
207 $form['textlinkads_themer']['textlinkads_colors']['textlinkads_no_bg'] = array(
208 '#type' => 'checkbox',
209 '#title' => t('Transparent Background'),
210 '#default_value' => variable_get('textlinkads_no_bg', 0),
211 '#attributes' => array('onclick' => 'update_bg_color()')
212 );
213 $form['textlinkads_themer']['textlinkads_colors']['textlinkads_link_color'] = array(
214 '#type' => 'textfield',
215 '#title' => t('Link Color'),
216 '#size' => 8,
217 '#maxlength' => 7,
218 '#default_value' => variable_get('textlinkads_link_color', '#0000ff'),
219 '#suffix' => '<a href="#" onclick="cp2.select(document.getElementById(\'edit-textlinkads-link-color\'),\'link_color_picker\');return false;" id="link_color_picker" name="link_color_picker">Pick Color</a>',
220 );
221
222 $form['textlinkads_themer']['textlinkads_preview'] = array('#type' => 'fieldset', '#title' => t('Example'));
223 $form['textlinkads_themer']['textlinkads_preview']['preview_div'] = array('#value' => '<div id="preview"></div><script type="text/javascript">cp2.writeDiv();</script>');
224
225 return system_settings_form($form);
226 }
227
228 function textlinkads_nodeapi(&$node, $op, $teaser = NULL, $page = NULL) {
229 switch ($op) {
230 case 'load':
231 $q = $_GET['q'];
232 if ($q == 'rss.xml' || $q == 'node/feed') {
233 $link = theme('textlinkads_rss_ad', textlinkads_next_rss_ad());
234 $node->teaser .= $link;
235 }
236 $node->textlinkads_inlinks = db_result(db_query("SELECT status FROM {textlinkads_inlinks} WHERE nid = %d", $node->nid));
237 break;
238 case 'view':
239 if(textlinkads_inlinks_allow_links($node)) {
240 $node->content['body']['#value'] = textlinkads_inlinks_add_links($node->content['body']['#value'], $node->nid);
241 }
242 break;
243 case 'update':
244 case 'insert':
245 textlinkads_inlinks_notify_tla('add', $node->nid);
246 if($node->textlinkads_inlinks_status === 0) {
247 db_query("DELETE FROM {textlinkads_inlinks} WHERE nid = %d", $node->nid);
248 }
249 else {
250 db_query("DELETE FROM {textlinkads_inlinks} WHERE nid = %d", $node->nid);
251 db_query("INSERT INTO {textlinkads_inlinks} (nid, status) VALUES (%d, %d)", $node->nid, $node->textlinkads_inlinks_status);
252 }
253 break;
254 }
255
256 }
257
258 function textlinkads_stats_page() {
259 if (!$key = variable_get('textlinkads_website_xml_key', '')) {
260 drupal_set_message(t('You need to enter your Customer ID on the <a href="%admin">administration page</a> before you can view your statistics here.', array('%admin' => url('admin/settings/textlinkads'))), 'error');
261 drupal_goto('admin/settings/textlinkads');
262 }
263
264 if ($_SESSION['textlinkads_password']) {
265 textlinkads_stats_page_show();
266 }
267 else {
268 return drupal_get_form('textlinkads_stats_page_form');
269 }
270 }
271
272 function textlinkads_stats_page_form($form_state) {
273 $form['textlinkads_password'] = array(
274 '#type' => 'password',
275 '#title' => t('Password'),
276 '#size' => 30,
277 '#max_length' => 64,
278 );
279 $form['textlinkads_xml_key'] = array(
280 '#type' => 'value',
281 '#value' => variable_get('textlinkads_website_xml_key', ''),
282 );
283 $form['values']['op'] = array(
284 '#type' => 'submit',
285 '#value' => t('Submit Settings')
286 );
287 $form['#submit'][] = 'textlinkads_stats_page_submit';
288 $form['#validate'][] = 'textlinkads_stats_page_validate';
289 return $form;
290 }
291
292 function textlinkads_stats_page_validate($form, &$form_state) {
293 if (!$form_state['values']['textlinkads_password'] && !$_SESSION['textlinkads_password']) {
294 form_set_error('textlinkads_password', t('Please enter your password'));
295 return;
296 }
297 $_SESSION['textlinkads_xml'] = file_get_contents('http://www.text-link-ads.com/publisher_stats_xml.php?xml_key='
298 . $form_state['values']['textlinkads_xml_key']
299 .'&password='
300 . ($_SESSION['textlinkads_password'] ? $_SESSION['textlinkads_password'] : $_SESSION['textlinkads_password'] = md5($form_state['values']['textlinkads_password'])));
301
302 if ((strpos('<?xml version="1.0" ?>', $_SESSION['textlinkads_xml']) !== 0) && (strpos('invalid password', strtolower($_SESSION['textlinkads_xml'])) !== false)) {
303 drupal_set_message(t('Invalid password'), 'error');
304 unset($_SESSION['textlinkads_password']);
305 }
306 }
307
308 function textlinkads_stats_page_submit($form, $form_state) {
309 if (!form_get_errors() && $_SESSION['textlinkads_password']) {
310 textlinkads_stats_page_show();
311 }
312 }
313
314 function textlinkads_stats_page_show() {
315 $parser = new xml2array();
316 $data = $parser->parseXMLintoarray($_SESSION['textlinkads_xml']);
317 print theme('page', theme('textlinkads_stats', $data));
318 }
319
320 /******************
321 * theme functions
322 */
323
324 function theme_textlinkads_rss_ad($link) {
325 $advertisement = variable_get('textlinkads_advertisement_word', t('Advertisement'));
326 return "\n\n$advertisement: {$link['rssbeforetext']} <a href='{$link['url']}'>{$link['rsstext']}</a> {$link['rssaftertext']}";
327 }
328
329
330 function theme_textlinkads_ads($links) {
331 $output = '';
332 if(count($links) > 0) {
333
334 $font_size = variable_get('textlinkads_font', 12);
335 $rows = variable_get('textlinkads_rows', 4);
336 $columns = ceil(count($links) / $rows);
337 $link_color = variable_get('textlinkads_link_color', '#0000ff');
338 $bg_color = variable_get('textlinkads_bg_color', '#0000ff');
339 $border_color = variable_get('textlinkads_border_color', '#0000ff');
340 $no_border = variable_get('textlinkads_no_border', 0);
341 $no_bg = variable_get('textlinkads_no_bg', 0);
342
343 $output = '<table style="width: 100%; margin: 5px auto;border: '. ($no_border ? 'none' : "1px solid $border_color") .'; border-spacing: 0px;background: '. ($no_bg ? 'transparent' : $bg_color) .';" cellpadding="5" cellspacing="0"><tbody>';
344
345 while (count($links) > 0) {
346 $output .= "<tr>";
347 for ($j = 0; $j < $columns; $j++) {
348 if ($link = array_pop($links)) {
349 $output .= "<td align='center'><span style='font-size:{$font_size}px; color=#000000;'>{$link['beforetext']} <a href='{$link['url']}' style='font-size:{$font_size}px; color:{$link_color}'>{$link['text']}</a> {$link['aftertext'][$i]}</span></td>";
350 }
351 else {
352 $output .= "<td></td>";
353 }
354 }
355 $output .= "</tr>";
356 }
357 $output .= "</tbody></table>";
358 }
359 return $output;
360 }
361
362
363 function theme_textlinkads_stats($stats_data) {
364 $last_update = format_date(variable_get('textlinkads_last_update', 0), 'custom', 'Y-m-d G:i:s') .
365 ' '. l(t('Update now'), 'textlinkads/update_now');
366 $header = array('', '');
367 $rows[] = array("domain:", $stats_data['WEBSITE']['STATS']['DOMAIN']);
368 $rows[] = array("description:", $stats_data['WEBSITE']['STATS']['DESCRIPTION']);
369 $rows[] = array("alexa rank:", $stats_data['WEBSITE']['STATS']['ALEXA_RANK']);
370 $rows[] = array("date created:", $stats_data['WEBSITE']['STATS']['CREATE_DATE']);
371 $rows[] = array("earnings this month:", $stats_data['WEBSITE']['STATS']['CURRENT_MONTHS_EARNINGS']);
372 $rows[] = array("last update of ads:", $last_update);
373
374 $output = theme('table', $header, $rows);
375
376 if (!empty($stats_data['WEBSITE']['ACTIVELINKS']['ACTIVELINK'])) {
377 $rows = array();
378 $output .= t('<h3>Currently Active Links:</h3>');
379 if (!$stats_data['WEBSITE']['ACTIVELINKS']['ACTIVELINK']['URL'] && is_array($stats_data['WEBSITE']['ACTIVELINKS']['ACTIVELINK'])) {
380 foreach ($stats_data['WEBSITE']['ACTIVELINKS']['ACTIVELINK'] as $activelink) {
381 $rows[] = array("<a href=\"$activelink[URL]\">$activelink[TEXT]</a>", "<b>({$activelink[CURRENT_MONTHS_EARNINGS]})</b>");
382 }
383 }
384 else {
385 $rows[] = array("<a href=\"{$stats_data[WEBSITE][ACTIVELINKS][ACTIVELINK][URL]}\">{$stats_data[WEBSITE][ACTIVELINKS][ACTIVELINK][TEXT]}</a>", "<b>({$stats_data[WEBSITE][ACTIVELINKS][ACTIVELINK][CURRENT_MONTHS_EARNINGS]})</b>");
386 }
387 $output .= theme('table', $header, $rows);
388 }
389
390 return $output;
391 }
392
393 function theme_textlinkads_themer_colors($form) {
394
395 $output .= '<table>';
396 $output .= '<tr><td>'. drupal_render($form['textlinkads_border_color']) .'</td><td>'. drupal_render($form['textlinkads_no_border']) .'</td></tr>';
397 $output .= '<tr><td>'. drupal_render($form['textlinkads_bg_color']) .'</td><td>'. drupal_render($form['textlinkads_no_bg']) .'</td></tr>';
398 $output .= '</table>';
399 $output .= drupal_render($form);
400
401 return $output;
402 }
403
404 /*
405 *
406 * Helper functions from text-link-ads file
407 *
408 */
409 function textlinkads_check_update() {
410 $CONNECTION_TIMEOUT = 10;
411 $url = 'http://www.text-link-ads.com/xml.php?inventory_key='. check_plain(variable_get(textlinkads_website_xml_key, ''))
412 .'&referer='. urlencode(request_uri())
413 .'&user_agent='. urlencode($_SERVER['HTTP_USER_AGENT'])
414 .'&drupal_module_version='. urlencode(TEXTLINKADS_VERSION);
415 textlinkads_update_links($url, $CONNECTION_TIMEOUT);
416 }
417
418 function textlinkads_update_links($url, $time_out) {
419 $xml = textlinkads_file_get_contents($url, $time_out);
420 $xml = substr($xml, strpos($xml, '<?'));
421
422 db_query("DELETE FROM {textlinkads}");
423 $parser = new xml2array();
424 if ($data = $parser->parseXMLintoarray($xml)) {
425 // there are no links or just one link
426 if (is_array($data['LINKS']) && $data['LINKS']['LINK']['URL']) {
427 $links = array($data['LINKS']['LINK']);
428 }
429 else {
430 $links = $data['LINKS']['LINK'];
431 if (!is_array($links)) {
432 /* When no ads for site, $data looks like this:
433 <?xml version="1.0" ?> <Links> </Links>
434 And $links = ' '
435 Subsequent code assumes we have an array - when no ads available,
436 $links is a string containing only spaces. So, let's force
437 $links to be an array so the code will work.
438 */
439 $links = array();
440 }
441 }
442 foreach ($links as $key => $values) {
443 db_query("INSERT INTO {textlinkads} (url, text, beforetext, aftertext, rsstext, rssbeforetext, rssaftertext, nid) VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', %d)", $values['URL'], $values['TEXT'], $values['BEFORETEXT'], $values['AFTERTEXT'], $values['RSSTEXT'], $values['RSSBEFORETEXT'], $values['RSSAFTERTEXT'], $values['POSTID']);
444 }
445 }
446 $count=count($links);
447 watchdog('TextLinkAds', "update_links: $count ads found" );
448 variable_set('textlinkads_last_update', time());
449 }
450
451 /**
452 * returns a single $link
453 *
454 */
455 function textlinkads_next_rss_ad() {
456 static $links = NULL;
457
458 if (!is_array($links)) {
459 $links = textlinkads_get_links('rss');
460 shuffle($links);
461 }
462
463 return array_pop($links);
464 }
465
466 /**
467 * Builds an array with the information needed to render ads on the site or in RSS
468 *
469 * @param string $type
470 * 'text' or 'rss'
471 * @return Array
472 */
473 function textlinkads_get_links($type = 'text') {
474
475 $links = array();
476 $limit = ($type == 'text') ? variable_get('textlinkads_total', 4) : variable_get('feed_default_items', 10);
477 $where = ($type == 'text') ? 'text IS NOT NULL && beforetext IS NOT NULL && aftertext IS NOT NULL' : 'rsstext IS NOT NULL';
478 $result = db_query("SELECT * FROM {textlinkads} WHERE $where AND nid = 0 LIMIT %d", $limit);
479 while ($row = db_fetch_array($result)) {
480
481 $links[] = $row;
482 }
483
484 return $links;
485 }
486
487 function textlinkads_file_get_contents($url, $time_out) {
488 $url = parse_url($url);
489
490 if ($handle = @fsockopen ($url["host"], 80)) {
491 if(function_exists(socket_set_timeout)) {
492 socket_set_timeout($handle,$time_out,0);
493 }
494 else if(function_exists('stream_set_timeout')) {
495 stream_set_timeout($handle,$time_out,0);
496 }
497
498 fwrite ($handle, "GET $url[path]?$url[query] HTTP/1.0\r\nHost: $url[host]\r\nConnection: Close\r\n\r\n");
499 while (!feof($handle)) {
500 $string .= @fread($handle, 40960);
501 }
502 fclose($handle);
503 }
504
505 return $string;
506 }
507
508 class xml2array {
509 function parseXMLintoarray ($xmldata){ // starts the process and returns the final array
510 $xmlparser = xml_parser_create();
511 xml_parse_into_struct($xmlparser, $xmldata, $arraydat);
512 xml_parser_free($xmlparser);
513 $semicomplete = $this->subdivide($arraydat);
514 $complete = $this->correctentries($semicomplete);
515 return $complete;
516 }
517
518 function subdivide ($dataarray, $level = 1){
519 foreach ($dataarray as $key => $dat){
520 if ($dat[level] === $level && $dat[type] === "open"){
521 $toplvltag = $dat[tag];
522 }
523 elseif ($dat[level] === $level && $dat[type] === "close" && $dat[tag]=== $toplvltag) {
524 $newarray[$toplvltag][] = $this->subdivide($temparray,($level +1));
525 unset($temparray,$nextlvl);
526 }
527 elseif ($dat[level] === $level && $dat[type] === "complete"){
528 if (isset($newarray[$dat['tag']]) && is_array($newarray[$dat['tag']])){
529 $newarray[$dat['tag']][] = $dat['value'];
530 }
531 elseif (isset($newarray[$dat['tag']]) && !is_array($newarray[$dat['tag']])){
532 $newarray[$dat['tag']] = array($newarray[$dat['tag']], $dat['value']);
533 }
534 else {
535 $newarray[$dat['tag']]=$dat['value'];
536 }
537 }
538 elseif ($dat[type] === "complete"||$dat[type] === "close"||$dat[type] === "open"){
539 $temparray[]=$dat;
540 }
541 }
542 return $newarray;
543 }
544
545 function correctentries($dataarray){
546 if (is_array($dataarray)){
547 $keys = array_keys($dataarray);
548 if (count($keys)== 1 && is_int($keys[0])){
549 $tmp = $dataarray[0];
550 unset($dataarray[0]);
551 $dataarray = $tmp;
552 }
553 $keys2 = array_keys($dataarray);
554 foreach($keys2 as $key){
555 $tmp2 = $dataarray[$key];
556 unset($dataarray[$key]);
557 $dataarray[$key] = $this->correctentries($tmp2);
558 unset($tmp2);
559 }
560 }
561 return $dataarray;
562 }
563 }
564
565
566 function textlinkads_get_js() {
567 $path = drupal_get_path('module', 'textlinkads');
568 $default_font_size = variable_get('textlinkads_font', 12);
569 $default_rows = variable_get('textlinkads_rows', 4);
570 $default_total_number = variable_get('textlinkads_total', 4);
571 $default_link_color = variable_get('textlinkads_link_color', '#0000ff');
572 $default_bg_color = variable_get('textlinkads_bg_color', '#0000ff');
573 $default_border_color = variable_get('textlinkads_border_color', '#0000ff');
574 $default_no_border = variable_get('textlinkads_no_border', 0);
575 $default_no_bg = variable_get('textlinkads_no_bg', 0);
576 $js =<<<__END__
577 <script type="text/javascript" src="/$path/colorpicker2.js"></script>
578 <script type="text/javascript">//<![CDATA[
579 var cp2 = new ColorPicker();
580 var table_total_ads = $default_total_number;
581 var table_rows = $default_rows;
582 var font_size = $default_font_size;
583 var link_color = '$default_link_color';
584 var bg_color = '$default_bg_color';
585 var border_color = '$default_border_color';
586 var no_border = $default_no_border;
587 var no_bg = $default_no_bg;
588 var example_link = 'Example Link';
589 var link_color_txt = 'link_color';
590 //]]>
591 </script>
592 <script type="text/javascript" src="/$path/textlinkads.js"></script>
593
594 __END__;
595 return $js;
596 }
597
598 /**
599 * function textlinkads_inlinks_add_links()
600 * @param string $data The text to be searched for keyword/links
601 * @param array $links An array of keyword => link entries to be replaced
602 *
603 * @return string The text after link replacement
604 */
605 function textlinkads_inlinks_add_links($data = NULL, $nid = NULL) {
606 $split = array("'(<script[^>]*?>.*?</script>)'", // strip out javascript
607 "'<style[^>]*?>.*?</style>'", // strip out styelsheets
608 "'(<a[\/\!]*?[^<>]*?/a>)'", // strip out html tags
609 "'(<[\/\!]--*?[^<>]*?-->)'", // strip out html comments
610 "'(<[\/\!]*?[^<>]*?>)'si", // strip out html tags
611 );
612 global $textlinkads_inlinks_links;
613 if (is_numeric($nid)) {
614 $results = db_query("SELECT text, url FROM {textlinkads} WHERE nid = %d", $nid);
615 $links = array();
616 while($link = db_fetch_object($results)) {
617 $links[$link->text] = $link->url;
618 }
619 $textlinkads_inlinks_links = $links;
620 $return = _textlinkads_inlinks_add_links($data, $split);
621 unset($textlinkads_inlinks_links);
622 return $return;
623 }
624 }
625
626 /**
627 * function _textlinkads_inlinks_add_links()
628 * @param $data string The string to be parsed for links
629 * @param array split The the regex to avoid replaceing unwanted items
630 *
631 * @return string The string after link replacement as occured
632 */
633
634 function _textlinkads_inlinks_add_links($data, $split) {
635 if(count($split) >= 1) {
636 $data2 = preg_split($split[0], $data, NULL, PREG_SPLIT_DELIM_CAPTURE);
637 array_shift($split);
638 if($data2) {
639 foreach($data2 as $key => $value) {
640 $return .= _textlinkads_inlinks_add_links($value, $split, $return);
641 }
642 return $return;
643 }
644 else {
645 return _textlinkads_inlinks_add_links_helper($data);
646 }
647 }
648 else {
649 return _textlinkads_inlinks_add_links_helper($data);
650 }
651 }
652
653 /**
654 * Function _textlinkads_inlinks_add_links_helper()
655 * A helper function for replacing keywords with links
656 * @param string $data The string to be searched for keywords
657 *
658 * @return string the data after keyword search/replace
659 */
660
661 function _textlinkads_inlinks_add_links_helper($data) {
662 global $textlinkads_inlinks_links;
663 //Don't replace anything within tags
664 if(substr($data, 0, 1) == '<') {
665 return $data;
666 }
667
668 elseif(is_array($textlinkads_inlinks_links)) {
669 $lower_data = strtolower($data);
670 //replace any keyword once
671 foreach ($textlinkads_inlinks_links as $keyword => $link) {
672 if (strpos(strtolower($lower_data), strtolower($keyword))) {
673 $start = strpos(strtolower($lower_data), strtolower($keyword));
674 $length = strlen($keyword);
675 $link_text = substr($data, $start, $length);
676 $link = '<a href="'. $link .'">'. $link_text .'</a>';
677 $replace_count = 1; // replace count can only be a variable??
678 $data = str_replace($link_text, $link, $data, $replace_count);
679 unset($textlinkads_inlinks_links[$keyword]);
680 }
681 }
682 return $data;
683 }
684 }
685 /**
686 * Function textlinkads_inlinks_sync()
687 * This funciton enables the tla servers to sync with our database
688 */
689 function textlinkads_inlinks_sync() {
690 header('Content-type: application/xml; charset="utf-8"',true);
691 $options = array();
692 $options['textlinkads_key'] = $_GET['textlinkads_key'];
693 $options['textlinkads_action'] = $_GET['textlinkads_action'];
694 $opitons['post_id'] = $_GET['post_id'];
695 watchdog('TextLinkAds', 'Textlinks sync initiated<br /><pre>'. var_export($options, true) .'</pre>');
696 $key = variable_get('textlinkads_website_xml_key', '');
697 if (!empty($_GET['textlinkads_key']) && $_GET['textlinkads_key'] == $key) {
698 $op = check_plain($_GET['textlinkads_action']);
699 switch ($op) {
700 case 'debug':
701 //perform debugging
702 break;
703 case 'sync_posts':
704 print textlinkads_inlinks_sync_posts();
705 exit;
706 break;
707 case 'rest_sync_limit':
708 textlinkads_inlinks_set_max_post_id();
709 break;
710 case 'reset_syncing':
711 variable_set('textlinkads_inlinks_last_sync_post_id', 0);
712 break;
713 }
714 }
715 else {
716 return false;
717 }
718 }
719
720 /**
721 * function textlinkads_inlinks_sync_posts()
722 * Format xml for the tla inlinks service.
723 *
724 * @return string xml of each post, formated for the tla inlinks service
725 */
726 function textlinkads_inlinks_sync_posts() {
727 $xml = '<?xml version="1.0" encoding="utf-8"?>';
728 $xml .= " <posts>\n";
729 if (is_numeric($_GET['post_id'])) {
730 $xml .= textlinkads_inlinks_prepare_node($_GET['post_id']);
731 }
732 else {
733 $last_post = variable_get('textlinkads_inlinks_last_sync_post_id', 0);
734 $results = db_query("SELECT nid FROM {node} WHERE nid > %d ORDER BY nid ASC LIMIT 100", $last_post);
735 while ($node = db_fetch_object($results)) {
736 $xml .= textlinkads_inlinks_prepare_node($node->nid);
737 }
738 }
739 $xml .= "</posts>\n";
740 return $xml;
741 }
742
743 /**
744 * function textlinkads_inlinks_prepare_node()
745 * This function should verify the node is allowed to have inlinks. If so it should
746 * update the last sync post id, and return the formated xml to send to inlinks.
747 * @param int nid the nid to prepare
748 *
749 * @return string Formatted xml for a single post
750 */
751 function textlinkads_inlinks_prepare_node($nid) {
752 $node = node_load($nid);
753 $last_post = variable_get('textlinkads_inlinks_last_sync_post_id', 0);
754
755 if($last_post < $nid) {
756 variable_set('textlinkads_inlinks_last_sync_post_id', $nid);
757 }
758 $body = urlencode(strip_tags($node->body));
759 $title = urlencode($node->title);
760 $post = " <post>\n";
761 $post .= ' <id>'. check_plain($node->nid) ."</id>\n";
762 $post .= ' <title>'. $title ."</title>\n";
763 $post .= ' <date>'. date('Y-m-d H:i:s', $node->created) ."</date>\n";
764 $post .= ' <url>'. url('node/'. $node->nid, array('absolute' => TRUE)) ."</url>\n";
765 $post .= ' <body>'. $body ."</body>\n";
766 $post .= " </post>\n";
767 return $post;
768 }
769
770 /**
771 * Function textlinkads_inlinks_notify_tla()
772 *
773 * @param string op The operation being performed. 'install' or 'add'
774 * @param int pid The id of the node being added.
775 */
776 function textlinkads_inlinks_notify_tla($op = NULL, $pid = NULL) {
777 $params = array( 'op' => $op, 'pid' => $pid);
778
779 switch ($op) {
780 case 'install':
781 $key = variable_get('textlinkads_website_xml_key', '');
782 $site_url = url('textlinkads/sync', array('absolute' => TRUE));
783 if ($key && $site_url) {
784 $url = 'http://www.text-link-ads.com/post_level_sync.php?'.
785 'action=install&inlinks=true&'.
786 'inventory_key='. $key .
787 '&site_url='.$site_url;
788 $file = file_get_contents($url);
789 if ($file) {
790 variable_set('textlinkads_inlinks_install', true);
791 }
792 }
793 $options['url'] = $url;
794 $options['key'] = $key;
795 watchdog('TextLinkAds', 'Notified Textlink ads<br /><pre>'. var_export($options, true) .'</pre>');
796 break;
797 case 'add':
798 $key = variable_get('textlinkads_website_xml_key', '');
799 if ($pid && $key) {
800 $url = 'http://www.text-link-ads.com/post_level_sync.php?'.
801 'action=add&'.
802 'inventory_key='. $key .
803 '&post_id='.$pid;
804 $file = file_get_contents($url);
805 }
806 $options['url'] = $url;
807 watchdog('TextLinkAds', 'Notified Textlink ads<br /><pre>'. var_export($options, true) .'</pre>');
808 break;
809 }
810 }
811
812 /**
813 * Function textlinkads_inlinks_set_max_post_id()
814 * Reset the textlinkads_inlinks_max_sync_post_id varialbe to the most recent nid
815 */
816 function textlinkads_inlinks_set_max_post_id() {
817 $max_nid = db_result(db_query("SELECT MAX(nid) FROM {node};"));
818 if ($max_nid) {
819 variable_set('textlinkads_inlinks_max_sync_post_id', $max_node);
820 }
821 else {
822 variable_set('textlinkads_inlinks_max_sync_post_id', 0);
823 }
824 }
825
826 function textlinkads_form_alter(&$form, $form_state, $form_id) {
827 if ($form['#id'] == 'node-form') {
828 if (user_access('administer inlinks by node')) {
829 $form['textlinkads_inlinks'] = array (
830 '#type' => 'fieldset',
831 '#access' => true,
832 '#title' => t('Text-Link-Ads Inlink'),
833 '#collapsible' => true,
834 '#collapsed' => true,
835 '#weight' => 25,
836 'textlinkads_inlinks_status' =>
837 array (
838 '#type' => 'radios',
839 '#title' => t('Allow Inlinks'),
840 '#default_value' => $form['#node']->textlinkads_inlinks,
841 '#options' => array(
842 0 => t('Default'),
843 1 => t('Allow'),
844 2 => t('Deny'),
845 )
846 ),
847 );
848 }
849 }
850 }
851
852 /**
853 * function textlinkads_inlink_allow_links()
854 * @param object node The node object
855 *
856 * @return boolean True if links are allowed, otherwise false
857 */
858 function textlinkads_inlinks_allow_links($node) {
859 $types = variable_get('textlinkads_inlinks_nodes_enabled', array());
860 if($node->textlinkads_inlinks == 2) {
861 return FALSE;
862 }
863 elseif ($types[$node->type] || $node->textlinkads_inlinks == 1) {
864 return TRUE;
865 }
866 }

  ViewVC Help
Powered by ViewVC 1.1.2