summaryrefslogtreecommitdiffstats
path: root/nodewords.module
blob: 4cf678b8d35e74d3e3faeb6bb0e2cfd9ff0a6a55 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
<?php
/**
 * @file
 * Implement an API that other modules can use to implement meta tags.
 */

/**
 * The minimum API version supported.
 */
define('NODEWORDS_MINIMUM_API_VERSION', '1.12');

/**
 * The current API version implemented.
 */
define('NODEWORDS_API_VERSION', '1.14');

/**
 * The type of objects to which the meta tags are associated.
 */
define('NODEWORDS_TYPE_BLOG',       13);
define('NODEWORDS_TYPE_DEFAULT',    1);
define('NODEWORDS_TYPE_ERRORPAGE',  2);
define('NODEWORDS_TYPE_FORUM',      12);
define('NODEWORDS_TYPE_FRONTPAGE',  3);
define('NODEWORDS_TYPE_NONE',       0);
define('NODEWORDS_TYPE_NODE',       5);
define('NODEWORDS_TYPE_OFFLINE',    11);
define('NODEWORDS_TYPE_PAGE',       10);
define('NODEWORDS_TYPE_PAGER',      4);
define('NODEWORDS_TYPE_TERM',       6);
define('NODEWORDS_TYPE_TRACKER',    7);
define('NODEWORDS_TYPE_USER',       8);
define('NODEWORDS_TYPE_VOCABULARY', 9);

/**
 * The types of meta tags the module is able to handle.
 */
define('NODEWORDS_META',          0);
define('NODEWORDS_HTTP_EQUIV',    1);
define('NODEWORDS_LINK_REL',      2);
define('NODEWORDS_LINK_REV',      3);
// This requires theme customizations, see README.txt for further details.
define('NODEWORDS_META_PROPERTY', 4);

define('NODEWORDS_GENERATION_NEVER',      0);
define('NODEWORDS_GENERATION_WHEN_EMPTY', 1);
define('NODEWORDS_GENERATION_ALWAYS',     2);

define('NODEWORDS_GENERATION_BODY',         1);
define('NODEWORDS_GENERATION_TEASER',       2);
define('NODEWORDS_GENERATION_TEASER_BODY',  3);

/**
 * Implements hook_content_extra_fields().
 * Allow the meta tags fields to be sorted in the node edit forms.
 */
function nodewords_content_extra_fields() {
  $extras = array();

  $extras['nodewords'] = array(
    'label' => t('Meta tags'),
    'description' => t('Meta tags fieldset.'),
    'weight' => 10,
  );

  return $extras;
}

/**
 * Implements hook_form_alter().
 */
function nodewords_form_alter(&$form, &$form_state, $form_id) {
  $bool = (
    isset($form['type']) &&
    isset($form['#node']) &&
    $form_id == $form['type']['#value'] . '_node_form' &&
    variable_get('nodewords_edit_metatags_' . $form['type']['#value'], TRUE)
  );

  if ($bool) {
    $node = $form['#node'];

    $form['nodewords'] = nodewords_form(
      NODEWORDS_TYPE_NODE,
      !empty($node->nodewords) ? $node->nodewords : array(),
      array(
        'tag_options' => array('node_type' => $form['type']['#value']),
      )
    );
  }
}

/**
 * Implements hook_form_FORM_ID_alter().
 */
function nodewords_form_node_type_form_alter(&$form, &$form_state) {
  if (isset($form['#node_type'])) {

    $form['nodewords'] = array(
      '#type' => 'fieldset',
      '#title' => t('Meta tags settings'),
      '#collapsible' => TRUE,
      '#collapsed' => TRUE,
      '#group' => 'additional_settings',
    );

    $form['nodewords']['nodewords_edit_metatags'] = array(
      '#type' => 'checkbox',
      '#title' => t('Allow editing of meta tags'),
      '#description' => t('If selected, the node edit form will allow the users with the right permissions to edit the meta tags associated with nodes of this content type.'),
      '#default_value' => variable_get('nodewords_edit_metatags_' . $form['#node_type']->type, TRUE),
    );

    $form['nodewords']['metatags_generation'] = array(
      '#type' => 'fieldset',
      '#title' => t('Node meta tags generation options'),
      '#description' => t('These options change how a meta tag content is generated from the node content. These settings apply to specific meta tags.'),
      '#collapsible' => TRUE,
    );

    $options = array(
      NODEWORDS_GENERATION_NEVER => t('Do not generate meta tags content'),
      NODEWORDS_GENERATION_WHEN_EMPTY => t('Generate meta tag content when the meta tag content is empty (default)'),
      NODEWORDS_GENERATION_ALWAYS => t('Always generate the meta tag content'),
    );

    $form['nodewords']['metatags_generation']['nodewords_metatags_generation_method'] = array(
      '#type' => 'radios',
      '#options' => $options,
      '#default_value' => variable_get(
        'nodewords_metatags_generation_method_' . $form['#node_type']->type,
        NODEWORDS_GENERATION_WHEN_EMPTY
      ),
    );

    $options = array(
      NODEWORDS_GENERATION_BODY => t('Generate meta tags content from the node body'),
      NODEWORDS_GENERATION_TEASER => t('Generate meta tags content from the node teaser (default)'),
      NODEWORDS_GENERATION_TEASER_BODY => t('Generate meta tags content from the node teaser, or the node body when the node teaser is empty'),
    );

    $form['nodewords']['metatags_generation']['nodewords_metatags_generation_source'] = array(
      '#type' => 'radios',
      '#title' => t('Generation source'),
      '#options' => $options,
      '#default_value' => variable_get(
        'nodewords_metatags_generation_source_' . $form['#node_type']->type,
        NODEWORDS_GENERATION_TEASER
      ),
    );

    $form['nodewords']['metatags_generation']['nodewords_use_alt_attribute'] = array(
      '#type' => 'checkbox',
      '#title' => t('Replace the tag IMG content with the attribute ALT'),
      '#default_value' => variable_get(
        'nodewords_use_alt_attribute_' . $form['#node_type']->type,
        TRUE
      ),
    );

    $options = array(
      'imagebrowser' => 'imagebrowser.module',
      'img_assist' => 'img_assist.module',
    );

    $form['nodewords']['metatags_generation']['nodewords_filter_modules_output'] = array(
      '#type' => 'checkboxes',
      '#title' => t('Filter the text added by third-party modules in the node teaser'),
      '#options' => $options,
      '#default_value' => variable_get(
        'nodewords_filter_modules_output_' . $form['#node_type']->type,
        array()
      ),
      '#checkall' => TRUE,
    );

    $form['nodewords']['metatags_generation']['nodewords_filter_regexp'] = array(
      '#type' => 'textfield',
      '#title' => t('Custom regular expression'),
      '#description' => t('A regular expression used to filter the text added in the node teaser from a third-party module. The regular expression uses the <a href="http://www.php.net/manual/en/pcre.pattern.php">Perl compatible</a> syntax. Slashes are assumed as delimiters and all expressions are case-sensitive.'),
      '#element_validate' => array('nodewords_filter_regex_validate'),
      '#default_value' => variable_get(
        'nodewords_filter_regexp_' . $form['#node_type']->type, ''
      ),
      '#field_prefix' => '/',
      '#field_suffix' => '/',
      '#size' => 60,
    );

    foreach (nodewords_get_possible_tags() as $name => $info) {
      $function = $info['callback'] . '_settings_form';
      $options = array();

      if (function_exists($function)) {
        $function($form, 'node_type_form', $options);
      }
    }
  }
}

