websiteWebsite
codingteam CodingTeam
A free forge, lightweight and extensible.

 

Browse the code

Revision log Information on the revision
Revision: 432 (differences)
Author: xbright
Log message: * Fixed #2214
* Fixed a typo
Change revision:
0 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
<?php
//   This file is a part of CodingTeam. Take a look at <http://codingteam.org>.
//   Copyright © 2007-2010 Erwan Briand <erwan@codingteam.net>
//
//   This program is free software: you can redistribute it and/or modify it
//   under the terms of the GNU Affero General Public License as published by
//   the Free Software Foundation, version 3 only.
//
//   This program is distributed in the hope that it will be useful, but
//   WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
//   or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public
//   License for more details.
//
//   You should have received a copy of the GNU Affero General Public License
//   along with this program. If not, see <http://www.gnu.org/licenses/>.
 
/**
 * @file
 * This file include all global functions
 *
 * This file include all global functions needed by a lot of files of the
 * whole CodingTeam software.
 */
 
 
/**
 * Translate a string and add arguments
 *
 * Gets the translated string from gettext and add arguments in it with
 * the Python way instead of the *ugly* PHP way (sprintf).
 *
 * @param $str
 *   The string to be translated.
 * @param $args
 *   All arguments to be added.
 * @return
 *   The translated and formatted string.
 */
function i18n($str, $args=array())
{
    // If i18n is temporarily down
    global $shutdown_i18n;
    if ($shutdown_i18n)
        return $str;
 
    // Get the translated string
    $str = gettext($str);
 
    // Add arguments to the string if exist
    if (count($args) > 0)
        // Fetching all arguments
        foreach ($args as $key => $value)
        {
            // Decimal value
            if (is_numeric($value))
                $type = 'd';
            // String value
            elseif (is_string($value))
                $type = 's';
 
            // Authorize errors
            if (!strstr($str, '%('.$key.')d') && $type == 'd')
                $type = 's';
 
            // Replace
            $str = str_replace('%('.$key.')'.$type, $value, $str);
        }
 
    // Return the translated string with arguments
    return $str;
}
 
 
/**
 * Generate a captcha
 *
 * Create two number that have to be sum. Generate a hash based on the 
 * SESSION `alea`.
 *
 * @return
 *   An array with the first number, the second and the result hash.
 */
function generateCaptcha()
{
    $n1 = rand(0, 10);
    $n2 = rand(0, 10);
    $n = $n1 + $n2;
    $n3 = sha1($n + $_SESSION['alea']);
    
    return array($n1, $n2, $n3);
}
 
 
/**
 * Generate an unique identifier
 *
 * Generate an identifier based on all ASCII characters or only on 
 * alphanumeric characters.
 *
 * @param $ascii (optional)
 *   TRUE if you want to use all ASCII characters.
 * @return
 *   The identifier.
 */
function generateUniqueID($ascii=TRUE)
{
    if ($ascii)
        $hash_str = " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTU".
                    "VWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~";
    else
        $hash_str = 'abcdefghijkmnopqrstuvwxyz023456789';
 
    $hash_nb = 42;
    $hash = '';
    for($i=1; $i<=$hash_nb; $i++)
    {
        $nb = strlen($hash_str);
        $nb = mt_rand(0, ($nb-1));
        $hash .= $hash_str[$nb];
    }
 
    return $hash;
}
 
 
/**
 * Transform tags in real URL
 *
 * Tags is the request array made by CodingTeam. This function use it
 * to generate the real URL
 *
 * @param $tag
 *   Often $this->page (in module's views).
 * @return
 *   An URL.
 */
function getURLbyTags($tag=FALSE)
{
    $ret = '';
    foreach ($tag as $key => $value)
        $ret .= $value.'/';
 
    return mb_substr($ret, 0, -1);
}
 
 
/**
 * Get user informations
 *
 * Get a class instance for an user. This function load the class
 * and return the class instance.
 *
 * @param $id
 *   Database identifier of the user.
 * @param $db
 *   The instance of the database class.
 * @param $loadby (optional)
 *   Database field to load from (empty if identifier).
 * @return
 *   An instance of User class.
 */
function getUser($id, $db, $loadby=FALSE)
{
    require_once(CT_BASEDIR.'/inc/modules/users/models/user.php');    
    $user = new User($db);
 
    if (!$loadby)
        $ldu = $user->load($id, 'id');
    else
        $ldu = $user->load($id, $loadby);
 
    if ($ldu)
        return $user;
    else
        return FALSE;
}
 
 
/**
 * Get DVCS user
 *
 * Try to get a CodingTeam user with a commit author from a DVCS.
 *
 * @param $author
 *   The author.
 * @param $db
 *   The instance of the database class.
 * @return
 *   An instance of User class.
 */
