root/ngcms/trunk/engine/includes/inc/functions.inc.php @ 143

Revision 143, 47.1 KB (checked in by ngcms, 4 years ago)

[DEVEL версия] Переработка механизма блокировки IP адресов, добавлена возможность блокировки подсетей и режим "тихий запрет" (когда пользователю не сообщается, что он заблокирован).

Со стороны движка проверка бана реализована сейчас только в комментариях.

Line 
1<?php
2
3//
4// Copyright (C) 2006-2008 Next Generation CMS (http://ngcms.ru/)
5// Name: functions.php
6// Description: Common system functions
7// Author: Vitaly Ponomarev, Alexey Zinchenko
8//
9
10// Protect against hack attempts
11if (!defined('NGCMS')) die ('HAL');
12
13//
14// SQL security string escape
15//
16function db_squote($string) {
17    return "'".mysql_real_escape_string($string)."'";
18}
19
20function db_dquote($string) {
21    return "'".mysql_real_escape_string($string).'"';
22}
23
24//
25// HTML & special symbols protection
26//
27function secure_html($string) {
28    return str_replace(array("{","<", ">"), array("&#123;","&lt;", "&gt;"), htmlspecialchars($string));
29}
30
31function Formatsize($file_size) {
32
33    if ($file_size >= 1073741824) {
34        $file_size = round($file_size / 1073741824 * 100) / 100 . " Gb";
35    } elseif ($file_size >= 1048576) {
36        $file_size = round($file_size / 1048576 * 100) / 100 . " Mb";
37    } elseif ($file_size >= 1024) {
38        $file_size = round($file_size / 1024 * 100) / 100 . " Kb";
39    } else {
40        $file_size = $file_size . " b";
41    }
42    return $file_size;
43}
44
45
46function checkIP() {
47    if (getenv("REMOTE_ADDR")) {
48        return getenv("REMOTE_ADDR");
49    } elseif ($_SERVER["REMOTE_ADDR"]) {
50        return $_SERVER['REMOTE_ADDR'];
51    }
52    return "unknown";
53}
54
55
56function gzip() {
57    global $config;
58
59    if ($config['use_gzip'] == "1" && extension_loaded('zlib') && function_exists('ob_gzhandler')) {
60        @ob_start('ob_gzhandler');
61    }
62}
63
64
65// Generate backup for table list. If no list is given - backup ALL tables with system prefix
66function dbBackup($fname, $gzmode, $tlist = ''){
67    global $mysql;
68
69    if ($gzmode && (!function_exists('gzopen')))
70        $gzmode = 0;
71
72    if ($gzmode)    $fh = gzopen($fname, "w");
73     else            $fh = fopen($fname, "w");
74
75    if ($fh === false)
76        return 0;
77
78    // Generate a list of tables for backup
79    if (!is_array($tlist)) {
80        $tlist = array();
81
82        foreach ($mysql->select("show tables like '".prefix."_%'") as $tn)
83            $tlist [] = $tn[0];
84    }
85
86    // Now make a header
87    $out  = "# ".str_repeat('=', 60)."\n# Backup file for `Next Generation CMS`\n# ".str_repeat('=', 60)."\n# DATE: ".gmdate("d-m-Y H:i:s", time())." GMT\n# VERSION: ".version."\n#\n";
88    $out .= "# List of tables for backup: ".join(", ", $tlist)."\n#\n";
89
90    // Write a header
91    if ($gzmode)    gzwrite($fh, $out);
92     else            fwrite($fh, $out);
93
94    // Now, let's scan tables
95    foreach ($tlist as $tname) {
96        // Fetch create syntax for table and after - write table's content
97        if (is_array($csql = $mysql->record("show create table `".$tname."`"))) {
98            $out  = "\n#\n# Table `".$tname."`\n#\n";
99            $out .= "DROP TABLE IF EXISTS `".$tname."`;\n";
100            $out .= $csql[1].";\n";
101
102            if ($gzmode)    gzwrite($fh, $out);
103             else            fwrite($fh, $out);
104
105            // Now let's make content of the table
106            $query = mysql_query("select * from `".$tname."`", $mysql->connect);
107            $rowNo = 0;
108            while ($row = mysql_fetch_row($query)) {
109                $out = "insert into `".$tname."` values (";
110                $rowNo++;
111                $colNo = 0;
112                foreach ($row as $v)
113                    $out .= (($colNo++)?', ':'').db_squote($v);
114                $out .= ");\n";
115
116                if ($gzmode)    gzwrite($fh, $out);
117                 else            fwrite($fh, $out);
118            }
119
120            $out = "# Total records: $rowNo\n";
121
122            if ($gzmode)    gzwrite($fh, $out);
123             else            fwrite($fh, $out);
124        } else {
125            $out = "#% Error fetching information for table `$tname`\n";
126
127            if ($gzmode)    gzwrite($fh, $out);
128             else            fwrite($fh, $out);
129        }
130    }
131    if ($gzmode)    gzclose($fh);
132     else            fclose($fh);
133
134    return 1;
135}
136
137function AutoBackup() {
138    global $config;
139
140    $backupFile = root."cache/last_backup.tmp";
141
142    $last_backup    =    @file_get_contents($backupFile);
143    $time_now        =    time();
144
145    if ($time_now > ($last_backup + $config['auto_backup_time'] * 3600)) {
146            // Try to open temp file for writing
147            $fx = is_file($backupFile)?@fopen($backupFile,"r+"):@fopen($backupFile,"w+");
148            if ($fx) {
149            $filename    =    root."backups/backup_".date("Y_m_d_H_i", $time_now).".gz";
150
151            // We need to create file with backup
152            dbBackup($filename, 1);
153
154            rewind($fx);
155            fwrite($fx, $time_now);
156            ftruncate($fx,ftell($fx));
157        }
158    }
159}
160
161function LangDate($format, $timestamp) {
162    global $lang;
163
164    $weekdays        =    explode(",", $lang['weekdays']);
165    $short_weekdays    =    explode(",", $lang['short_weekdays']);
166    $months            =    explode(",", $lang['months']);
167    $months_s        =    explode(",", $lang['months_s']);
168    $short_months    =    explode(",", $lang['short_months']);
169
170    foreach ($weekdays as $name => $value)
171    $weekdays[$name] = preg_replace("/./", "\\\\\\0", $value);
172
173    foreach ($short_weekdays as $name => $value)
174    $short_weekdays[$name] = preg_replace("/./", "\\\\\\0", $value);
175
176    foreach ($months as $name => $value)
177    $months[$name] = preg_replace("/./", "\\\\\\0", $value);
178
179    foreach ($months_s as $name => $value)
180    $months_s[$name] = preg_replace("/./", "\\\\\\0", $value);
181
182    foreach ($short_months as $name => $value)
183    $short_months[$name] = preg_replace("/./", "\\\\\\0", $value);
184
185    $format = @preg_replace("/(?<!\\\\)D/", $short_weekdays[date("w", $timestamp)], $format);
186    $format = @preg_replace("/(?<!\\\\)F/", $months[date("n", $timestamp) - 1], $format);
187    $format = @preg_replace("/(?<!\\\\)Q/", $months_s[date("n", $timestamp) - 1], $format);
188    $format = @preg_replace("/(?<!\\\\)l/", $weekdays[date("w", $timestamp)], $format);
189    $format = @preg_replace("/(?<!\\\\)M/", $short_months[date("n", $timestamp) - 1], $format);
190
191    return @date($format, $timestamp);
192}
193
194//
195// Generate a list of smilies to show
196function InsertSmilies($insert_location, $break_location = false, $area = false) {
197    global $config, $tpl;
198
199    if ($config['use_smilies']) {
200        $smilies = explode(",", $config['smilies']);
201
202        // For smilies in comments, try to use 'smilies.tpl' from site template
203        $templateDir = (($insert_location == 'comments') && is_readable(tpl_dir.$config['theme'].'/smilies.tpl'))?tpl_dir.$config['theme']:tpl_actions;
204
205        foreach ($smilies as $null => $smile) {
206            $i++;
207            $smile = trim($smile);
208
209            $tvars['vars'] = array(
210                'area'        =>    $area,
211                'smile'        =>    $smile
212            );
213
214            $tpl -> template('smilies', $templateDir);
215            $tpl -> vars('smilies', $tvars);
216            $output .= $tpl -> show('smilies');
217
218            if ($i%$break_location == "0" && $break_location) {
219                $output .= "<br />";
220            } else {
221                $output .= "&nbsp;";
222            }
223        }
224        return $output;
225    }
226}
227
228
229function phphighlight($content = '') {
230
231    $f    =    array('<br>', '<br />', '<p>', '&lt;', '&gt;', '&amp;', '&#124;', '&quot;', '&#036;', '&#092;', '&#039;','&nbsp;', '\"');
232    $r    =    array("\n", "\n", "\n", '<', '>', '&', '\|', '"', '$', '', '\'', '', '"');
233    $content    =    str_replace($f, $r, $content);
234    $content    =    highlight_string($content, true);
235
236    return $content;
237}
238
239
240function QuickTags($area = false, $template = false) {
241    global $config, $lang, $tpl;
242
243    $tvars['vars'] = array(
244        'php_self'    =>    $PHP_SELF,
245        'area'        =>    $area
246    );
247
248    if ($template == "pmmes") {
249        $tpl -> template('quicktags_pmmes', tpl_actions);
250        $tpl -> vars('quicktags_pmmes', $tvars);
251        return $tpl -> show('quicktags_pmmes');
252    }
253    elseif ($template == "editcom") {
254        $tpl -> template('quicktags_editcom', tpl_actions);
255        $tpl -> vars('quicktags_editcom', $tvars);
256        return $tpl -> show('quicktags_editcom');
257    }
258    elseif ($template == "siteaddnews") {
259        $tpl -> template('quicktags', tpl_site);
260        $tpl -> vars('quicktags', $tvars);
261        return $tpl -> show('quicktags');
262    }
263    elseif ($template == "bbnews") {
264        $tpl -> template('bbnews', tpl_actions);
265        $tpl -> vars('bbnews', $tvars);
266        return $tpl -> show('bbnews');
267    } else {
268        $tpl -> template('quicktags', tpl_actions);
269        $tpl -> vars('quicktags', $tvars);
270        return $tpl -> show('quicktags');
271    }
272}
273
274
275function BBCodes($area = false) {
276    global $config, $lang, $tpl;
277
278    if ($config['use_bbcodes'] == "1") {
279        $tvars['vars'] = array(
280            'php_self'    =>    $PHP_SELF,
281            'area'        =>    $area
282        );
283
284        $tpl -> template('bbcodes', tpl_site);
285        $tpl -> vars('bbcodes', $tvars);
286
287        return $tpl -> show('bbcodes');
288    }
289}
290
291
292function Padeg($n, $s) {
293
294    $n    =    abs($n);
295    $a    =    split(",", $s);
296    $l1    =    $n - ((int)($n / 10)) * 10;
297    $l2    =    $n - ((int)($n / 100)) * 100;
298
299    if ("11" <= $l2 && $l2 <= "14") {
300        $e = $a[2];
301    } else {
302        if ($l1 == "1") {
303            $e = $a[0];
304        }
305
306        if ("2" <= $l1 && $l1 <= "4") {
307            $e = $a[1];
308        }
309
310        if (("5" <= $l1 && $l1 <= "9") || $l1 == "0") {
311            $e=$a[2];
312        }
313    }
314
315    if ($e == "") {
316        $e = $a[0];
317    }
318
319    return($e);
320}
321
322
323//
324// Perform BAN check
325// $ip        - IP address of user
326// $act        - action type ( 'users', 'comments', 'news',... )
327// $subact    - subaction type ( for comments this may be 'add' )
328// $userRec    - record of user (in case of logged in)
329// $name    - name entered by user (in case it was entered)
330function checkBanned($ip, $act, $subact, $userRec, $name) {
331    global $mysql;
332
333    $check_ip = sprintf("%u", ip2long($ip));
334
335    // Currently we use limited mode. Try to find row
336    if ($ban_row = $mysql->record("select * from ".prefix."_ipban where addr_start <= ".db_squote($check_ip)." and addr_stop >= ".db_squote($check_ip)." order by netlen limit 1")) {
337        // Row is found. Let's check for event type. STATIC CONVERSION
338        $mode = 0;
339        if        (($act == 'users') &&        ($subact == 'register'))    { $mode = 1; }
340        else if    (($act == 'users') &&         ($subact == 'auth'))        { $mode = 2; }
341        else if    (($act == 'comments') &&    ($subact == 'add'))            { $mode = 3; }
342        if (($locktype = intval(substr($ban_row['flags'], $mode, 1))) > 0) {
343            $mysql->query("update ".prefix."_ipban set hitcount=hitcount+1 where id=".db_squote($ban_row['id']));
344            return $locktype;
345        }
346    }
347    return 0;
348}
349
350//
351// Perform FLOOD check
352// $mode    - WORKING MODE ( 0 - check only, 1 - update )
353// $ip        - IP address of user
354// $act        - action type ( 'comments', 'news',... )
355// $subact    - subaction type ( for comments this may be 'add' )
356// $userRec    - record of user (in case of logged in)
357// $name    - name entered by user (in case it was entered)
358function checkFlood($mode, $ip, $act, $subact, $userRec, $name){
359    global $mysql, $config;
360
361    // Return if flood protection is disabled
362    if (!$config['flood_time']) {
363        return 0;
364    }
365
366    $this_time = time() + ($config['date_adjust'] * 60) - $config['flood_time'];
367
368    // If UPDATE mode is used - update data
369    if ($mode) {
370        $this_time = time() + ($config['date_adjust'] * 60);
371        $mysql->query("insert into ".prefix."_flood (ip, id) values (".db_squote($ip).", ".db_squote($this_time).") on duplicate key update id=".db_squote($this_time));
372        return 0;
373    }
374
375    // Delete expired records
376    $mysql->query("DELETE FROM ".prefix."_flood WHERE id < ".db_squote($this_time));
377
378    // Check if we have record
379    if ($mysql->rows($mysql->query("SELECT * FROM ".prefix."_flood WHERE id > ".db_squote($this_time)." AND ip = ".db_squote($ip))) > "0") {
380        // Flood found
381        return 1;
382    }
383    return 0;
384}
385
386
387function zzMail($to, $subject, $message, $filename = false, $mail_from = false) {
388    global $lang, $config;
389
390    $mail_from    =    (!$mail_from) ? "mailbot@".str_replace("www.", "", $_SERVER['SERVER_NAME']) : $mail_from;
391    $uniqid        =    md5(uniqid(time()));
392
393    $headers    =    'From: '.$mail_from."\n";
394    $headers    .=    'Reply-to: '.$mail_from."\n";
395    $headers    .=    'Return-Path: '.$mail_from."\n";
396    $headers    .=    'Message-ID: <'.$uniqid.'@'.$_SERVER['SERVER_NAME'].">\n";
397    $headers    .=    'MIME-Version: 1.0'."\n";
398    $headers    .=    'Date: '.gmdate('D, d M Y H:i:s', time())."\n";
399    $headers    .=    'X-Priority: 3'."\n";
400    $headers    .=    'X-MSMail-Priority: Normal'."\n";
401    $headers    .=    'X-Mailer: '.engineName.' : '.engineVersion."\n";
402    $headers    .=    'X-MimeOLE: '.engineName.' : '.engineVersion."\n";
403    $headers    .=    'Content-Type: multipart/mixed;boundary="----------'.$uniqid.'"'."\n\n";
404    $headers    .=    '------------'.$uniqid."\n";
405    $headers    .=    'Content-Type: text/html;charset='.$lang['encoding'].''."\n";
406    $headers    .=    'Content-Transfer-Encoding: 8bit';
407
408    if (is_file($filename)){
409        $file        =    fopen($filename, 'rb');
410        $message    .=    "\n".'------------'.$uniqid."\n";
411        $message    .=    'Content-Type: application/octet-stream;name="'.basename($filename).'"'."\n";
412        $message    .=    'Content-Transfer-Encoding: base64'."\n";
413        $message    .=    'Content-Disposition: attachment;';
414        $message    .=    'filename="'.basename($filename).'"'."\n\n";
415        $message    .=    chunk_split(base64_encode(fread($file, filesize($filename))))."\n";
416    }
417
418    @mail($to, $subject, $message, $headers);
419}
420
421
422function msg($msg_arr) {
423    global $config, $lang, $template, $PHP_SELF, $how;
424
425    if ($msg_arr["type"] == "error") {
426        $msg = '<div class="msge"><img src="'.skins_url.'/images/error.gif" hspace="10" />'.$lang["msge_error"].$msg_arr["text"].'</div>';
427        if ($PHP_SELF == "admin.php" || $how) { echo $msg; } else { $template['vars']['mainblock'] .= $msg; }
428
429        if ($msg_arr["info"] && $msg_arr["info"] != "") {
430            $msg = '<div class="msgi"><img src="'.skins_url.'/images/info.gif" hspace="10" />'.$lang["msgi_info"].$msg_arr["info"].'</div>';
431            if ($PHP_SELF == "admin.php" || $how) { echo $msg; } else { $template['vars']['mainblock'] .= $msg; }
432        }
433    } elseif ($msg_arr["type"] == "info") {
434        $msg = '<div class="msgi"><img src="'.skins_url.'/images/info.gif" hspace="10" />'.$lang["msgi_info"].$msg_arr["info"].'</div>';
435        if ($PHP_SELF == "admin.php" || $how) { echo $msg; } else { $template['vars']['mainblock'] .= $msg; }
436    } else {
437        $msg = '<div class="msgo"><img src="'.skins_url.'/images/msg.gif" hspace="10" />'.$msg_arr["text"].'</div>';
438        if ($PHP_SELF == "admin.php" || $how) { echo $msg; } else { $template['vars']['mainblock'] .= $msg; }
439
440        if ($msg_arr["info"] && $msg_arr["info"] != "") {
441            $msg = '<div class="msgi"><img src="'.skins_url.'/images/info.gif" hspace="10" />'.$lang["msgi_info"].$msg_arr["info"].'</div>';
442            if ($PHP_SELF == "admin.php" || $how) { echo $msg; } else { $template['vars']['mainblock'] .= $msg; }
443        }
444    }
445}
446
447
448function DirSize($directory) {
449
450    if (!is_dir($directory)) return -1;
451    $size = 0;
452
453    if ($dir = opendir($directory)) {
454        while (($dirfile = readdir($dir)) !== false) {
455            if (is_link($directory . '/' . $dirfile) || $dirfile == '.' || $dirfile == '..') {
456                continue;
457            }
458            if (is_file($directory . '/' . $dirfile)) {
459                $size += filesize($directory . '/' . $dirfile);
460            } elseif (is_dir($directory . '/' . $dirfile)) {
461                $dirSize = dirsize($directory . '/' . $dirfile);
462                if ($dirSize >= 0) {
463                    $size += $dirSize;
464                } else {
465                    return -1;
466                }
467            }
468        }
469        closedir($dir);
470    }
471    return $size;
472}
473
474
475// Scans directory and returns it's size and file count
476// Return array with size, count
477function directoryWalk($dir, $blackmask = null, $whitemask = null) {
478 if (!is_dir($dir)) return array( -1, -1);
479
480 $size  = 0;
481 $count = 0;
482 $flag  = 0;
483 $path  = array($dir);
484 $wpath = array();
485 $files = array();
486 $od = array();
487 $dfile = array();
488 $od[1] = opendir($dir);
489
490 while (count($path)) {
491  $level = count($path);
492  $sd    = join("/", $path );
493  $wsd   = join("/", $wpath);
494  while (($dfile[$level] = readdir($od[$level])) !== false) {
495   if (is_link($sd . '/' . $dfile[$level]) || $dfile[$level] == '.' || $dfile[$level] == '..')
496    continue;
497
498   if (is_file($sd . '/' . $dfile[$level])) {
499    // Check for black list
500
501    $size += filesize($sd . '/' . $dfile[$level]);
502    $files []= ($wsd?$wsd.'/':'').$dfile[$level];
503    $count ++;
504   } elseif (is_dir($sd . '/' . $dfile[$level])) {
505    array_push($path, $dfile[$level]);
506    array_push($wpath, $dfile[$level]);
507    $od[$level+1] = opendir(join("/", $path));
508    $flag = 1;
509    break;
510   }
511  }
512  if ($flag) {
513      $flag = 0;
514      continue;
515  }
516  array_pop($path);
517  array_pop($wpath);
518 }
519 return array($size, $count, $files);
520}
521
522
523// makeCategoryList - make <SELECT> list of categories
524// Params: set via named array
525// * name      - name field of <SELECT>
526// * selected  - ID of category to be selected or array of IDs to select (in list mode)
527// * skip      - ID of category to skip or array of IDs to skip
528// * doempty   - add empty category to the beginning ("no category"), value = 0
529// * doall     - all category named "ALL" to the beginning, value is empty
530// * nameval   - use DB field "name" instead of ID in HTML option value
531// * resync    - flag, if set - we make additional lookup into database for new category list
532// * checkarea - flag, if set - generate a list of checkboxes instead of <SELECT>
533function makeCategoryList($params = array() /*selected=0, $my=0, $noempty=0, $name='category'*/){
534    global $catz, $lang, $mysql;
535
536    if (!is_array($params['skip'])) { $params['skip'] = $params['skip']?array($params['skip']):array(); }
537    $name = array_key_exists('name', $params)?$params['name']:'category';
538
539    if (!$params['checkarea']) {
540     $out = "<select name=\"$name\" id=\"catmenu\"".($params['class']?' class="'.$params['class'].'"':'').">\n";
541     if ($params['doempty'])    { $out.= "<option value=\"0\">".$lang['no_cat']."</option>\n"; }
542     if ($params['doall'])    { $out.= "<option value=\"\">".$lang['sh_all']."</option>\n"; }
543    }
544    if ($params['resync'])  {
545        $catz = array();
546        foreach ($mysql->select("select * from `".prefix."_category` order by posorder asc", 1) as $row) {
547            $catz[$row['alt']] = $row;
548            $catmap[$row['id']] = $row['alt'];
549        }
550    }
551
552    foreach($catz as $k => $v){
553        if (in_array($v['id'], $params['skip'])) { continue; }
554        if ($params['checkarea']) {
555            $out .= str_repeat('&#8212; ', $v['poslevel']).'<label><input type="checkbox" name="'.$name.'_'.$v['id'].'" value="1"'.((is_array($params['selected']) && in_array($v['id'], $params['selected']))?' checked="checked"':'').'/> '.$v['name']."</label><br/>\n";
556        } else {
557            $out.="<option value=\"".($params['nameval']?$v['name']:$v['id'])."\"".(($v['id']==$params['selected'])?' selected="selected"':'').">".str_repeat('&#8212; ', $v['poslevel']).$v['name']."</option>\n";
558        }
559    }
560    if (!$params['checkarea']) {
561        $out.="</select>";
562    }
563    return $out;
564}
565
566
567function OrderList($value) {
568    global $lang, $catz;
569
570    $output = "<select name=\"orderby\">\n";
571    foreach (array('id desc', 'id asc', 'postdate desc', 'postdate asc', 'title desc', 'title asc', 'rating desc', 'rating asc') as $v) {
572            $vx = str_replace(' ','_',$v);
573        $output.='<option value="'.$v.'"'.(($value==$v)?' selected="selected"':'').'>'.$lang["order_$vx"]."</option>\n";
574    }
575    $output.="</select>\n";
576    return $output;
577}
578
579
580function ChangeDate($time = 0) {
581    global $lang, $langShortMonths;
582
583    if ($time <= 0) { $time = time(); }
584
585    $result = '<div id="cdate"><select name="c_day">';
586    for ($i=1; $i <= 31; $i++)
587        $result .= '<option value="'.$i.'"'.((date('j', $time)==$i)?' selected="selected"':'').'>'.$i.'</option>';
588
589    $result .= '</select><select id="c_month" name="c_month">';
590
591    foreach ($langShortMonths as $k => $v)
592        $result .= '<option value="'.($k+1).'"'.((date('n', $time)==($k+1))?' selected="selected"':'').'>'.$v.'</option>';
593
594    $result .= '</select>
595    <input type="text" id="c_year" name="c_year" size="4" maxlength="4" value="'.date('Y',$time).'" />
596    <input type="text" id="c_hour" name="c_hour" size="2" maxlength="2" value="'.date('H',$time).'" /> :
597    <input type="text" id="c_minute" name="c_minute" size="2" maxlength="2" value="'.date('i',$time).'" />
598    </div>';
599
600    return $result;
601}
602
603
604function ListFiles($path, $ext) {
605
606    $file_list = array();
607
608    if (!$handle = opendir("$path")) {
609        echo "<p>Can not open directory</p> ";
610    }
611
612    while (false !== ($file = readdir($handle))) {
613        if(eregi(".$ext", $file)) {
614            $file_arr = explode(".", $file);
615            $file_list["$file_arr[0]"]= $file_arr[0];
616        }
617    }
618    closedir($handle);
619    return $file_list;
620}
621
622
623function ListDirs($folder, $category = false, $alllink = true) {
624    global $lang;
625
626    $select = '<select name="category">'.($alllink?'<option value="">- '.$lang['all'] .' -</option>':'');
627
628    if ($folder == "files") {
629        $def_dir    =    files_dir;
630        $dir        =    opendir(files_dir);
631    }
632
633    if ($folder == "images") {
634        $def_dir    =    images_dir;
635        $dir        =    opendir(images_dir);
636    }
637
638    while($file = readdir($dir)) {
639        $in_dir[] = $file;
640    }
641
642    natcasesort($in_dir);
643    reset($in_dir);
644
645    foreach ($in_dir as $file) {
646        if (is_dir($def_dir."/".$file) && $file != "." && $file != "..")
647            $select .= "<option value=\"".$file."\"".($category==$file?' selected="selected"':'').">".$file."</option>\n";
648    }
649    $select .= '</select>';
650
651    return $select;
652}
653
654
655function MakeDropDown($options, $name, $selected = "FALSE") {
656    $output = "<select size=1 name=\"".$name."\">";
657    foreach ($options as $k=>$v)
658        $output .= "<option value=\"".$k."\"".(($selected==$k)?" selected=\"selected\"":'').">".$v."</option>";
659    $output .= "</select>";
660
661    return $output;
662}
663
664
665function LoadLang($what, $where = '') {
666    global $config, $lang;
667
668    $where = ($where) ? '/'.$where : '';
669
670    if (!file_exists($toinc = root.'lang/'.$config['default_lang'].$where.'/'.$what.'.ini')) {
671        $toinc = root.'lang/english/'.$where.'/'.$what.'.ini';
672    }
673    if (file_exists($toinc)) {
674        $lang = (!is_array($lang)) ? parse_ini_file($toinc, true) : array_merge($lang, parse_ini_file($toinc, true));
675    }
676    return $lang;
677}
678
679// Return plugin dir
680function GetPluginDir($name) {
681    global $EXTRA_CONFIG;
682
683    $extras = get_extras_list();
684    if (!$extras[$name]) { return 0; }
685    return extras_dir.'/'.$extras[$name]['dir'];
686}
687
688function GetPluginLangDir($name) {
689    global $config;
690    $lang_dir = GetPluginDir($name).'/lang';
691    if (!$lang_dir) { return 0; }
692    if (is_dir($lang_dir.'/'.$config['default_lang'])) { $lang_dir = $lang_dir.'/'.$config['default_lang']; }
693    else if (is_dir($lang_dir.'/english')) { $lang_dir = $lang_dir.'/english'; }
694    else if (is_dir($lang_dir.'/russian')) { $lang_dir = $lang_dir.'/russian'; }
695    return $lang_dir;
696}
697
698// Load LANG file for plugin
699function LoadPluginLang($plugin, $file, $group = '', $prefix = '', $delimiter = '_') {
700    global $config, $lang, $EXTRA_CONFIG;
701
702    if (!$prefix) { $prefix = $plugin; }
703    // If requested plugin is activated, we can get 'dir' information from active array
704    $active = get_active_array();
705    if (!$active['active'][$plugin]) {
706        // No, plugin is not active. Let's load plugin list
707        $extras = get_extras_list();
708
709        // Exit if no data about this plugin is found
710        if (!$extras[$plugin]) { return 0; }
711        $lang_dir = extras_dir.'/'.$extras[$plugin]['dir'].'/lang';
712    } else {
713        $lang_dir = extras_dir.'/'.$active['active'][$plugin].'/lang';
714    }
715
716    // Exit if no lang dir
717    if (!is_dir($lang_dir)) { return 0; }
718
719    // find if we have 'lang' dir in plugin directory
720    // Try to load langs in order: default / english / russian
721    if (is_dir($lang_dir.'/'.$config['default_lang'])) { $lang_dir = $lang_dir.'/'.$config['default_lang']; }
722    else if (is_dir($lang_dir.'/english')) { $lang_dir = $lang_dir.'/english'; }
723    else if (is_dir($lang_dir.'/russian')) { $lang_dir = $lang_dir.'/russian'; }
724    else { return 0; }
725    // load file
726    $plugin_lang = parse_ini_file($lang_dir.'/'.($group?$group.'/':'').$file.'.ini');
727
728    // merge values
729    if (is_array($plugin_lang)) {
730        foreach ($plugin_lang as $p => $v) {
731            $lang[$prefix.$delimiter.$p] = $v;
732        }
733    }
734    return 1;
735}
736
737
738function GetAllCategories($cats) {
739    global $catz;
740
741    foreach ($cats as $k => $v) {
742        foreach ($catz as $row) {
743            if ($v == $row['id']) {
744                $catline .= ", ".$row['name'];
745            }
746        }
747    }
748
749    return preg_replace('[^([, ]+)]', '', $catline);
750}
751
752
753function MakeRandomPassword() {
754    global $config;
755    return substr(md5($config['crypto_salt'].uniqid(rand(),1)),0,10);
756}
757
758
759function EncodePassword($pass) {
760    $pass = md5(md5($pass));
761    return $pass;
762}
763
764function generateAdminNavigations($current, $start, $stop, $link, $navigations){
765    $result = '';
766    //print "call generateAdminNavigations(current=".$current.", start=".$start.", stop=".$stop.")<br>\n";
767    //print "Navigations: <pre>"; var_dump($navigations); print "</pre>";
768    for ($j=$start; $j<=$stop; $j++) {
769        if ($j == $current) {
770            $result .= str_replace('%page%',$j,$navigations['current_page']);
771        } else {
772            $row['page'] = $j;
773            $result .= str_replace('%page%',$j,str_replace('%link%',str_replace('%page%', $j, $link), $navigations['link_page']));
774        }
775    }
776    return $result;
777}
778
779
780// Generate page list for admin panel
781// * current - number of current page
782// * count   - total count of pages
783// * url     - URL of page, %page% will be replaced by page number
784function generateAdminPagelist($param){
785    global $tpl;
786
787    if ($param['count'] < 2) return '';
788
789    $nav = getNavigations(tpl_actions);
790    $tpl -> template('pages', tpl_actions);
791
792    // Prev page link
793    if ($param['current'] > 1) {
794        $prev = $param['current'] - 1;
795        $tvars['regx']["'\[prev-link\](.*?)\[/prev-link\]'si"] = str_replace('%page%',"$1",str_replace('%link%',str_replace('%page%', $prev, $param['url']), $nav['prevlink']));
796    } else {
797        $tvars['regx']["'\[prev-link\](.*?)\[/prev-link\]'si"] = "";
798        $no_prev = true;
799    }
800
801    // ===[ TO PUT INTO CONFIG ]===
802    $pages = '';
803    $maxNavigations         = 10;
804
805    $sectionSize    = floor($maxNavigations / 3);
806    if ($param['count'] > $maxNavigations) {
807        // We have more than 10 pages. Let's generate 3 parts
808        // Situation #1: 1,2,3,4,[5],6 ... 128
809        if ($param['current'] < ($sectionSize * 2)) {
810            $pages .= generateAdminNavigations($param['current'], 1, $sectionSize * 2, $param['url'], $nav);
811            $pages .= " ... ";
812            $pages .= generateAdminNavigations($param['current'], $param['count']-$sectionSize, $param['count'], $param['url'], $nav);
813        } elseif ($param['current'] > ($param['count'] - $sectionSize * 2 + 1)) {
814            $pages .= generateAdminNavigations($param['current'], 1, $sectionSize, $param['url'], $nav);
815            $pages .= " ... ";
816            $pages .= generateAdminNavigations($param['current'], $param['count']-$sectionSize*2 + 1, $param['count'], $param['url'], $nav);
817        } else {
818            $pages .= generateAdminNavigations($param['current'], 1, $sectionSize, $param['url'], $nav);
819            $pages .= " ... ";
820            $pages .= generateAdminNavigations($param['current'], $param['current']-1, $param['current']+1, $param['url'], $nav);
821            $pages .= " ... ";
822            $pages .= generateAdminNavigations($param['current'], $param['count']-$sectionSize, $param['count'], $param['url'], $nav);
823        }
824    } else {
825        // If we have less then 10 pages
826        $pages .= generateAdminNavigations($param['current'], 1, $param['count'], $param['url'], $nav);
827    }
828
829
830    $tvars['vars']['pages'] = $pages;
831    if ($prev + 2 <= $param['count']) {
832        $next = $prev + 2;
833        $tvars['regx']["'\[next-link\](.*?)\[/next-link\]'si"] = str_replace('%page%',"$1",str_replace('%link%',str_replace('%page%', $next, $param['url']), $nav['nextlink']));
834    } else {
835        $tvars['regx']["'\[next-link\](.*?)\[/next-link\]'si"] = "";
836        $no_next = true;
837    }
838    $tpl -> vars('pages', $tvars);
839    return $tpl -> show('pages');
840}
841
842function GetLink($what, $row = array(), $rawlink = 0){
843    global $config, $linkz, $catz, $catmap;
844
845    if (($what == 'category') && ($catz[$row['alt']]['alt_url'])) { return $catz[$row['alt']]['alt_url']; }
846
847    $entire = $linkz[ $config['mod_rewrite']? 'rewrite' : 'plain'][$what];
848    if (is_array($entire)) {
849        $link = $entire[ $config['category_link']? 'by_cat' : 'by_date'];
850    } else {
851        $link = $entire;
852    }
853
854    if ($row['catid']) {
855        $cats = array();
856        foreach (explode(',', $row['catid']) as $catid) {
857            if ($catmap[$catid] != '')
858                $cats[] = $catmap[$catid];
859        }
860        $categories = implode("-", $cats);
861    } else {
862        $categories = "none";
863    }
864
865    $tr =     array(
866        '&'            =>    '&amp;',
867        '{alt}'            =>    $row['alt'],
868        '{id}'            =>    $row['id'],
869        '{year}'        =>    date('Y', $row['postdate']),
870        '{month}'        =>    date('m', $row['postdate']),
871        '{day}'            =>    date('d', $row['postdate']),
872        '{alt_name}'    =>    $row['alt_name'],
873        '{catlink}'        =>    $categories,
874        '{author}'        =>    ($row['author']) ? urlencode($row['author']) : $row['name'],
875        '{page}'        =>    $row['page'],
876        '{userid}'        =>    $row['userid'],
877        '{code}'        =>    $row['code'],
878        '{plugin_name}'        =>    $row['plugin_name']);
879    if ($rawlink)
880        array_shift($tr);
881
882    $link = strtr($link, $tr);
883
884    preg_match_all('/\((.*?)\)/i', $link, $array);
885
886    for ($i = 0; $i < sizeof($array[1]); $i++){
887        $that = reset(explode("|", $array[1][$i]));
888        $link = str_replace('('.$array[1][$i].')', $that, $link);
889    }
890    return home."/".$link;
891}
892
893
894$letters = array('%A8' => '%D0%81', '%B8' => '%D1%91', '%C0' => '%D0%90', '%C1' => '%D0%91', '%C2' => '%D0%92', '%C3' => '%D0%93', '%C4' => '%D0%94', '%C5' => '%D0%95', '%C6' => '%D0%96', '%C7' => '%D0%97', '%C8' => '%D0%98', '%C9' => '%D0%99', '%CA' => '%D0%9A', '%CB' => '%D0%9B', '%CC' => '%D0%9C', '%CD' => '%D0%9D', '%CE' => '%D0%9E', '%CF' => '%D0%9F', '%D0' => '%D0%A0', '%D1' => '%D0%A1', '%D2' => '%D0%A2', '%D3' => '%D0%A3', '%D4' => '%D0%A4', '%D5' => '%D0%A5', '%D6' => '%D0%A6', '%D7' => '%D0%A7', '%D8' => '%D0%A8', '%D9' => '%D0%A9', '%DA' => '%D0%AA', '%DB' => '%D0%AB', '%DC' => '%D0%AC', '%DD' => '%D0%AD', '%DE' => '%D0%AE', '%DF' => '%D0%AF', '%E0' => '%D0%B0', '%E1' => '%D0%B1', '%E2' => '%D0%B2', '%E3' => '%D0%B3', '%E4' => '%D0%B4', '%E5' => '%D0%B5', '%E6' => '%D0%B6', '%E7' => '%D0%B7', '%E8' => '%D0%B8', '%E9' => '%D0%B9', '%EA' => '%D0%BA', '%EB' => '%D0%BB', '%EC' => '%D0%BC', '%ED' => '%D0%BD', '%EE' => '%D0%BE', '%EF' => '%D0%BF', '%F0' => '%D1%80', '%F1' => '%D1%81', '%F2' => '%D1%82', '%F3' => '%D1%83', '%F4' => '%D1%84', '%F5' => '%D1%85', '%F6' => '%D1%86', '%F7' => '%D1%87', '%F8' => '%D1%88', '%F9' => '%D1%89', '%FA' => '%D1%8A', '%FB' => '%D1%8B', '%FC' => '%D1%8C', '%FD' => '%D1%8D', '%FE' => '%D1%8E', '%FF' => '%D1%8F');
895//$chars = array('%C2%A7' => '&#167;', '%C2%A9' => '&#169;', '%C2%AB' => '&#171;', '%C2%AE' => '&#174;', '%C2%B0' => '&#176;', '%C2%B1' => '&#177;', '%C2%BB' => '&#187;', '%E2%80%93' => '&#150;', '%E2%80%94' => '&#151;', '%E2%80%9C' => '&#147;', '%E2%80%9D' => '&#148;', '%E2%80%9E' => '&#132;', '%E2%80%A6' => '&#133;', '%E2%84%96' => '&#8470;', '%E2%84%A2' => '&#153;', '%C2%A4' => '&curren;', '%C2%B6' => '&para;', '%C2%B7' => '&middot;', '%E2%80%98' => '&#145;', '%E2%80%99' => '&#146;', '%E2%80%A2' => '&#149;');
896// TEMPORARY SOLUTION AGAINST '&' quoting
897$chars = array('%D0%86' => '[CYR_I]', '%D1%96' => '[CYR_i]', '%D0%84' => '[CYR_E]', '%D1%94' => '[CYR_e]', '%D0%87' => '[CYR_II]', '%D1%97' => '[CYR_ii]', '%C2%A7' => chr(167), '%C2%A9' => chr(169), '%C2%AB' => chr(171), '%C2%AE' => chr(174), '%C2%B0' => chr(176), '%C2%B1' => chr(177), '%C2%BB' => chr(187), '%E2%80%93' => chr(150), '%E2%80%94' => chr(151), '%E2%80%9C' => chr(147), '%E2%80%9D' => chr(148), '%E2%80%9E' => chr(132), '%E2%80%A6' => chr(133), '%E2%84%96' => '&#8470;', '%E2%84%A2' => chr(153), '%C2%A4' => '&curren;', '%C2%B6' => '&para;', '%C2%B7' => '&middot;', '%E2%80%98' => chr(145), '%E2%80%99' => chr(146), '%E2%80%A2' => chr(149));
898$byary = array_flip($letters);
899
900
901function convert($content) {
902    global $byary, $chars;
903
904    $content = strtr(urlencode($content), $byary);
905    $content = strtr($content, $chars);
906    $content = urldecode($content);
907
908    return $content;
909}
910
911function utf2cp1251($text) { return convert($text); }
912
913function GetCategories($catid, $plain = false) {
914    global $catz, $catmap;
915
916    $cats = is_array($catid)?$catid:explode(",", $catid);
917    foreach ($cats as $v) {
918        if (isset($catmap[$v])) {
919            $row = $catz[$catmap[$v]];
920            $catline[] = ($plain) ? $row['name'] : "<a href=\"".GetLink('category', $row)."\">".$row['name']."</a>";
921        }
922    }
923
924    return ($catline ? implode(", ", $catline) : '');
925}
926
927
928//
929// New category menu generator
930function generateCategoryMenu(){
931    global $mysql, $catz, $tpl, $config;
932
933    $tpl -> template('categories', tpl_site);
934    foreach($catz as $k => $v){
935        if (!$v['cat_show']) continue;
936
937        $tvars['vars'] = array(
938            'if_active'    =>    (category && category == $v['alt'])?'active_cat':'',
939            'link'        =>    GetLink('category', array ('alt' => $v['alt'])),
940            'mark'        =>    str_repeat('&#8212;', $v['poslevel']),
941            'cat'        =>    $v['name'],
942            'counter'    =>    ($config['category_counters'] && $v['posts'])?('['.$v['posts'].']'):'',
943            'icon'        =>    $v['icon'],
944        );
945        $tvars['regx']['[\[icon\](.*)\[/icon\]]'] = trim($v['icon'])?'$1':'';
946
947        $tpl -> vars('categories', $tvars);
948
949        $result .= $tpl -> show('categories');
950    }
951    return $result;
952}
953
954//
955// make an array for filtering from text line like 'abc-def,dfg'
956function generateCategoryArray($categories){
957    global $catz;
958
959    $carray = array();
960    foreach(explode(",", $categories) as $v){
961        $xa = array();
962        foreach(explode("-", $v) as $n) {
963            if (is_array($catz[trim($n)]))
964                array_push($xa, $catz[trim($n)]['id']);
965        }
966        if (count($xa))
967            array_push($carray, $xa);
968    }
969    return $carray;
970}
971
972//
973// make a SQL filter for specified array
974function generateCategoryFilter(){
975
976}
977
978// Fill variables for news:
979// * $row - SQL row
980// * $fullMode - flag if desired mode is full
981// * $page - page No to show in full mode
982//function Prepare($row, $page) {
983function newsFillVariables($row, $fullMode, $page = 0, $disablePagination = 0) {
984    global $config, $parse, $lang;
985
986    $tvars = array ( 'vars' => array( 'pagination' => '', 'title' => $row['title']));
987
988    $url = GetLink('full', $row);
989
990    $tvars['vars']['author'] = "<a href=\"".GetLink('user', $row)."\" target=\"_blank\">".$row['author']."</a>";
991
992    // Divide into short and full content
993    list ($short, $full) = explode('<!--more-->', $row['content'], 2);
994
995    // Check if long part is divided into several pages
996    if ($full && (!$disablePagination) && (strpos($full, "<!--nextpage-->") !== false)) {
997        if (!is_numeric($page) || ($page <1)) $page = 1;
998
999        $pagination        =    '';
1000        $pages            =    explode("<!--nextpage-->", $full);
1001
1002        if (($pcnt = count($pages)) > 1) {
1003            if ($page > 1) {
1004                $row['page']    =    $page - 1;
1005                $pagination        .=    " <a href=\"".GetLink('full_page', $row)."\">".$lang['prevpage']."</a>&nbsp;\n";
1006                $tvars['vars']['short-story'] = '';
1007            }
1008
1009            for ($i = 1; $i <= $pcnt; $i++) {
1010                if ($i == $page) {
1011                    $pagination        .=    "[<b>".$i."</b>]\n";
1012                } else {
1013                    $row['page'] = $i;
1014                    $pagination        .=    "<a href=\"".GetLink('full_page', $row)."\">$i</a>\n";
1015                }
1016            }
1017
1018            if ($page != $pcnt) {
1019                $row['page']    =    $page + 1;
1020                $pagination        .=    "&nbsp;<a href=\"".GetLink('full_page', $row)."\">".$lang['nextpage']."</a>\n";
1021            }
1022            $tvars['vars']['pagination']    = $pagination;
1023            $full                            = $pages[$page-1];
1024        }
1025    }
1026
1027    if ($pagination) {
1028        $tvars['vars']['[pagination]'] = '';
1029        $tvars['vars']['[/pagination]'] = '';
1030    } else {
1031            $tvars['regx']["'\[pagination\].*?\[/pagination\]'si"] = '';
1032    }
1033
1034    // Delete "<!--nextpage-->" if pagination is disabled
1035    if ($disablePagination)
1036        $full = str_replace("<!--nextpage-->", "\n", $full);
1037
1038    // If HTML code is not permitted - LOCK it
1039    $title = $row['title'];
1040
1041    if (!($row['flags'] & 2)) {
1042        $short    = str_replace('<', '&lt;', $short);
1043        $full    = str_replace('<', '&lt;', $full);
1044        $title    = secure_html($title);
1045    }
1046    $tvars['vars']['title'] = $title;
1047
1048    // Make conversion
1049    if ($config['blocks_for_reg'])        { $short = $parse -> userblocks($short);    $full = $parse -> userblocks($full); }
1050    if ($config['use_htmlformatter'] && (!($row['flags'] & 1)))    {
1051        $short = $parse -> htmlformatter($short);    $full = $parse -> htmlformatter($full);
1052    }
1053    if ($config['use_bbcodes'])            { $short = $parse -> bbcodes($short);        $full = $parse -> bbcodes($full); }
1054    if ($config['use_smilies'])            { $short = $parse -> smilies($short);        $full = $parse -> smilies($full); }
1055
1056    $tvars['vars']['short-story']    = $short;
1057    $tvars['vars']['full-story']    = $full;
1058
1059    // Activities for short mode
1060    if (!$fullMode) {
1061        // Make link for full news
1062        $tvars['vars']['[full-link]']    =    "<a href=\"".$url."\">";
1063        $tvars['vars']['[/full-link]']    =    "</a>";
1064
1065        // Make blocks [fullnews] .. [/fullnews] and [nofullnews] .. [/nofullnews]
1066        if (strlen($full)) {
1067            // we have full news
1068            $tvars['vars']['[fullnews]'] = '';
1069            $tvars['vars']['[/fullnews]'] = '';
1070
1071            $tvars['regx']["'\[nofullnews\].*?\[/nofullnews\]'si"] = '';
1072        } else {
1073            // we have ONLY short news
1074            $tvars['vars']['[nofullnews]'] = '';
1075            $tvars['vars']['[/nofullnews]'] = '';
1076
1077            $tvars['regx']["'\[fullnews\].*?\[/fullnews\]'si"] = '';
1078
1079        }
1080
1081    } else {
1082        $tvars['regx']["'\\[full-link\\].*?\\[/full-link\\]'si"] = '';
1083    }
1084
1085    $tvars['vars']['pinned']    =    ($row['pinned']) ? "news_pinned" : "";
1086    $tvars['vars']['category']    =    @GetCategories($row['catid']);
1087
1088    if (!$fullMode) {
1089        $tvars['vars']['[link]'] = "<a href=\"".$url."\">";
1090        $tvars['vars']['[/link]'] = "</a>";
1091    } else {
1092        $tvars['vars']['[link]'] = '';
1093        $tvars['vars']['[/link]'] = '';
1094    }
1095
1096    $tvars['vars']['[print-link]']    =    "<a href=\"".GetLink('print', $row)."\">";
1097    $tvars['vars']['[/print-link]']    =    "</a>";
1098    $tvars['vars']['news_link']        =    $url;
1099
1100
1101    $tvars['vars']['news-id']    =    $row['id'];
1102    $tvars['vars']['php-self']    =    $PHP_SELF;
1103
1104    if ($row['editdate']) {
1105        $tvars['regx']['[\[update\](.*)\[/update\]]'] = '$1';
1106        $tvars['vars']['update'] = LangDate($config['timestamp_updated'], $row['editdate']);
1107    } else {
1108        $tvars['regx']['[\[update\](.*)\[/update\]]'] = '';
1109        $tvars['vars']['update'] = '';
1110    }
1111
1112    return $tvars;
1113}
1114
1115
1116//
1117// Navigation line generator for news / static pages
1118//
1119function generateNavigations($current, $start, $stop, $which_link, $row, $navigations){
1120    $result = '';
1121    for ($j=$start; $j<=$stop; $j++) {
1122        if ($j == $current) {
1123            $result .= str_replace('%page%',$j,$navigations['current_page']);
1124        } else {
1125            $row['page'] = $j;
1126            $result .= str_replace('%page%',$j,str_replace('%link%',GetLink($which_link, $row), $navigations['link_page']));
1127        }
1128    }
1129    return $result;
1130}
1131
1132
1133
1134function GetNewsTitle($sep, $name) {
1135    global $config, $lang, $mysql, $catz;
1136
1137    if ($config['lock']) {
1138        return $sep.$lang['lock'];
1139    }
1140
1141    if (altname) {
1142        if ($config["category_link"] == "0") {
1143            $where['catid']        =    "";
1144            $where['date']        =    " postdate > '".mktime(0, 0, 0, month, day, year)."' AND postdate < '".mktime(23, 59, 59, month, day, year)."'";
1145        } else {
1146            if (category == "none") {
1147                $where['catid']        =    " catid = ''";
1148                $where['date']        =    "";
1149            } else {
1150                $category = explode("-", category);
1151
1152                foreach ($category as $cat) {
1153                    $catids[] = $catz[$cat]['id'];
1154                }
1155                $categories = implode(",", $catids);
1156                $where['catid']        =    " catid regexp '[[:<:]]($categories)[[:>:]]'";
1157                $where['date']        =    "";
1158            }
1159        }
1160
1161        $title = $mysql->result("SELECT title FROM ".prefix."_news WHERE".$where['catid'].$where['date']." AND alt_name = ".db_squote($name));
1162
1163        if ($config["category_link"] == "1") {
1164            $echo_name = $sep.($categories ? GetCategories($categories, true) : "Uncategorized").$sep.secure_html($title);
1165        } else {
1166            $echo_name = $sep.LangDate(timestamp, mktime("0", "0", "0", month, day, year)).$sep.secure_html($title);
1167        }
1168    }
1169    elseif (id) {
1170        $row = $mysql->record("SELECT title, catid, month(from_unixtime(postdate)) as mm, year(from_unixtime(postdate)) as yy, day(from_unixtime(postdate)) as dd FROM ".prefix."_news WHERE id = ".db_squote(id));
1171
1172        if ($config["category_link"] == "0") {
1173            if ($row['catid']) {
1174                foreach ($row['catid'] as $cat) {
1175                    $catids[] = $catz[$cat]['id'];
1176                }
1177            } else {
1178                $catids = array();
1179            }
1180
1181            $categories = implode(",", $catids);
1182            $echo_name = $sep.($categories ? GetCategories($categories, true) : "Uncategorized").$sep.secure_html($row['title']);
1183        } else {
1184            $echo_name = $sep.LangDate(timestamp, mktime("0", "0", "0", $row['mm'], $row['dd'], $row['yy'])).$sep.secure_html($row['title']);
1185        }
1186    } else {
1187        if (category && !altname) {
1188            $cat_name    =    $catz[category]['name'];
1189            $echo_name    =    $sep.$cat_name;
1190        }
1191        if (year && (!month && !altname)) {
1192            $echo_name = $sep.LangDate("Y", mktime(0, 0, 0, 12, 7, year));
1193        }
1194        if (month && (!category && !altname)) {
1195            $echo_name = $sep.LangDate("F Y", mktime(0, 0, 0, month, 7, year));
1196        }
1197        if (month && day && (!category && !altname)) {
1198            $echo_name = $sep.LangDate("j Q Y", mktime("0", "0", "0", month, day, year));
1199        }
1200        if (!category && !day && !month && !year && !altname && !id) {
1201            if ($_POST['action'] == "search") {
1202                $echo_name = $sep.$lang['search'];
1203            } else {
1204                $echo_name = $sep.$lang['mainpage'];
1205            }
1206        }
1207    }
1208
1209    return(stripslashes($echo_name));
1210}
1211
1212
1213function GetMetatags() {
1214    global $config, $mysql, $catz, $category, $SYSTEM_FLAGS;
1215
1216    if (!$config['meta'])
1217        return;
1218
1219    $meta['description']    =    $config['description'];
1220    $meta['keywords']        =    $config['keywords'];
1221
1222    if ($category) {
1223        if ($catz[$category]['description']) {
1224            $meta['description'] = $catz[$category]['description'];
1225        }
1226        if ($catz[$category]['keywords']) {
1227            $meta['keywords'] = $catz[$category]['keywords'];
1228        }
1229    }
1230
1231    if (isset($SYSTEM_FLAGS['meta']['description']) && ($SYSTEM_FLAGS['meta']['description'] != ''))
1232        $meta['description'] = $SYSTEM_FLAGS['meta']['description'];
1233
1234    if (isset($SYSTEM_FLAGS['meta']['keywords']) && ($SYSTEM_FLAGS['meta']['keywords'] != ''))
1235        $meta['keywords'] = $SYSTEM_FLAGS['meta']['keywords'];
1236
1237    $result  = ($meta['description'] != '')?"<meta name=\"description\" content=\"".secure_html($meta['description'])."\" />\r\n":'';
1238    $result .= ($meta['keywords'] != '')?"<meta name=\"keywords\" content=\"".secure_html($meta['keywords'])."\" />\r\n":'';
1239
1240    return $result;
1241}
1242
1243function getNavigations($tpldir) {
1244    if (is_file($tpldir.'/navigation.ini')) {
1245        $navigation = parse_ini_file($tpldir.'/navigation.ini');
1246    } else {
1247        $navigation = array('prevlink' => '<a href="%link%">%page%</a> ','nextlink' => '<a href="%link%">%page%</a> ','current_page' => ' [%page%] ','link_page' => '<a href="%link%">%page%</a> ','dots' => ' ... ');
1248    }
1249    return $navigation;
1250}
1251
1252
1253//
1254// Generate navigations panel ( like: 1.2.[3].4. ... 25 )
1255// $current        - current page
1256// $start        - first page in navigations
1257// $end            - last page in navigations
1258// $maxnav        - maximum number of navigtions to show
1259// $link        - link to info page with text {page} that will be replaced by page number
1260function generatePagination($current, $start, $end, $maxnav, $link, $navigations){
1261    // Generate pagination block
1262    function generatePaginationBlock($current, $start, $end, $link, $navigations){
1263        $result = '';
1264        for ($j=$start; $j<=$end; $j++) {
1265            if ($j == $current) {
1266                $result .= str_replace('%page%',$j,$navigations['current_page']);
1267            } else {
1268                $row['page'] = $j;
1269                $result .= str_replace('%page%',$j,str_replace('%link%', str_replace('{page}', $j, $link), $navigations['link_page']));
1270            }
1271        }
1272        return $result;
1273    }
1274
1275
1276    $pages_count = $end - $start + 1;
1277
1278    if ($pages_count > $maxnav) {
1279        // We have more than 10 pages. Let's generate 3 parts
1280        $sectionSize    = floor($maxnav / 3);
1281
1282        // Section size should be not less 1 item
1283        if ($sectionSize < 1)
1284            $sectionSize = 1;
1285
1286        // Situation #1: 1,2,3,4,[5],6 ... 128
1287        if ($start < ($sectionSize * 2)) {
1288            $pages .= generatePaginationBlock($current, 1, $sectionSize * 2, $link, $navigations);
1289            $pages .= " ... ";
1290            $pages .= generatePaginationBlock($current, $pages_count-$sectionSize, $pages_count, $link, $navigations);
1291        } elseif ($start > ($pages_count - $sectionSize * 2 + 1)) {
1292            $pages .= generatePaginationBlock($current, 1, $sectionSize, $link, $navigations);
1293            $pages .= " ... ";
1294            $pages .= generatePaginationBlock($current, $pages_count-$sectionSize*2 + 1, $pages_count, $link, $navigations);
1295        } else {
1296            $pages .= generatePaginationBlock($current, 1, $sectionSize, $link, $navigations);
1297            $pages .= " ... ";
1298            $pages .= generatePaginationBlock($current, $cstart-1, $cstart+1, $link, $navigations);
1299            $pages .= " ... ";
1300            $pages .= generatePaginationBlock($current, $pages_count-$sectionSize, $pages_count, $link, $navigations);
1301        }
1302    } else {
1303        // If we have less then 10 pages
1304        $pages .= generatePaginationBlock($current, 1, $pages_count, $link, $navigations);
1305    }
1306    return $pages;
1307}
1308
1309
1310//
1311// Return user record by login
1312//
1313function locateUser($login) {
1314    global $mysql;
1315    if ($row = $mysql->record("select * from ".uprefix."_users where name = ".db_squote($login))) {
1316        return $row;
1317    }
1318    return array();
1319}
1320
1321
1322function GetCategoryById($id) {
1323    global $catz;
1324
1325    foreach ($catz as $cat) {
1326        if ($cat['id'] == $id) {
1327            return $cat;
1328        }
1329    }
1330    return array();
1331}
1332
1333
1334if (!function_exists('json_encode'))
1335{
1336  function json_encode($a=false)
1337  {
1338    if (is_null($a)) return 'null';
1339    if ($a === false) return 'false';
1340    if ($a === true) return 'true';
1341    if (is_scalar($a))
1342    {
1343      if (is_float($a))
1344      {
1345        // Always use "." for floats.
1346        return floatval(str_replace(",", ".", strval($a)));
1347      }
1348
1349      if (is_string($a))
1350      {
1351        static $jsonReplaces = array(array("\\", "/", "\n", "\t", "\r", "\b", "\f", '"'), array('\\\\', '\\/', '\\n', '\\t', '\\r', '\\b', '\\f', '\"'));
1352        return '"' . str_replace($jsonReplaces[0], $jsonReplaces[1], $a) . '"';
1353      }
1354      else
1355        return $a;
1356    }
1357    $isList = true;
1358    for ($i = 0, reset($a); $i < count($a); $i++, next($a))
1359    {
1360      if (key($a) !== $i)
1361      {
1362        $isList = false;
1363        break;
1364      }
1365    }
1366    $result = array();
1367    if ($isList)
1368    {
1369      foreach ($a as $v) $result[] = json_encode($v);
1370      return '[' . join(',', $result) . ']';
1371    }
1372    else
1373    {
1374      foreach ($a as $k => $v) $result[] = json_encode($k).':'.json_encode($v);
1375      return '{' . join(',', $result) . '}';
1376    }
1377  }
1378}
1379
1380// Parse params
1381function parseParams($paramLine){
1382
1383    // Start scanning
1384    // State:
1385    // 0 - waiting for name
1386    // 1 - scanning name
1387    // 2 - waiting for '='
1388    // 3 - waiting for value
1389    // 4 - scanning value
1390    // 5 - complete
1391    $state = 0;
1392    // 0 - no quotes activated
1393    // 1 - single quotes activated
1394    // 2 - double quotes activated
1395    $quotes = 0;
1396
1397    $keyName = '';
1398    $keyValue = '';
1399    $errorFlag = 0;
1400
1401    $keys = array();
1402
1403    for ($sI = 0; $sI < strlen($paramLine); $sI ++) {
1404        // act according current state
1405        $x = $paramLine{$sI};
1406
1407        switch ($state) {
1408            case 0:  if      ($x == "'") { $quotes = 1; $state = 1; $keyName = '';}
1409                     else if ($x == "'") { $quotes = 2; $state = 1; $keyName = ''; }
1410                     else if ((($x >='A')&&($x <='Z'))||(($x >='a')&&($x <='z'))) { $state = 1; $keyName = $x; }
1411                     break;
1412            case 1:  if ((($quotes == 1)&&($x == "'"))||(($quotes == 2)&&($x == '"'))) { $quotes = 0; $state=2; }
1413                     else if ((($x >='A')&&($x <='Z'))||(($x >='a')&&($x <='z'))) { $keyName .= $x; }
1414                     else if ($x == '=') { $state = 3; }
1415                     else if (($x == ' ')||($x == chr(9))) { $state = 2; }
1416                     else { $erorFlag = 1; }
1417                     break;
1418            case 2:  if ($x == '=') { $state = 3; }
1419                     else if (($x == ' ')||($x == chr(9))) { ; }
1420                     else { $errorFlag = 1; }
1421                     break;
1422            case 3:  if      ($x == "'") { $quotes = 1; $state = 4; $keyValue = '';}
1423                     else if ($x == '"') { $quotes = 2; $state = 4; $keyValue = ''; }
1424                     else if ((($x >='A')&&($x <='Z'))||(($x >='a')&&($x <='z'))) { $state = 4; $keyValue = $x; }
1425                     break;
1426            case 4:  if ((($quotes == 1)&&($x == "'"))||(($quotes == 2)&&($x == '"'))) { $quotes = 0; $state=5; }
1427                     else if (!$quotes &&  (($x == ' ')||($x == chr(9)))) { $state = 5; }
1428                     else { $keyValue .= $x; }
1429                     break;
1430        }
1431
1432        // Action in case when scanning is complete
1433        if ($state == 5) {
1434            $keys [ strtolower($keyName) ] = $keyValue;
1435            $state = 0;
1436        }
1437    }
1438
1439    // If we finished and we're in stete "scanning value" - register this field
1440    if ($state == 4) {
1441        $keys [ strtolower($keyName) ] = $keyValue;
1442        $state = 0;
1443    }
1444
1445    // If we have any other state - report an error
1446    if ($state) {
1447        $errorFlag = 1; // print "EF ($state)[".$paramLine."].";
1448    }
1449
1450    if ($errorFlag) {
1451        return -1;
1452    }
1453    return $keys;
1454}
1455
1456//
1457// Print output HTTP headers
1458//
1459function printHTTPheaders() {
1460    global $SYSTEM_FLAGS;
1461
1462    foreach ($SYSTEM_FLAGS['http.headers'] as $hkey => $hvalue) {
1463        @header($hkey.': '.$hvalue);
1464    }
1465}
Note: See TracBrowser for help on using the browser.