/**
 * Implements hook_form_FORM_ID_alter().
 */
function nodewords_form_taxonomy_form_term_alter(&$form, &$form_state) {
  $bool = (isset($form['tid']['#value']) &&
    !isset($form_state['confirm_delete']) &&
    !isset($form_state['confirm_parents'])
  );

  if ($bool) {
    $id = $form['tid']['#value'];

    if (!empty($form_state['values']['nodewords'])) {
      $tags = $form_state['values']['nodewords'];
    }
    elseif (isset($id) && is_numeric($id)) {
      $tags = nodewords_load_tags(NODEWORDS_TYPE_TERM, $id);
    }
    else {
      $tags = array();
    }

    $form['nodewords'] = nodewords_form(
      NODEWORDS_TYPE_TERM,
      $tags
    );

    // Ensure the submit & delete buttons are at the bottom. Hopefully.
    $form['submit']['#weight'] = 1000;
    $form['delete']['#weight'] = 1001;
  }
}

/**
 * Implements hook_form_FORM_ID_alter().
 */
function nodewords_form_taxonomy_form_vocabulary_alter(&$form, &$form_state) {
  if (isset($form['vid']['#value'])) {
    $id = $form['vid']['#value'];

    if (!empty($form_state['values']['nodewords'])) {
      $tags = $form_state['values']['nodewords'];
    }
    elseif (isset($id) && is_numeric($id)) {
      $tags = nodewords_load_tags(NODEWORDS_TYPE_VOCABULARY, $id);
    }
    else {
      $tags = array();
    }

    $form['nodewords'] = nodewords_form(
      NODEWORDS_TYPE_VOCABULARY,
      $tags
    );

    // Ensure the submit & delete buttons are at the bottom. Hopefully.
    $form['submit']['#weight'] = 1000;
    $form['delete']['#weight'] = 1001;
  }
}

/**
 *  Implemenation of hook_help().
 */
function nodewords_help($path, $arg) {
  switch ($path) {
    case 'admin/content/nodewords/meta-tags':
      $output = '<p>' . t('On this page you can enter the default values for the meta tags of your site.') . '</p>';
      break;

    case 'admin/content/nodewords/meta-tags/errorpage_403':
      $output = '<p>' . t('On this page you can enter the meta tags for the <q>access denied</q> error page of your site.') . '</p>';
      break;

    case 'admin/content/nodewords/meta-tags/errorpage_404':
      $output = '<p>' . t('On this page you can enter the meta tags for the <q>page not found</q> error page of your site.') . '</p>';
      break;

    case 'admin/content/nodewords/meta-tags/frontpage':
      $output = '<p>' . t('On this page you can enter the meta tags for the front page of your site.') . '</p>';
      break;

    case 'admin/content/nodewords/meta-tags/custom':
      $output = '<p>' . t('On this page you can enter the meta tags for other pages of your site. The meta tags set in these page are used before the ones set for nodes or user profiles, and they can ovverride those meta tags.') . '</p>';
      break;

    default:
      $output = '';
      break;
  }

  return $output;
}

/**
 * Implements hook_menu().
 */