function getDVCSUser($author, $db)
{
    $user = FALSE;
 
    $user = getUser($author, $db, 'nickname');
    if (!$user)
    {
        $re = '([\\w-+]+(?:\\.[\\w-+]+)*@(?:[\\w-]+\\.)+[a-zA-Z]{2,7})';
        if ($c = preg_match_all("/".$re."/is", $author, $matches))
        {
            $email = $matches[1][0];
            $user = getUser($email, $db, 'email');
        }
    }
 
    return $user;
}
 
 
/**
 * Get DVCS username
 *
 * Get an username from a "John Doe <john.doe@domain.tld>" string. For use
 * only with non-existing accounts on the forge. It removes the mail from the
 * username.
 *
 * @param $author
 *   The author.
 * @return
 *   An username.
 */
function getDVCSUserName($author)
{
    $re = '([\\w-+]+(?:\\.[\\w-+]+)*@(?:[\\w-]+\\.)+[a-zA-Z]{2,7})';
    if ($c = preg_match_all("/".$re."/is", $author, $matches))
    {
        $email = $matches[1][0];
 
        if (strstr($author, ' <'.$email.'>'))
            $author = mb_substr($author, 0, -mb_strlen(' <'.$email.'>'));
    }
 
    return $author;
}
 
 
/**
 * Get a class
 *
 * Require a file, load the class and return the class instance.
 * If the class name contains `.`, the class is from a module. If not,
 * this is a global class.
 *
 * @param $class
 *   Name of the class.
 * @param $arg (optional)
 *   Argument for class loading.
 * @return
 *   An instance of the class.
 */
function getClass($class, $arg=FALSE)
{
    if (mb_strstr($class, '.'))
        $base = FALSE;
    else
        $base = TRUE;
 
    // This class is from the core of CodingTeam
    if ($base)
        $file = CT_BASEDIR.'/inc/classes/'.$class.'.php';
 
    // This class is a model of a module
    else
    {
        $grep = explode('.', $class);
        $module = $grep[0];
        $class = $grep[1];
        $file = CT_BASEDIR.'/inc/modules/'.$module.'/models/'.$class.'.php';
    }
 
    if (!file_exists($file))
        exit('Error.');
    else
    {
        require_once($file);
        $classname = ucfirst($class);
        if ($arg)
            // Create a new instance with args
            $object = new $classname($arg);
        else
            // Create a new instance
            $object = new $classname();
 
        return $object;
    }
}
 
 
/**
 * Get a static page
 *
 * Search if the page exists in the database and return it.
 *
 * @param $db
 *   The instance of the database class.
 * @param $page
 *   The name of the page.
 * @return
 *   An array with the title, the text, the date and the author of the page.
 */
function getStaticPage($db, $page)
{
    $texts = getClass('texts', $db);
    $txtval = $texts->get($page);
 
    if ($txtval)
    {
        $textview = getClass('textview');
 
        return array('title' => htmlspecialchars($txtval['title']),
                     'text' => $textview->prepare($txtval['text'],
                                                  $txtval['allow_nl2br']),
                     'date' => $txtval['date'],
                     'author' => $txtval['author']);
    }
 
    return FALSE;
}
 
 
/**
 * Internationalize date
 *
 * Change the format of the date in human readable.
 *
 * @param $date
 *   A date in the datetime format.
 * @param $lang
 *   A language code.
 * @return
 *   The new date.
 */
function i18nDate($date, $lang)
{
    if (mb_substr($lang, 0, 2) == 'fr')
    {
        $d = array();
        $d['day'] = mb_substr($date, 8, 2);
        $d['month'] = mb_substr($date, 5, 2);
        $d['year'] = mb_substr($date, 0, 4);
        $c = explode(' ', $date); 
 
        $hours = ((isset($c[1])) ? $c[1] : '');
 
        return $d['day'].'/'.$d['month'].'/'.$d['year'].' '.$hours;
    }
    else
        return $date;
}
 
 
/**
 * Convert a date
 *
 * Convert a date from a format to another.
 *
 * @param $date
 *   The date.
 * @param $in
 *   The input format.
 * @param $out
 *   The output format.
 * @return
 *   The new date.
 */