function nodewords_menu() {
  $admin_access = array('administer meta tags');
  $items = array();

  $items['admin/content/nodewords'] = array(
    'title' => 'Meta tags',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('nodewords_settings_form'),
    'description' => 'Configure HTML meta tags for all the content.',
    'access arguments' => $admin_access,
    'type' => MENU_NORMAL_ITEM,
    'file' => 'nodewords.admin.inc',
  );

  $items['admin/content/nodewords/settings'] = array(
    'title' => 'Settings',
    'access arguments' => $admin_access,
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => -10,
    'file' => 'nodewords.admin.inc',
  );

  $items['admin/content/nodewords/meta-tags'] = array(
    'title' => 'Default and specific meta tags',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('nodewords_tags_form'),
    'access arguments' => $admin_access,
    'type' => MENU_LOCAL_TASK,
    'file' => 'nodewords.admin.inc',
    'weight' => -9,
  );

  $items['admin/content/nodewords/meta-tags/default'] = array(
    'title' => 'Default values',
    'access arguments' => $admin_access,
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'file' => 'nodewords.admin.inc',
    'weight' => -10,
  );

  $items['admin/content/nodewords/meta-tags/frontpage'] = array(
    'title' => 'Front page',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('nodewords_tags_form', (string) NODEWORDS_TYPE_FRONTPAGE),
    'access arguments' => $admin_access,
    'type' => MENU_LOCAL_TASK,
    'file' => 'nodewords.admin.inc',
    'weight' => -9,
  );

  $items['admin/content/nodewords/meta-tags/offline'] = array(
    'title' => 'Site off-line page',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('nodewords_tags_form', (string) NODEWORDS_TYPE_OFFLINE),
    'access arguments' => $admin_access,
    'type' => MENU_LOCAL_TASK,
    'file' => 'nodewords.admin.inc',
    'weight' => -8,
  );

  $items['admin/content/nodewords/meta-tags/errorpage_403'] = array(
    'title' => 'Error 403 page',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('nodewords_tags_form', (string) NODEWORDS_TYPE_ERRORPAGE, '403'),
    'access arguments' => $admin_access,
    'type' => MENU_LOCAL_TASK,
    'file' => 'nodewords.admin.inc',
    'weight' => -7,
  );

  $items['admin/content/nodewords/meta-tags/errorpage_404'] = array(
    'title' => 'Error 404 page',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('nodewords_tags_form', (string) NODEWORDS_TYPE_ERRORPAGE, '404'),
    'access arguments' => $admin_access,
    'type' => MENU_LOCAL_TASK,
    'file' => 'nodewords.admin.inc',
    'weight' => -6,
  );

  // Only show the forum settings page if the core Blog module is enabled.
  if (module_exists('blog')) {
    $items['admin/content/nodewords/meta-tags/blog'] = array(
      'title' => 'Blog main page',
      'page callback' => 'drupal_get_form',
      'page arguments' => array('nodewords_tags_form', (string) NODEWORDS_TYPE_BLOG),
      'access arguments' => $admin_access,
      'type' => MENU_LOCAL_TASK,
      'file' => 'nodewords.admin.inc',
      'weight' => -5,
    );
  }

  // Only show the forum settings page if the core Forum module is enabled.
  if (module_exists('forum')) {
    $items['admin/content/nodewords/meta-tags/forum'] = array(
      'title' => 'Forum main page',
      'page callback' => 'drupal_get_form',
      'page arguments' => array('nodewords_tags_form', (string) NODEWORDS_TYPE_FORUM),
      'access arguments' => $admin_access,
      'type' => MENU_LOCAL_TASK,
      'file' => 'nodewords.admin.inc',
      'weight' => -4,
    );
  }

  $items['admin/content/nodewords/meta-tags/custom'] = array(
    'title' => 'Custom pages',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('nodewords_custom_pages_overview'),
    'access arguments' => $admin_access,
    'type' => MENU_LOCAL_TASK,
    'weight' => 20,
    'file' => 'nodewords.admin.inc',
  );

  $items['admin/content/nodewords/meta-tags/custom/add'] = array(
    'title' => 'Add custom pages meta tags',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('nodewords_custom_pages_edit'),
    'access arguments' => $admin_access,
    'type' => MENU_CALLBACK,
    'file' => 'nodewords.admin.inc',
  );

  $items['admin/content/nodewords/meta-tags/custom/%nodewords_page/delete'] = array(
    'title' => 'Delete custom pages meta tags',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('nodewords_custom_pages_confirm_delete', 5),
    'access arguments' => $admin_access,
    'parent' => 'admin/content/nodewords/meta-tags/custom',
    'type' => MENU_CALLBACK,
    'file' => 'nodewords.admin.inc',
  );

  $items['admin/content/nodewords/meta-tags/custom/%nodewords_page/edit'] = array(
    'title' => 'Edit custom pages meta tags',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('nodewords_custom_pages_edit', 5),
    'access arguments' => $admin_access,
    'parent' => 'admin/content/nodewords/meta-tags/custom',
    'type' => MENU_CALLBACK,
    'file' => 'nodewords.admin.inc',
  );

  return $items;
}

/**
 * Implements hook_node_operations().
 */
function nodewords_node_operations() {
  $operations = array(
    'delete_metatags' => array(
      'label' => t('Delete meta tags'),
      'callback' => 'nodewords_mass_update',
      'callback arguments' => array('type' => NODEWORDS_TYPE_NODE, 'operation' => 'delete'),
    ),
  );

  return $operations;
}

/**
 * Implements hook_node_type().
 */
function nodewords_node_type($op, $info) {
  if ($op == 'delete') {
    $variables = array(
      'nodewords_metatags_generation_method_',
      'nodewords_metatags_generation_source_',
      'nodewords_edit_metatags_',
      'nodewords_filter_modules_output_',
      'nodewords_filter_regexp_',
      'nodewords_use_alt_attr_',
      'nodewords_use_teaser_',
    );

    foreach ($variables as $variable) {
      variable_del($variable . $info->type);
    }
  }
}

/**
 * Implements hook_nodeapi().
 */
function nodewords_nodeapi(&$node, $op, $teaser = NULL, $page = NULL) {
  switch ($op) {
    case 'delete':
      nodewords_delete_tags(NODEWORDS_TYPE_NODE, $node->nid);
      break;

    case 'insert':
    case 'update':
      if (isset($node->nodewords)) {
        nodewords_save_tags(NODEWORDS_TYPE_NODE, $node->nid, $node->nodewords, TRUE);
      }
      break;

    case 'load':
      return array(
        'nodewords' => nodewords_load_tags(NODEWORDS_TYPE_NODE, $node->nid),
      );

    case 'prepare translation':
      if (isset($node->translation_source->nodewords)) {
        $node->nodewords = $node->translation_source->nodewords;
      }
      break;

    case 'update index':
      $output_tags = array();
      $tag_options = array(
        'type' => NODEWORDS_TYPE_NODE,
        'id' => $node->nid,
        'output' => 'update index',
      );

      if (isset($node->nodewords)) {
        // Prepare the tags.
        foreach (nodewords_get_possible_tags() as $name => $info) {
          $bool = (
            !empty($info['templates']['search index']) &&
            function_exists($function = $info['callback'] . '_prepare')
          );

          if ($bool) {
            $function(
              $output_tags,
              isset($node->nodewords[$name]) ? $node->nodewords[$name] : array(),
              $tag_options
            );
          }
        }

        drupal_alter('nodewords_tags', $output_tags, $tag_options);
        $output = _nodewords_output_tags($output_tags, 'update index');
        drupal_alter('nodewords_tags_output', $output, $tag_options);

        return $output;
      }

      return '';
  }
}

/**
 * Implements hook_perm().
 */
function nodewords_perm() {
  return array('administer meta tags');
}

/**
 * Implements hook_preprocess_page().
 */
function nodewords_preprocess_page(&$variables) {
   // Do not do anything when running in install or update mode.
   if (defined('MAINTENANCE_MODE')) {
     return;
   }
 
  $options = _nodewords_detect_type_and_id();
  $output_tags = array();

  $options += array(
    'default' => nodewords_load_tags(),
    'output' => 'head',
  );

  if ($options['type'] == NODEWORDS_TYPE_PAGER) {
    foreach (nodewords_get_possible_tags() as $name => $info) {
      $bool = (
        !empty($info['context']['allowed']) &&
        in_array(NODEWORDS_TYPE_PAGER, $info['context']['allowed']) &&
        function_exists($function = $info['callback'] . '_prepare')
      );

      if ($bool) {
        $function($output_tags, array(), $options);
      }
    }
  }
  else {
    // User profiles meta tags are not enabled.
    if ($options['type'] == NODEWORDS_TYPE_USER && !variable_get('nodewords_enable_user_metatags', TRUE)) {
      return;
    }
    // If the visitor doesn't have access to this node, don't load anything.
    elseif ($options['type'] == NODEWORDS_TYPE_NODE && !node_access('view', node_load($options['id']))) {
      $tags = array();
    }
    // Otherwise, load the tags for this page.
    else {
      $tags = nodewords_load_tags($options['type'], $options['id']);
    }

    // Prepare the tags.
    foreach (nodewords_get_possible_tags() as $name => $info) {
      if (function_exists($function = $info['callback'] . '_prepare')) {
        $function($output_tags, isset($tags[$name]) ? $tags[$name] : array(), $options);
      }
    }
  }

  drupal_alter('nodewords_tags', $output_tags, $options);

  // Title tag has its own page preprocess variable and must be handled
  // separately.
  if (isset($output_tags['page_title'])) {
    if (!empty($output_tags['page_title'])) {
      drupal_set_title($output_tags['page_title']);
      $variables['head_title'] = strip_tags(drupal_get_title());
    }
    unset($output_tags['page_title']);
  }

  $output = _nodewords_output_tags($output_tags);
  drupal_alter('nodewords_tags_output', $output, $options);

  // Output the tags to the header.
  drupal_set_html_head($output);
  $variables['head'] = drupal_get_html_head();
}

/**
 * Implements hook_preprocess_maintenance_page().
 */
function nodewords_preprocess_maintenance_page(&$variables) {
  nodewords_preprocess_page($variables);
}

/**
 * Implements hook_taxonomy().
 */
function nodewords_taxonomy($op, $type, $array = NULL) {
  if (isset($array)) {
    if ($type == 'term') {
      $type = NODEWORDS_TYPE_TERM;
      $id = $array['tid'];
    }
    elseif ($type == 'vocabulary') {
      $type = NODEWORDS_TYPE_VOCABULARY;
      $id = $array['vid'];
    }
    else {
      return;
    }

    switch ($op) {
      case 'delete':
        nodewords_delete_tags($type, $id);
        break;

      case 'insert':
      case 'update':
        if (isset($array['nodewords'])) {
          nodewords_save_tags($type, $id, $array['nodewords'], TRUE);
        }
        break;
    }
  }
}

/**
 * Implements hook_theme().
 */
function nodewords_theme() {
  return array(
    'nodewords_custom_pages_overview' => array(
      'arguments' => array('form' => array()),
      'file' => 'nodewords.admin.inc',
    ),
  );
}

/**
 * Implements hook_user().
 */
function nodewords_user($op, &$edit, &$account, $category = NULL) {
  global $user;

  switch ($op) {
    case 'load':
      if (arg(0) == 'user' && !empty($account->uid) && variable_get('nodewords_enable_user_metatags', TRUE)) {
        $account->nodewords = nodewords_load_tags(NODEWORDS_TYPE_USER, $account->uid);
      }
      break;

    case 'delete':
      nodewords_delete_tags(NODEWORDS_TYPE_USER, $account->uid);
      break;

    case 'insert':
    case 'update':
      if (isset($edit['nodewords'])) {
        nodewords_save_tags(NODEWORDS_TYPE_USER, $account->uid, $edit['nodewords'], TRUE);
      }

      $edit['nodewords'] = NULL;
      break;

    case 'form':
      $bool = (
        (
          user_access('administer meta tags') ||
          $user->uid == $account->uid
        ) && variable_get('nodewords_enable_user_metatags', TRUE) &&
        $category == 'account'
      );

      if ($bool) {
        $tags = nodewords_load_tags(NODEWORDS_TYPE_USER, $account->uid);
        $form['nodewords'] = nodewords_form(
          NODEWORDS_TYPE_USER,
          $tags
        );

        return $form;
      }
      return array();
  }
}

/**
 * Implements hook_user_operations().
 */
function nodewords_user_operations() {
  $operations = array(
    'delete_metatags' => array(
      'label' => t('Delete meta tags'),
      'callback' => 'nodewords_mass_update',
      'callback arguments' => array('type' => NODEWORDS_TYPE_USER, 'operation' => 'delete'),
    ),
  );

  return $operations;
}

/**
 * Delete tags from table.
 */
function nodewords_delete_tags($type, $id) {
  db_query("DELETE FROM {nodewords} WHERE type = %d AND id = %d", $type, $id);

  if ($type == NODEWORDS_TYPE_PAGE) {
    db_query("DELETE FROM {nodewords_custom} WHERE pid = %d", $id);
  }
}

/**
 * Return the form used to set the meta tags values.
 *
 * @param $type
 *   The object to which the meta tags are associated (node, user, taxonomy
 *   term, etc...).
 * @param $tags
 *   The meta tags array as returned by nodewords_load_tags().
 *
 * @return
 *   An array as requested by the form API.
 */
function nodewords_form($type, $tags, $options = array()) {
  $default_options = array(
    'fieldset' => TRUE,
    'fieldset:title' => t('Meta tags'),
    'fieldset:weight' => 20,
  );
  $default_tag_options = array(
    'default' => nodewords_load_tags(),
    'type' => $type,
  );
  $edit_tags = variable_get('nodewords_edit', array());
  $form = array();
  $options += $default_options;

  if (isset($options['tag_options']) && is_array($options['tag_options'])) {
    $tag_options = $options['tag_options'] + $default_tag_options;
  }
  else {
    $tag_options = $default_tag_options;
  }

  $tags_info = nodewords_get_possible_tags();

  foreach ($tags_info as $name => $info) {
    $bool = (
      (
        user_access('administer meta tags')
      ) ||
      !empty($edit_tags[$name])
    );

    if ($bool) {
      $bool = (
        (
          !empty($info['context']['allowed']) &&
          is_array($info['context']['allowed']) &&
          !in_array($type, $info['context']['allowed'])
        ) ||
        (
          !empty($info['context']['denied']) &&
          is_array($info['context']['denied']) &&
          in_array($type, $info['context']['denied'])
        )
      );

      if ($bool) {
        continue;
      }

      $bool = (
        (
          user_access('administer meta tags')
        ) ||
        (
          !empty($info['permission']) &&
          user_access($info['permission'])
        )
      );

      if ($bool) {
        if (function_exists($function = $info['callback'] . '_form')) {
          $function($form, isset($tags[$name]) ? $tags[$name] : array(), $tag_options);
        }
      }
    }
  }

  if (!empty($form) && $options['fieldset']) {
    $form['#type'] = 'fieldset';
    $form['#title'] = $options['fieldset:title'];
    $form['#tree'] = TRUE;
    $form['#collapsible'] = TRUE;
    $form['#collapsed'] = TRUE;
    $form['#weight'] = $options['fieldset:weight'];
    $form['#group'] = 'additional_settings';
  }

  return $form;
}