function convertDate($date, $in, $out)
{
    // Input date is a datetime
    if ($in == 'datetime')
    {
        // Ouput date is RFC-822 compliant 
        if ($out == 'rfc')
        {
            list($date, $hours) = explode(' ', $date);
            list($year, $month, $day) = explode('-', $date);
            list($hour, $min, $sec) = explode(':', $hours);
            return date('r', mktime($hour, $min, $sec, $month, $day, $year));
        }
        // Output date is a Unix timestamp
        elseif ($out == 'timestamp')
        {
            $_val = explode(' ', $date);
            $_date = explode('-', $_val[0]);
            $_time = explode(':', $_val[1]);
            return mktime($_time[0], $_time[1], $_time[2],
                          $_date[1], $_date[2], $_date[0]);
        }
    }
    // Input date is a timestamp
    elseif ($in == 'timestamp')
    {
        // Output date is RFC-3339 compliant
        if ($out == 'rfc.3339')
        {
            $date_ = date('Y-m-d\TH:i:s', $date);
            $matches = array();
            if (preg_match('/^([\-+])(\d{2})(\d{2})$/', date('O', $date),
                $matches))
                $date_ .= $matches[1].$matches[2].':'.$matches[3];
            else
                $date_ .= 'Z';
        }
        return $date_;
    }
    // Input date is format used by Subversion
    elseif ($in == 'svn')
    {
        // Output date is datetime
        if ($out == 'datetime')
        {
            return preg_replace(
                    "/(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}).(.*)Z/",
                    "$1-$2-$3 $4:$5:$6", $date);
        }
    }
    // Input date is format used by Mercurial
    elseif ($in == 'hg')
    {
        // Output date is datetime
        if ($out == 'datetime')
        {
            $_date = convertDate($date, 'datetime', 'timestamp');
            return date("Y-m-d H:i:s", $_date);
        }
    }
}
 
 
/**
 * Truncate a string
 *
 * Truncate a string with a certain number of allowed characters and
 * put a `…` after the string. 
 *
 * @param $str
 *   The string.
 * @param $char
 *   The number of allowed characters.
 * @param $utf8
 *   TRUE for the '…' character.
 * @return
 *   The new string.
 */
function map_str($str, $char, $utf8=TRUE)
{
    if (mb_strlen($str) > $char)
        return mb_substr($str, 0, $char).(($utf8) ? '…' : '...');
    else
        return mb_substr($str, 0, $char);
}
 
 
/**
 * SVN decode
 *
 * Decode a string from SVN.
 *
 * @param $str
 *   The string.
 * @return
 *   The new string.
 */
function svn_decode($str)
{
    if (mb_detect_encoding($str) == 'ASCII')
    {
        $new = preg_replace('/(\?\\\)(\\d+)/ei', 'chr(intval(\'\\2\'))', $str);
        $final = html_entity_decode($new, ENT_COMPAT, 'UTF-8');
 
        return htmlspecialchars($final);
    }
    else
        return htmlspecialchars($str);
}
 
 
/**
 * Send a mail
 *
 * Send a mail with pretty headers.
 *
 * @param $subject
 *   The subject of the mail.
 * @param $text
 *   The content of the mail.
 * @param $to
 *   The receiver of the mail.
 * @param $db
 *   The instance of the database class.
 * @return
 *   A boolean: TRUE if the mail is sended.
 */
function sendmail($subject, $text, $to, $db)
{
    $config = getClass('config', $db);
    $mailfrom = $config->get('global', 'mailfrom');
 
    $text_ = wordwrap($text, 70);
    $headers = 'From: '.$mailfrom."\r\n".
    'Reply-To: '.$mailfrom."\r\n".
    'X-Mailer: PHP/'.phpversion()."\r\n".
    'MIME-Version: 1.0'."\r\n".
    'Content-type: text/plain; charset=utf-8'."\r\n";
 
    if (mail($to, $subject, $text_, $headers))
        return TRUE;
 
    return FALSE;
}
 
 
/**
 * Verifiy the level of the user
 *
 * Exit with a 401 HTTP code if the level of the user is not the wished one. 
 *
 * @param $user_id
 *   The database id of the user.
 * @param $wished_level
 *   The level to be tested.
 * @param $session
 *   The instance of the session class.
 * @param $error
 *   The instance of the error class.
 * @param $db
 *   The instance of the database class.
 */