/**
 * Query all the modules implementing meta tags and return the list of meta tags.
 *
 * @param $load
 *   If TRUE, the file containing the code implementing the meta tags will be loaded.
 *
 * @return
 *   An array containing the list of meta tags definitions.
 */
function nodewords_get_possible_tags($load = FALSE) {
  static $tags_info = array();

  if ($load) {
    $tags_info = array();
  }

  if (empty($tags_info)) {
    // Allow third-party modules to alter the  meta tags list, or to add new
    // meta tags.
    foreach (module_implements('nodewords_tags_info') as $module) {
      if (module_hook($module, 'nodewords_api')) {
        $info = module_invoke($module, 'nodewords_api');
        $version = '0.0';

        if (isset($info)) {
          if (is_string($info)) {
            $version = $info;
          }
          elseif (is_array($info) && isset($info['version'])) {
            $version = $info['version'];

            if ($load && !empty($info['file'])) {
              $include_file = $info['file'];

              if (isset($info['path'])) {
                $include_file = $info['path'] . '/' . $include_file;
              }

              include_once $include_file;
            }
          }
        }

        $bool = (
          version_compare($version, NODEWORDS_MINIMUM_API_VERSION, '<') ||
          version_compare($version, NODEWORDS_API_VERSION, '>')
        );

        if ($bool) {
          continue;
        }

        $result = module_invoke($module, 'nodewords_tags_info');

        if (isset($result) && is_array($result)) {
          $tags_info = array_merge($tags_info, $result);
        }
      }
    }
  }

  return $tags_info;
}

/**
 * Return the term object matching a term ID. This is a modified version of
 * taxonomy_get_term() which uses db_rewrite_sql().
 *
 * @param $tid
 *   A term's ID.
 * @param $uid
 *  The user ID; if not passed, the function will use the global user ID.
 *
 * @return
 *   A term object, or FALSE. Results are statically cached.
 */
function nodewords_get_term($tid, $uid = NULL) {
  global $user;
  static $terms = array();

  if (!isset($uid)) {
    $uid = $user->uid;
  }

  if (!isset($terms[$uid][$tid])) {
    $terms[$uid][$tid] = db_fetch_object(
      db_query(
        db_rewrite_sql('SELECT * FROM {term_data} t WHERE t.tid = %d', 't', 'tid'),
        $tid
      )
    );
  }

  return !empty($terms[$uid][$tid]) ? $terms[$uid][$tid] : FALSE;
}

/**
 * Load tags from table.
 */
function nodewords_load_tags($type = NODEWORDS_TYPE_DEFAULT, $id = 0) {
  static $queries = array();

  // If the metatags haven't been loaded before, load them.
  if (!isset($queries[$type][$id])) {
    $result = db_query("SELECT * FROM {nodewords} WHERE type = %d AND id = %d", $type, $id);
    $tags = array();
    $tags_info = nodewords_get_possible_tags();

    while ($row = db_fetch_object($result)) {
      if (isset($tags_info[$row->name])) {
        $tags[$row->name] = unserialize($row->content);
      }
    }

    // If no metatags are found for this term, try loading the vocabulary's.
    if (empty($tags) && $type == NODEWORDS_TYPE_TERM) {
      $tags = nodewords_load_tags(NODEWORDS_TYPE_VOCABULARY, db_result(db_query('SELECT vid FROM {term_data} WHERE tid = %d', $id)));
    }

    // Cache the metatags for later.
    $queries[$type][$id] = $tags;
  }

  return $queries[$type][$id];
}


/**
 * Delete the nodes meta tags.
 *
 * @param $ids
 *  An array of IDs.
 * @param $type
 *  The type of the object associated with the IDs (NODEWORDS_TYPE_NODE, NODEWORDS_TYPE_USER,
 *  NODEWORDS_TYPE_PAGER, NODEWORDS_TYPE_PAGE, ...).
 * @param $operation
 *  The operation to execute (currently implemented: delete).
 */
function nodewords_mass_update($ids, $type, $operation = 'delete') {
  if ($operation == 'delete') {
    if (($count = count($ids))) {
      if ($count <= 10) {
        db_query("DELETE FROM {nodewords} WHERE id IN (" . db_placeholders($ids, 'int') . ") AND type = %d",
          array_merge($ids, array($type))
        );

        if ($type == NODEWORDS_TYPE_PAGE) {
          db_query("DELETE FROM {nodewords_custom} WHERE pid IN (" . db_placeholders($ids, 'int') . ")", $ids);
        }

        drupal_set_message(t('The update has been performed.'));
      }
      else {
        $batch = array(
          'operations' => array(
            array('_nodewords_mass_delete_batch_process', array($ids, $type))
          ),
          'finished' => '_nodewords_mass_update_batch_finished',
          'title' => t('Processing'),
          'progress_message' => '',
          'error_message' => t('The update has encountered an error.'),
          'file' => drupal_get_path('module', 'nodewords') .'/nodewords.admin.inc',
        );
        batch_set($batch);
      }
    }
  }
}

/**
 * Create the content of a meta tag from a node teaser.
 *
 * @param $node
 *   The node object the meta tag refers to.
 * @param $content
 *   The meta tag content.
 * @param $options
 *  An array of options; currently, the only option used is the maximum allowed
 *  length.
 *
 * @return
 *   The string used as meta tag content.
 */
function nodewords_metatag_from_node_content($node, $content, $options = array()) {
  // The method used to generate the summary string.
  $method = variable_get('nodewords_metatags_generation_method_' . $node->type, NODEWORDS_GENERATION_WHEN_EMPTY);

  // If not generating an automatic description, return immediately.
  if ($method == NODEWORDS_GENERATION_NEVER
    || ($method == NODEWORDS_GENERATION_WHEN_EMPTY && !empty($content))) {
    return $content;
  }

  // Proceed as normal.
  $result = '';
  $source = variable_get('nodewords_metatags_generation_source_' . $node->type, NODEWORDS_GENERATION_TEASER);

  // If generating an automatic description, determine the source.
  if (!empty($node->teaser) && ($source == NODEWORDS_GENERATION_TEASER || $source == NODEWORDS_GENERATION_TEASER_BODY)) {
    $result = $node->teaser;
  }
  elseif (!empty($node->body) && ($source == NODEWORDS_GENERATION_BODY || ($source == NODEWORDS_GENERATION_TEASER_BODY && empty($node->teaser)))) {
    $result = $node->body;
  }

  // Clean up the text by running it through applicable filters.
  if (!empty($result)) {
    // Check for the presence of the PHP evaluator filter in the current format.
    // If the text contains PHP code, do not split it up to prevent parse errors.
    $filters = filter_list_format($node->format);
    if (isset($filters['php/0']) && strpos($result, '<?') !== FALSE) {
      $result = '';
    }

    // Continue as normal.
    else {
      // Run all of the normal text filters on the summary text.
      $result = check_markup($result, $node->format, FALSE);

      // Ensure there's a setting for controlling the maximum summary length.
      if (!isset($options['size'])) {
        $options['size'] = variable_get('nodewords_max_size', 350);
      }

      // Optionally replace the tag IMG with its ALT attribute.
      if (variable_get('nodewords_use_alt_attribute', FALSE)) {
        $result = preg_replace("/<img\s[^>]*alt=[\"']([^\"']*)[\"'][^>]*>/i", ' ($1) ', $result);
      }

      // Strip off all the HTML tags.
      $result = strip_tags($result);

      // Remove the strings added from third-party modules.
      $modules = array_filter(variable_get('nodewords_filter_modules_output_' . $node->type, array()));
      $regexps = array(
        'imagebrowser' => '/\[ibimage[^\]]*\]/i',
        'img_assist' => '/\[img_assist[^\]]*\]/i',
      );
      foreach ($regexps as $module => $regexp) {
        if (isset($modules[$module])) {
          $result = preg_replace($regexp, '', $result);
        }
      }

      // Remove the text matching the type-specific regular expression.
      if ($regexp = trim(variable_get('nodewords_filter_regexp_' . $node->type, ''))) {
        $result = preg_replace('/' . $regexp . '/', '', $result);
      }

      // Remove line breaks.
      $result = preg_replace('/(\r\n?|\n)/', ' ', $result);

      // Remove any leading & trailing whitespace.
      $result = trim($result);

      // Remove excess inline whitespace.
      $result = preg_replace('/\s\s+/', ' ', $result);

      // Trim the filtered text to the maximum length allowed.
      $result = node_teaser($result, $node->format, $options['size']);
    }
  }

  return $result;
}

/**
 * This function is used from the menu system when a menu callback path contains
 * %nodewords_page_load.
 */
function nodewords_page_load($pid) {
  return _nodewords_get_custom_pages_data($pid);
}

/**
 * Update or insert tags in the table.
 */
function nodewords_save_tags($type, $id, $tags, $log_message = FALSE) {
  global $user;

  $done = FALSE;
  $tags_info = nodewords_get_possible_tags();
  $types_str = array(
    NODEWORDS_TYPE_BLOG => t('blog main page'),
    NODEWORDS_TYPE_DEFAULT => t('default'),
    NODEWORDS_TYPE_ERRORPAGE => t('HTTP error page'),
    NODEWORDS_TYPE_FORUM => t('forum main page'),
    NODEWORDS_TYPE_FRONTPAGE => t('front page'),
    NODEWORDS_TYPE_NODE => t('node'),
    NODEWORDS_TYPE_OFFLINE => t('site offline page'),
    NODEWORDS_TYPE_PAGE => t('custom page'),
    NODEWORDS_TYPE_PAGER => t('list page'),
    NODEWORDS_TYPE_TERM => t('taxonomy term'),
    NODEWORDS_TYPE_USER => t('user profile'),
    NODEWORDS_TYPE_VOCABULARY => t('vocabulary'),
  );

  foreach ($tags as $name => $content) {
    if (isset($tags_info[$name])) {
      $content = serialize($content);
      $result = db_fetch_object(
        db_query_range(
          "SELECT * FROM {nodewords} WHERE type = %d AND id = %d AND name = '%s'",
          $type, $id, $name, 0, 1
        )
      );

      if ($result === FALSE) {
        $row = new stdClass();
        $row->type = $type;
        $row->id = $id;
        $row->name = $name;
      }
      else {
        $row = $result;
      }

      $row->content = $content;

      drupal_write_record('nodewords', $row, $result !== FALSE ? 'mtid' : array());

      if (!$done) {
        watchdog('nodewords', 'User %name changed the meta tags for type %type (ID %id).', array('%name' => $user->name, '%type' => isset($types_str[$type]) ? $types_str[$type] : t('unknown'), '%id' => $id));
        $done = TRUE;
      }
    }
  }

  // Reload the tags so that future API calls get the correct data.
  nodewords_load_tags($type, $id);
}

/**
 * Remove the duplicates from a list of items separated from the separator,
 * preserving the order in which they appear.
 * @param $text
 *   The string containing the list of items concatenated using $separator.
 * @param $separator
 *   The string used to split the string into an array. A space will be appended
 *   to the string before it is used to create the string from the array of
 *   unique items found in the string passed as argument.
 * @param $max_items
 *   The maximum number of items accepted in the returned array; the default
 *   value is -1, which means no limit.
 *
 * @return
 *   A string containing only unique items present in the string of concatenated
 *   items.
 */
function nodewords_unique_values($text, $separator = ',', $max_items = -1) {
  $lc_values = array();
  $unique_values = array();

  if (empty($text)) {
    return '';
  }

  foreach (array_filter(array_map('trim', explode($separator, $text))) as $item) {
    $lowercase = drupal_strtolower($item);

    if (!in_array($lowercase, $lc_values)) {
      $lc_values[] = $lowercase;
      $unique_values[] = $item;
    }
  }

  if ($max_items > 0) {
    $unique_values = array_slice($unique_values, 0, $max_items);
  }

  return implode("$separator", $unique_values);
}