function verify_user_level($user_id, $wished_level, $session, $error, $db)
{
    if ($session->isLogged())
    {
        $user = getUser($user_id, $db);
        $level = $user->getLevel();
 
        if ($level != $wished_level)
            $error->displayError('401 Unauthorized.', 0, '401 Unauthorized');
    }
    else
        $error->displayError('401 Unauthorized.', 0, '401 Unauthorized');
}
 
 
/*
 * Check if can see project
 *
 * Exit if this user can't see this project.
 *
 * @param $valid
 *   Whatever the project is valid or not.
 * @param $private
 *   Whatever the project is private or not.
 * @param $pid
 *   The database identifier of the project.
 * @param $uid
 *   The database identifier of the user.
 * @param $session
 *   The instance of the Session class.
 * @param $db
 *   The instance of the Database class.
 * @param $e
 *   The instance of the Error class.
 * @param $features
 *   The list of enabled features.
 * @param $view
 *   The name of the current view.
 */
function check_can_see_project($valid, $private, $pid, $uid, $session, $db, $e,
                               $features, $view)
{
    // Validity
    if (!$valid)
        $e->displayError(i18n('This project have to be validated.'), 0);
 
    // Features
    $views = array('screenshots', 'statistics', 'timeline', 'download',
                   'browse', 'bugs', 'roadmap', 'i18n', 'doc', 'news', 'forum',
                   'jabber');
 
    if (!empty($features) && in_array($view, $views))
    {
        $expfeat = explode('_', $features);
 
        if (!in_array($view, $expfeat))
            $e->displayError(i18n('This feature has been disabled by an '.
                                  'administrator.'), 0);
    }
 
    // Privacy
    if ($private)
    {
        $can_see_that_project = FALSE;
 
        if ($session->isLogged())
        {
            if ($_SESSION['id'] == $uid)
                $can_see_that_project = TRUE;
            else
            {
                $cl = getClass('project.admins', $db);
                $admins = $cl->getAdmins($pid, 'project');
 
                foreach ($admins as $admin)
                    if ($_SESSION['id'] == $admin['userid'])
                        $can_see_that_project = TRUE;
            }
 
            if (is_level($_SESSION['id'], 'administrator', $db))
                $can_see_that_project = TRUE;
        }
 
        if (!$can_see_that_project)
            $e->displayError(i18n('Project not found.'), 0);
    }
}
 
 
/**
 * Test the level
 *
 * Test if the level of the user is the wished one. 
 *
 * @param $user_id
 *   The database id of the user.
 * @param $wished_level
*   The level to be tested.
 * @param $db
 *   The instance of the database class.
 * @return
 *   A boolean: TRUE if both user level and wished level are equal.
 */
function is_level($user_id, $wished_level, $db)
{
    if ($user_id)
    {
        $user = getUser($user_id, $db);
        $level = $user->getLevel();
 
        if ($level == $wished_level)
            return TRUE;
    }
 
    return FALSE;
}
 
 
/**
 * Test affiliation
 *
 * Test if the user is affiliated with the project as a project administrator. 
 *
 * @param $user_id
 *   The database id of the user.
 * @param $project_id
 *   The database id of the project.
 * @param $db
 *   The instance of the database class.
 * @param $power (optional)
 *   A power.
 * @return
 *   A boolean: TRUE if user is a project administrator.
 */
function is_affiliation($user_id, $project_id, $db, $power=NULL)
{
    $project = getClass('projects.projects', $db);
    $iffound = $project->load($project_id);
 
    $result = FALSE;
    if ($iffound)
    {
        // Project initiator
        if ($user_id == $project->getUserid())
            $result = TRUE;
        else
        {
            // Project administrator
            $admins = getClass('project.admins', $db);
            $admins_list = $admins->getAdmins($project_id, 'project');
 
            $_p = $admins->getAvailablePowers();
            $powers = $_p[0];
            $bpowers = $_p[1];
 
            if (sizeof($admins_list) > 0)
                foreach ($admins_list as $admin)
                    if ($admin['userid'] == $user_id)
                    {
                        if (is_null($power))
                            $result = TRUE;
                        else
                        {
                            $powers = explode('_', $admin['powers']);
 
                            if (count($powers) > 0 && $powers[0] != '')
                            {
                                if (in_array($power, $powers))
                                    $result = TRUE;
                            }
                            else
                            {
                                if (in_array($power, $bpowers[$admin['role']]))
                                    $result = TRUE;
                            }
                        }
                    }
        }
    }
    return $result;
}
 
 
/**
 * Delete a cached page
 *
 * Delete the version of a page stored in the cache. 
 *
 * @param $pagetag
 *   Often $this->page (in module's views).
 * @param $recursive (optional)
 *   TRUE if recursive deletion requested
 */