/**
 * Return the absolute URL of a path.
 *
 * Return the absolute URL of a path built using the base URL saved in the
 * Drupal variable nodewords_base_url.
 *
 * @param $path
 *  The path for which the absolute must be built.
 * @param $options
 *  An array of options as used by url().
 */
function nodewords_url($path, $options = array()) {
  // Remove the trailing slash, it will be added in the url() function.
  $base_url = rtrim(variable_get('nodewords_base_url', ''), '/');

  $options += array(
    'alias' => TRUE,
    'absolute' => TRUE,
    'fragment' => '',
    'query' => '',
    'prefix' => ''
  );

  // Identify if the URL alias should be used.
  if (variable_get('nodewords_use_path_alias', TRUE)) {
    // Note: the url() function's 'alias' argument is to specify that the
    // path is *already* an alias, it is not for requesting an alias be loaded.
    $options['alias'] = FALSE;
  }

  $options['base_url'] = empty($base_url) ? NULL : $base_url;

  return url($path, $options);
}

/**
 * Implementation of hook_migrate_api().
 */
function nodewords_migrate_api() {
  return array(
    'api' => 1,
    'integration modules' => array(
      'nodewords' => array('status' => FALSE),
    ),
  );
}


/**
 * Internal functions
 */


/**
 * Try to guess the $type and $id by looking at $_GET['q'].
 */
function _nodewords_detect_type_and_id() {
  $arg = arg();
  $default = array('type' => NODEWORDS_TYPE_PAGE, 'id' => 0);

  // Do not do anything when running in install or update mode.
  if (defined('MAINTENANCE_MODE')) {
    return array('type' => NODEWORDS_TYPE_NONE);
  }

  if (variable_get('site_offline', 0) && !user_access('administer site configuration')) {
    // User will see the site-offline page.
    return array('type' => NODEWORDS_TYPE_OFFLINE, 'id' => 0);
  }

  $headers = drupal_get_headers();

  if (preg_match('@HTTP/1\.[01]\x20+403@', $headers)) {
    return array('type' => NODEWORDS_TYPE_ERRORPAGE, 'id' => 403);
  }

  if (preg_match('@HTTP/1\.[01]\x20+404@', $headers)) {
    return array('type' => NODEWORDS_TYPE_ERRORPAGE, 'id' => 404);
  }

  $bool = (
    !variable_get('nodewords_list_repeat', FALSE) &&
    isset($_REQUEST['page']) &&
    intval($_REQUEST['page']) > 0
  );

  if ($bool) {
    return array('type' => NODEWORDS_TYPE_PAGER, 'id' => 0);
  }

  if (drupal_is_front_page() && variable_get('nodewords_use_frontpage_tags', TRUE)) {
    return array('type' => NODEWORDS_TYPE_FRONTPAGE, 'id' => 0);
  }

  if (module_exists('blog') && $_GET['q'] == 'blog') {
    return array('type' => NODEWORDS_TYPE_BLOG, 'id' => 0);
  }

  if (module_exists('forum') && $_GET['q'] == 'forum') {
    return array('type' => NODEWORDS_TYPE_FORUM, 'id' => 0);
  }

  // Check all of the custom page paths.
  foreach (_nodewords_get_pages_paths() as $pid => $path) {
    // The path is a system path.
    if (drupal_match_path($_GET['q'], $path)) {
      return array('type' => NODEWORDS_TYPE_PAGE, 'id' => $pid);
    }

    // The path is a URL alias.
    $alias = drupal_get_path_alias($_GET['q']);
    if ($alias != $_GET['q'] && drupal_match_path($alias, $path)) {
      return array('type' => NODEWORDS_TYPE_PAGE, 'id' => $pid);
    }
  }

  if (!isset($arg[0])) {
    return $default;
  }

  _nodewords_load_all_includes();

  $result = array(
    'type' => NODEWORDS_TYPE_NONE,
    'id' => 0,
  );

  foreach (module_implements('nodewords_type_id') as $module) {
    $function = $module . '_nodewords_type_id';
    $function($result, $arg);

    if ($result['type'] !=  NODEWORDS_TYPE_NONE) {
      return $result;
    }
  }

  return $default;
}

/**
 * Load the page meta tags data from the cache.
 *
 * @param $id
 *   The ID of the page to load; by default the function loads all the custom
 *   pages data.
 */
function _nodewords_get_custom_pages_data($id = NULL) {
  static $pages;

  if (!isset($pages)) {
    $pages = array();
    $result = db_query("SELECT * FROM {nodewords_custom} ORDER BY weight ASC");

    while ($page = db_fetch_object($result)) {
      $page->tags = nodewords_load_tags(NODEWORDS_TYPE_PAGE, $page->pid);
      $pages[$page->pid] = $page;
    }
  }

  return isset($id) ? (isset($pages[$id]) ? $pages[$id] : FALSE) : $pages;
}

/**
 * Answer a listing of page paths, stored in a static cache.
 */
function _nodewords_get_pages_paths() {
  static $paths;

  if (!isset($paths)) {
    $paths = array();
    $result = db_query("SELECT pid, path FROM {nodewords_custom} ORDER BY weight ASC");

    while ($page = db_fetch_object($result)) {
      $paths[$page->pid] = $page->path;
    }
  }

  return $paths;
}

/**
 * Load the files in the directory "includes" basing on the enabled modules.
 */
function _nodewords_load_all_includes() {
  $dir = drupal_get_path('module', 'nodewords') . '/includes';

  // Update this array when new files are added.
  $includes = array(
    'forum',
    'image',
    'node',
    'taxonomy',
    'taxonomy_menu',
    'uc_catalog',
    'user',
  );
  foreach ($includes as $include) {
    if (module_exists($include) && !module_hook($include, 'nodewords_type_id')) {
      module_load_include('inc', 'nodewords', 'includes/' . $include);
    }
  }
}

/**
 * Render the meta tag values as HTML.
 *
 * @param $tags
 *   An array of tags.
 *
 * @param $output_type
 *  The type of output, 'head' (default), or 'update index'.
 *
 * @return
 *   A string containing the HTML output for the META tag.
 */