function deleteCacheVersion($pagetag, $recursive=FALSE)
{
    // Delete cached page for all available langs
    $langdir = opendir(CT_BASEDIR.'/i18n/');
    while ($lang = readdir($langdir))
        if ($lang != '..' && $lang != '.svn')
        {
            if ($lang == '.')
                $lang = 'en';
 
            // Delete cached page for all type (xhtml, rss and atom)
            foreach (array('xhtml', 'rss', 'atom') as $type)
            {
                $file = CT_BASEDIR.'/public/cache/'.$type.'/'.
                        $lang.str_replace('/', '-', $pagetag);
                if (is_file($file))
                    unlink($file);
 
                // For some browsers and users who loves / at the end of URLs
                if (is_file($file.'-'))
                    unlink($file.'-');
 
                if ($recursive)
                {
                    // Delete cached page that name starts with pagetag
                    $recdir = opendir(CT_BASEDIR.'/public/cache/'.$type);
                    while ($rec = readdir($recdir))
                        if (mb_substr($rec, 0, 1) != '.')
                        {
                            $strduo = $lang.str_replace('/', '-', $pagetag);
                            $sub = mb_substr($rec, 0, mb_strlen($strduo));
                            if ($sub == $strduo && $rec != $strduo)
                            {
                                unlink(CT_BASEDIR.'/public/cache/'.
                                       $type.'/'.$rec);
                            }
                        }
                }
            }
        }
}
 
 
/**
 * Clear the cache
 *
 * Clear all views stored in the cache (you can filter by category).
 *
 * @param $category
 *   The category of the cache to be cleared (XHTML, RSS or ATOM).
 */
function clear_cache($category)
{
    if (in_array($category, array('xhtml', 'rss', 'atom')))
    {
        $path = CT_BASEDIR.'/public/cache/'.$category.'/';
        $dir = opendir($path);
 
        while ($file = readdir($dir))
            if (mb_substr($file, 0, 1) != '.')
                unlink($path.$file);
 
        closedir($dir);
    }
}
 
 
/**
 * Reformat a size
 *
 * Improve the readability of a file size for humans
 *
 * @param $size
 *   The size to format
 */
function format_size($size)
{
    $sizes = array('B', 'kB', 'MB', 'GB');
    for ($i=0; $size > 1024 && $i < count($sizes) - 1; $i++)
        $size /= 1024;
 
    return round($size, 0).' '.$sizes[$i];
} 
 
 
/**
 * Crypt a mail/jabber id (fight SPAM)
 *
 * 
 * @param $mail
 *   The mail to crypt
 */
function cryptmail($mail)
{
    $cryptedmail = "";
    $len = strlen($mail);
 
    for ($x=0; $x<$len; $x++)
    {
        $ord = ord(substr($mail, $x, 1));
        $cryptedmail .= "&#$ord;";
    }
    return $cryptedmail;
}
 
 
/**
 * InversedVSort
 *
 * Inversed versions sorting.
 */
function invertedvsort($a, $b)
{
    if ($a['posid'] == $b['posid'])
        return 0;
 
    return ($a['posid'] > $b['posid']) ? -1 : 1;
}
 
 
/**
 * SpamFilter
 *
 * Filter a message and define if it would be a SPAM or not. This function
 * have to be used only for contents published by anonymous users.
 *
 * @param $userinput
 *   The input text.
 * @param $ct_db
 *   The instance of the database class.
 * @return
 *   TRUE if this message would be a SPAM.
 */