function _nodewords_output_tags($tags, $output_type = 'head') {
  $output = array();
  $tags_info = nodewords_get_possible_tags();
  $weights = array();

  foreach ($tags as $name => $content) {
    if ($content === '') {
      continue;
    }

    // Check if it's a property meta tag (which may contain an XML namespace).
    $is_property = (
      $output_type == 'head' &&
      isset($tags_info[$name]['templates']['head'][$name]) &&
      $tags_info[$name]['templates']['head'][$name] == NODEWORDS_META_PROPERTY
    );
    $parts = $is_property ? array($name, $name) : explode(':', $name); 

    // Ensure that the previous assigned output template was cleared.
    $template = NULL;

    if (!isset($parts[1])) {
      $parts[1] = $parts[0];
    }

    if ($output_type == 'update index') {
      $bool = (
        isset($tags_info[$parts[0]]['templates']['search index'][$parts[1]])
      );

      if ($bool) {
        // The '%content' element will be added later.
        $replace = array(
          '%attributes' => empty($tags_info[$parts[0]]['attributes'][$parts[1]]) ? '' : drupal_attributes($tags_info[$parts[0]]['attributes'][$parts[1]]),
        );
        $template = $tags_info[$parts[0]]['templates']['search index'][$parts[1]];
        $weight = isset($tags_info[$parts[0]]['weight'][$parts[1]]) ? $tags_info[$parts[0]]['weight'][$parts[1]] : 0;
      }
    }
    else {
      $bool = (
        isset($tags_info[$parts[0]]['templates']['head'][$parts[1]]) &&
        ($meta_name = check_plain(decode_entities(strip_tags($parts[1]))))
      );

      if ($bool) {
        // The '%content' element will be added later.
        $replace = array(
          '%name' => $meta_name,
          '%attributes' => empty($tags_info[$parts[0]]['attributes'][$parts[1]]) ? '' : drupal_attributes($tags_info[$parts[0]]['attributes'][$parts[1]]),
        );
        $template = $tags_info[$parts[0]]['templates']['head'][$parts[1]];
        $weight = isset($tags_info[$parts[0]]['weight'][$parts[1]]) ? $tags_info[$parts[0]]['weight'][$parts[1]] : 0;

        if (!is_string($template)) {
          switch ($template) {
            case NODEWORDS_META:
              $template = '<meta name="%name" content="%content"%attributes />';
              break;

            case NODEWORDS_HTTP_EQUIV:
              $template = '<meta http-equiv="%name" content="%content"%attributes />';
              break;

            case NODEWORDS_LINK_REL:
              $template = '<link rel="%name" href="%content"%attributes />';
              break;

            case NODEWORDS_LINK_REV:
              $template = '<link rev="%name" href="%content"%attributes />';
              break;

            // This requires theme customizations in order for the output to
            // remain valid XHTML, see the OpenGraph section of the README.txt
            // for further details.
            case NODEWORDS_META_PROPERTY:
              $template = '<meta property="%name" content="%content"%attributes />';
              break;

            default:
              $template = '';
              break;
          }
        }
      }
    }

    if (!empty($template)) {
      // Allow the meta tags to have multiple values.
      if (!empty($tags_info[$name]['multiple'])) {
        $content = explode("\n", $content);
      }

      // Simplify the output handling.
      if (!is_array($content)) {
        $content = array($content);
      }

      // Now add the content element(s) to the replacement array.
      foreach ($content as $content_item) {
        $replace['%content'] = str_replace('&#039;', "'", trim(check_plain(decode_entities(strip_tags($content_item)))));
        $output[] = strtr($template, $replace);
        $weights[] = $weight;
      }
    }
  }

  if (count($output)) {
    array_multisort($weights, $output);

    return implode("\n", $output);
  }
  else {
    return '';
  }
}

/**
 * Provide a complete path for the current URL, optionally using a value
 * manually assigned via a form.
 *
 * @param $content
 *   An array of settings for this current field, optionally including the
 *   manually assigned path.
 * @param $options
 *   An array of options for this current page.
 *
 * @return
 *   Fully qualified absolute URL for the current page.
 */
function _nodewords_prepare_path($content, $options) {
  // Need to compare the value against system base path.
  $base_path = base_path();

  // Remove the base path from the front of the URL.
  if (!empty($content['value']) && strpos($content['value'], $base_path) === 0) {
    $content['value'] = drupal_substr($content['value'], drupal_strlen($base_path));
  }

  // Start with a system path.
  if (empty($content['value'])) {
    $path = '';

    switch ($options['type']) {
      case NODEWORDS_TYPE_FRONTPAGE:
        $path = '<front>';
        break;

      case NODEWORDS_TYPE_NODE:
        $path = 'node/' . $options['id'];
        break;

      case NODEWORDS_TYPE_PAGE:
        $path = $_GET['q'];
        break;

      case NODEWORDS_TYPE_TERM:
        // Accommodate other modules that change the path via hook_term_path().
        $term = taxonomy_get_term($options['id']);
        $path = module_invoke('taxonomy', 'term_path', $term);
        break;

      case NODEWORDS_TYPE_USER:
        $path = 'user/' . $options['id'];
        break;
    }

    if (!empty($path)) {
      $content['value'] = $path;
    }
  }

  if (!empty($content['value'])) {
    return check_url(nodewords_url($content['value'], $options));
  }
  else {
    return '';
  }
}

/**
 * Extract or generate the description for the current object.
 *
 * @param $tags
 *   The array of tags currently generated.
 * @param $content
 *   An array of settings for this current field, optionally including the
 *   manually assigned path.
 * @param $options
 *   An array of options for this current page.
 * @param $tag_name
 *   The name of the tag being generated.
 *
 * @return
 *   The final string to be used for the description tag.
 */
function _nodewords_prepare_description(&$tags, $content, $options, $tag_name) {
  // Will need this.
  if (!isset($content['value'])) {
    $content['value'] = '';
  }

  // If this is a node, try to load it then see if the description can or needs
  // to be automatically generated.
  if ($options['type'] == NODEWORDS_TYPE_NODE && $node = node_load($options['id'])) {
    $autogenerate = variable_get('nodewords_metatags_generation_method_' . $node->type, NODEWORDS_GENERATION_WHEN_EMPTY);

    if ($autogenerate == NODEWORDS_GENERATION_ALWAYS
      || (empty($content['value']) && $autogenerate == NODEWORDS_GENERATION_WHEN_EMPTY)) {
      $content['value'] = nodewords_metatag_from_node_content($node, $content['value']);
    }
  }

  // Load the default if no value is present.
  if (empty($content['value']) && !empty($options['default'][$tag_name]['value'])) {
    $content['value'] = $options['default'][$tag_name]['value'];
  }

  $tags[$tag_name] = $content['value'];
}