function spamfilter($userinput, $ct_db)
{
    $text = strtolower($userinput);
    $score = 0;
 
    // Anonymous users can post something?
    $config = getClass('config', $ct_db);
    $authorized = $config->get('global', 'authorize-anonymous-posts');
    if (!$authorized)
        $score += 5;
 
    // One 'http://' equals one point
    $score += substr_count($text, 'http://');
 
    // One 'www.' equals one half point
    $score += substr_count($text, 'www.') / 2;
 
    // One URL insertion equals one point
    $list = array('<a href=', '[url=', '[link=');
    foreach ($list as $word)
        $score += substr_count($text, $word);
 
    // One word in this list equals two points
    $list = array('viagra', 'cialis', 'meds', 'cheap', 'lottery', 'penis',
                  'enlarg', 'poker', 'insurance', 'ringtone', 'blackjack',
                  'casino', 'earn', 'weight', 'winner', 'free!', 'dollars',
                  '20%', '50%', '70%', '80%', '99%', 'cash', 'credit',
                  'satisfaction', 'fee', 'pharmacy', 'marketing', 'offer',
                  'promotion', 'bid', '$', '€', '£', 'porn', 'pr0n', 'video',
                  'russia', 'girl', 'customer', 'invoice', 'low prices',
                  'price', 'income', 'revenue', 'purchase', 'vegas', 'club',
                  'buy', 'tramadol', 'xanax', 'pill', 'holy', 'nude', '.com',
                  '. , ', 'site', 'nice', 'congrat', 'good', 'photo', 'pic',
                  'diet', 'drug');
    foreach ($list as $word)
        $score += substr_count($text, $word) * 2;
 
    // Content length must be superior to 5 characters
    if (mb_strlen($text) <= 5)
        $score += 5;
 
    if ($score >= 5)
        return TRUE;
}
 
 
/**
 * HTMLSourceView
 *
 * Show a beautiful syntax-highlighted source code in a semantic way and valid
 * XHTML 1.0 Strict and CSS 2.1.
 *
 * @param $source
 *   The source code you want to highlight.
 * @param $lang
 *   The language of this snippet.
 * @param $hlline (optional)
 *   A line you want to highlight.
 * @param $link (optional)
 *   An optional link base for lines anchors.
 * @param $n (optional)
 *   FALSE if you don't want to add line breaks.
 * @return
 *   The HTMLSourceView.
 */
function HTMLSourceView($source, $lang, $hlline=FALSE, $link=FALSE, $n=TRUE)
{
    require_once(CT_BASEDIR.'/inc/libs/geshi.php');
 
    $geshi = new GeSHi($source, $lang);
    $geshi->enable_line_numbers(GESHI_NO_LINE_NUMBERS);
    $geshi->set_header_type(GESHI_HEADER_NONE);
    $geshi->enable_multiline_span(FALSE);
    $geshi->enable_keyword_links(TRUE);
    $geshi->set_line_ending("\n");
    $_code = $geshi->parse_code();
 
    $code_ = explode("\n", $_code);
 
    if ($hlline)
    {
        list($hl_lines, $hl_line) = $hlline;
        array_pop($code_);
    }
 
    if ($link)
        list($url, $hash) = $link;
 
    $code_future = '';
    $code = '<div class="code border_top border_left border_bottom '.
            'border_right background_code_ln" style="width: 98%;">'.
            '<div class="border_right lines">';
 
    $i = 0;
    foreach ($code_ as $line)
    {
        if ($hlline && $hl_lines[$i] == $hl_line)
            $class = 'background_original';
        elseif ($i & 1)
            $class = 'background_code_first';
        else
            $class = 'background_code_second';
 
        if ($link)
        {
            $f = '<a href="'.$url.'#'.$hash.'line-'.$i.'">';
            $l = '</a>';
        }
 
        $code .= '<span class="linenumber" '.((!$hlline) ? 'id="'.$hash.
                 'line-'.$i.'"' : '').'>'.
                   (($hlline && $hl_lines[$i] == $hl_line) ? '<strong>' : '').
                   ((!$link) ? $hl_lines[$i] : $f.$i.$l).
                   (($hlline && $hl_lines[$i] == $hl_line) ? '</strong>' : '').
                 '</span>'.(($n) ? "\n" : '');
 
        $code_future .= '<span class="line '.$class.'">'.$line.
                        (($n) ? "\n" : '').'</span>';
 
        $i ++;
    }
 
    $code .= '</div><div class="src"><pre>'.$code_future.'</pre></div></div>';
    return $code;
}
 
 
/**
 * Generate the pagination
 *
 * Generate the pagination in a fancy way.
 *
 * @param $total
 *   The total number of items.
 * @param $max
 *   The maximum number of items by page.
 * @param $page
 *   The page that is currently viewed.
 * @param $plink
 *   A prefix for the links.
 * @param $slink (optional)
 *   A suffix for the links.
 * @param $f (optional)
 *   TRUE to force pagenum even if it's 1.
 * @return
 *   The HTML-formed pagination.
 */
function generate_pagination($total, $max, $page, $plink, $slink='', $f=FALSE)
{
    $str = '';
 
    global $generate_pagination_infos_links;
    $generate_pagination_infos_links = array($plink, $slink, $f);
 
    // Construct link
    function crtlnk($i)
    {
        global $generate_pagination_infos_links;
        list($plink, $slink, $f) = $generate_pagination_infos_links;
 
        $lnk = $plink.(($i != 1 || $f) ? $i : '' ).$slink;
        return str_replace('//', '/', $lnk);
    }
 
    // Calculate
    if ($total > $max)
    {
        $str = '<div style="float: left;padding-right: 15px;">';
 
        $first_page = 1;
        $last_page = ceil($total/$max);
 
        $current_page = $page;
        if ($current_page == 0)
            $current_page = 1;
 
        // Javascript combobox
        $str .= '<form><select id="jscboxurl" name="sel" onChange="window.'.
        'location=document.getElementById(\'jscboxurl\').value" '.
        'style="padding:0;margin:0;">{links}</select></form>'.
        '</div><div style="line-height: 1.5em;">';
 
        $content = '';
        for ($j=1; $j<=$last_page; $j++)
        {
            $content .= '<option value="'.crtlnk($j).'" '.
                        (($j == $current_page) ? 'selected="selected"' : '').
                        '>'.i18n('Page %(n)d on %(t)d',
                                 array('n' => $j, 't' => $last_page)).
                        '</option>';
        }
 
        $str = str_replace('{links}', $content, $str);
 
        // Links
        if ($current_page != $first_page)
            $str .= '<a href="'.crtlnk($first_page).'">'.
                    i18n('First (%(n)d)', array('n' => $first_page)).
                    '</a>&nbsp;-&nbsp;';
        else
            $str .= i18n('First (%(n)d)',
                         array('n' => $first_page)).'&nbsp;-&nbsp;';
 
        if ($current_page - 4 > $first_page)
            $str .= '…&nbsp;';
 
        for ($i=($current_page - 4); $i<($current_page + 5); $i++)
        {
            if ($i > 0 && $i <= $last_page)
            {
                if ($current_page == $i)
                    $str .= '<strong>'.$i.'</strong>&nbsp;';
                else
                    $str .= '<a href="'.crtlnk($i).'">'.$i.'</a>&nbsp;';
 
                $final_i = $i;
            }
        }
 
        if ($final_i < $last_page)
            $str .= '…&nbsp;';
 
        if ($current_page != $last_page)
            $str .= '-&nbsp;<a href="'.crtlnk($last_page).'">'.
                    i18n('Last (%(n)d)', array('n' => $last_page)).'</a>';
        else
            $str .= '-&nbsp;'.i18n('Last (%(n)d)',
                                array('n' => $last_page));
 
        $str .= '</div>';
    }
    else
    {
        $current_page = $page;
        $final_i = 0;
    }
 
    // Statistics
    if ($page == 0)
        $st_start = 0;
    else
        $st_start = ($current_page - 1) * $max;
 
    if ($final_i > $page)
        $st_total = $max * $current_page;
    else
        $st_total = $total;
 
    if ($page == 0)
        $st_write = 1;
    else
        $st_write = $st_start + 1;
 
    return array($str, array('total' => $st_total,
                             'write' => $st_write));
}
 
 
/**
 * Show user infos
 *
 * Show the nickname and the avatar of an user and show a contact toolbar too. 
 *
 * @param $unregistered_nick
 *   The nickname of the user if not registered.
 * @param $registered_id
 *   The database id of the registered user.
 * @param $ct_db
 *   The instance of the database class.
 * @param $lang
 *   The lang.
 * @param $toolbar (optional)
 *   TRUE if you want to see the contact toolbar.
 * @param $details (optional)
 *   TRUE if you want to get more details on the user.
 * @param $mini (optional)
 *   TRUE if you want to get a mini display.
 * @return
 *   A piece of XHTML code that presents an user.
 */
function show_user_infos($unregistered_nick, $registered_id, $ct_db, $lang,
                         $toolbar=TRUE, $details=FALSE, $mini=FALSE)
{
    $return = '';
    $config = getClass('config', $ct_db);
    $baseavatar = 'public/images/icons/stock/generic/stock_person_big.png';
    $deleavatar = 'public/images/icons/actions/edit-delete_big.png';
 
    if ($details)
        $length = 100;
    else
        $length = 32;
 
    if (!empty($unregistered_nick))
        $return .= '<img src="'.$baseavatar.'" alt="'.
                   htmlspecialchars($unregistered_nick).'" '.
                   'class="border_left border_right border_top border_bottom"'.
                   ' style="float: left;padding: 1px;margin-right: 5px;width:'.
                   $length.'px;height: '.$length.'px;" />'.
                   '<strong>'.htmlspecialchars($unregistered_nick).'</strong>'.
                   '<br /><span class="text_normal" '.
                   'style="font-style: italic;">'.i18n('Anonymous user').
                   '</span>';
    else
    {
        $user = getUser($registered_id, $ct_db);
        $avatar = htmlspecialchars($user->getAvatar());
        $nickname = htmlspecialchars($user->getNickname());
        $jabberid = htmlspecialchars($user->getJid());
        $website = htmlspecialchars($user->getUrl());
 
        $omnipresence_url = $config->get('jabber', 'omnipresence-url');
            
        $file = 'public/upload/avatars/'.$nickname;
        
        if ($avatar == '!jabber!')
            $logourl = $omnipresence_url.'avatar.php?hash='.md5($jabberid).
                       '&amp;default='.CT_BASEURL.$baseavatar;
        elseif ($avatar == '!no!')
            $logourl = $baseavatar;
        elseif ($avatar == '!deleted!')
            $logourl = $deleavatar;
        elseif (is_file(CT_BASEDIR.'/'.$file))
            $logourl = 'users/avatar/'.$nickname;
        else
            $logourl = $baseavatar;
 
        if ($mini)
        {
            $return .= '<a href="users/show/'.$nickname.'" title="'.$nickname.
                       '"><img src="'.$logourl.'" alt="'.$nickname.'" '.
                       'class="border_left border_right border_top '.
                       'border_bottom" style="padding: 1px;'.
                       'margin-right: 5px;width:'.
                       $length.'px;height: '.$length.'px;" /></a>';
        }
        else
        {
            $return .= '<img src="'.$logourl.'" alt="'.$nickname.'" '.
                       'class="border_left border_right border_top '.
                       'border_bottom" style="float: left;padding: 1px;'.
                       'margin-right: 5px;width:'.
                       $length.'px;height: '.$length.'px;" />'.
                       '<a href="users/show/'.$nickname.'"><strong>'.
                       $nickname.'</strong></a>';
 
            if ($user->getLevel() == 'deleted')
            {
                $return .= '<br /><span class="text_normal" '.
                           'style="font-style: italic;">'.
                           i18n('Deleted user').'</span>';
            }
            else
            {
                if (!empty($jabberid))
                    $return .= '<br /><span class="text_normal" '.
                               'style="font-style: italic;"><script '.
                               'type="text/javascript" src="'.
                               $omnipresence_url.md5($jabberid).'/text_js-'.
                               mb_substr($lang, 0, 2).'.txt"></script></span>';
 
                if ($details)
                    $return .= '<br /><br />'.htmlspecialchars($user->getName()).
                               ' '.htmlspecialchars($user->getSurname()).
                               '<br /><span class="text_normal">'.
                               i18n('Registered on %(date)s.',
                               array('date' => i18nDate($user->getDate(), $lang))).
                               '</span>';
 
                if ($toolbar)
                {
                    $return .= '<div class="background_important" '.
                               'style="width: 100%;padding: 5px;display: '.
                               'block;clear: left;margin-top: 15px;">'.
                               '<a href="users/messages/new/'.$nickname.'" '.
                               'title="'.i18n('Send a private message').
                               '"><img src="public/images/icons/stock/net/'.
                               'stock_mail-send.png" alt="'.
                               i18n('Send a private message').'" '.
                               'style="margin-right: 5px;" /></a>'.
                               '<a href="mailto:'.
                               cryptmail(htmlspecialchars($user->getEmail())).
                               '" title="'.i18n('Send a mail to this user').
                               '"><img src="'.
                               'public/images/icons/actions/mail-forward.png"'.
                               ' alt="'.i18n('Send a mail to this user').'" '.
                               'style="margin-right: 5px;" /></a>';
 
                    if (!empty($jabberid))
                        $return .= '<a href="xmpp:'.cryptmail($jabberid).'" '.
                                   'title="'.i18n('Contact this user by Jabber').
                                   '"><img src="'.
                                   'public/images/icons/apps/im-jabber.png" '.
                                   'alt="'.i18n('Contact this user by Jabber').
                                   '" style="margin-right: 5px;" /></a>';
 
                    if (!empty($website))
                        $return .= '<a href="'.$website.'" title="'.
                                   i18n('View the website of the user').
                                   '"><img src="'.
                                   'public/images/icons/apps/web-browser.png" '.
                                   'alt="'.i18n('View the website of the user').
                                   '" style="margin-right: 5px;" /></a>';
                
                    $return .= '<a href="api/user/'.$nickname.'" '.
                               'title="'.i18n('OpenForge API').
                               '"><img src="public/images/icons/mimetypes/x-'.
                               'office-address-book.png" alt="'.
                               i18n('OpenForge API').'" style="margin-left: '.
                               '10px;" /></a>'.
                               '</div>';
                }
            }
        }
    }
 
    return $return;
}
?>