1<?php
2/**
3 * Automatic login - interface for admins
4 *
5 * @author Ondrej Machac <omachac@seznam.cz>
6 */
7
8
9
10if(!defined('DOKU_INC')) die();
11
12if(!defined('DOKU_PLUGIN')) define('DOKU_PLUGIN',DOKU_INC.'lib/plugins/');
13require_once(DOKU_PLUGIN.'admin.php');
14
15/**
16 * All DokuWiki plugins to extend the admin function
17 * need to inherit from this class
18 */
19class admin_plugin_autlogin extends DokuWiki_Admin_Plugin {
20
21
22   var $visitors = null; //from visit.php
23   var $acl = null; //from transl.php
24   var $rule = null; //from acl.auth.php
25   var $kolo;
26   var $ns;
27   var $current_item = null;
28   var $passw = "autlogin";
29/**
30   * return some info
31   */
32  function getInfo()
33   {
34    return array(
35      'author' => 'Ondrej Machac',
36      'email'  => 'omachac@seznam.cz',
37      'date'   => '2011-03-01',
38      'name'   => 'Automatic login',
39      'desc'   => 'Automatic login for host, who meets some criterion of performance.',
40      'url'    => 'http://dl.dropbox.com/u/26256434/autlogin.tgz',
41    );
42   }
43
44    /**
45     * return prompt for admin menu
46     */
47    function getMenuText($language)
48     {
49         return 'Automatic login';
50     }
51
52    /**
53     * return sort order for position in admin menu
54     */
55    function getMenuSort()
56     {
57        return 140;
58     }
59
60    function forAdminOnly() {
61          return false;
62      }
63
64
65  /**
66     * handle user request
67     *
68     * Initializes internal vars and handles modifications
69
70     */
71
72   function handle()
73    {
74    global $auth;
75    global $username;
76
77
78// namespace given?
79        if($_REQUEST['ns'] == '*'){
80            $this->ns = '*';
81        }else{
82            $this->ns = cleanID($_REQUEST['ns']);
83        }
84
85        if ($_REQUEST['current_ns']) {
86            $this->current_item = array('id' => cleanID($_REQUEST['current_ns']), 'type' => 'd');
87        } elseif ($_REQUEST['current_id']) {
88            $this->current_item = array('id' => cleanID($_REQUEST['current_id']), 'type' => 'f');
89        } elseif ($this->ns) {
90            $this->current_item = array('id' => $this->ns, 'type' => 'd');
91        } else {
92            $this->current_item = array('id' => $ID, 'type' => 'f');
93        }
94
95
96     if(isset($_REQUEST['cmd']) && checkSecurityToken()){
97
98        if(isset($_REQUEST['cmd']['visit'])) //if some host from visit.php was chosen
99         {
100           $who = $_REQUEST['select_visit']; //who host was chosen
101
102           if(isset($_REQUEST['radioselect']))  //finds out perm
103           {
104              $perm = $_REQUEST['radioselect'];
105              $coun = 0;
106               if(isset($_REQUEST['check1'])){  //finds out criteria
107                 $coun++;
108                 $IP = $_REQUEST['check1'];
109               }
110               if(isset($_REQUEST['check2'])) {
111                 $coun++;
112                 $WB = $_REQUEST['check2'];
113                 }
114               if(isset($_REQUEST['check3'])) {
115                  $coun++;
116                 $VERSION = $_REQUEST['check3'];
117                 }
118               if(isset($_REQUEST['check4']))   {
119                 $coun++;
120                 $EP = $_REQUEST['check4'];
121                 }
122               if(isset($_REQUEST['check5'])) {
123                 $coun++;
124                 $OS = $_REQUEST['check5'];
125                 }
126               if(!empty($_REQUEST['username'])){
127                 $username=$_REQUEST['username'];
128
129              }
130
131               if($coun != 0) // only if some item in criterai was chosen
132               $this->_save_user($who, $perm, $IP, $WB, $VERSION, $EP, $OS);
133
134           }
135         }
136
137       $r=0;
138      if(isset($_REQUEST['cmd']['update'])) //if some rule was update
139      {
140       if(isset($_REQUEST['del'])){
141        foreach((array)$_REQUEST['del'] as $stranka1 => $n1)
142           foreach($n1 as $alias1){
143          // remove all rules marked for deletion
144           $this->del_acl($alias1,$stranka1);//delete rule from acl.auth.php
145         }
146
147
148        $this->get_perm(); //read transl.php
149        $this->_actaulize(); //actualize it
150        $this->get_perm();  //read actual transl.php
151             //check if was change some number of perm
152       }
153
154       $this->get_acl(); //read acl.auth.php
155       $AUTH_ACL = file(DOKU_CONF.'acl.auth.php');
156       foreach($AUTH_ACL as $line){
157             if($line{0} == '#'){
158                 $lines[] = $line;
159             }else{
160                 break;
161             }
162       }
163      $save = join('\n',$lines);
164      if(!empty($this->rule))
165       {
166       foreach($this->rule as $page => $n1)
167         foreach ($n1 as $alias => $cislo)
168            {
169               $flags = 0;
170               $visit = substr($alias,0,1);
171               if($visit != '@'){ //only users, not groups
172               if(($_REQUEST[$alias.$page] > -1) && ($_REQUEST[$alias.$page] < 256)){
173               $perm = $_REQUEST[$alias.$page];
174               $flags = 1;
175               }
176
177               $user = auth_nameencode($alias);
178               $info = $auth->getUserData($user);
179               if($info === false){
180                     $exist = false;
181               }else{
182                    $groups = $info['grps'];
183                    $exist = true;
184
185            }
186
187               if(((auth_aclcheck($page,$alias,$groups)) != $perm) && $flags == 1){//if number was change
188                  $this->del_acl($alias,$page);//delete rule from acl.auth.php
189                  $this->add_acl($page,$alias,$perm);//add rule whit new number perm
190              }
191           }
192           }
193       }
194
195
196     }
197
198      if(isset($_REQUEST['cmd']['manual'])) //if some host was add manually
199       {
200          $line=array();
201          $flag = 0;
202          $counter = 0;
203          $perm = $_REQUEST['manualmanual'];
204
205          if(!empty($_REQUEST['id']))
206           $stranka = $_REQUEST['id'];
207          elseif(!empty($_REQUEST['ns']))
208           $stranka = $_REQUEST['ns'].":*";
209
210          if($stranka == "*:*")
211           $stranka = "*";
212      //choose a page and perm is more then EDIT? max right is EDIT
213           if(substr($stranka,strlen($stranka)-1,1) != '*' && $perm > AUTH_EDIT)
214            $perm = AUTH_EDIT;
215          //save criterions
216          if(!empty($_REQUEST['ip_address'])){
217              if($this->control_ip($_REQUEST['ip_address']) == 1){
218                 $lines[]="IP=".$_REQUEST['ip_address'];
219                 $counter++;
220              }
221              else $flag=1;
222          }
223          if(!empty($_REQUEST['browser'])){
224
225                 $lines[]="WB=".$_REQUEST['browser'];
226                 $counter++;
227              }
228
229          if(!empty($_REQUEST['version'])){
230                 $lines[]="VER=".$_REQUEST['version'];
231                 $counter++;
232             }
233
234          if(!empty($_REQUEST['e_page'])){
235              if($this->control_page($_REQUEST['e_page'])){
236                 $lines[]="EP=".$_REQUEST['e_page'];
237                 $counter++;
238             }
239              else $flag=1;
240          }
241          if(!empty($_REQUEST['os'])){
242                 $lines[]="OS=".$_REQUEST['os'];
243                 $counter++;
244              }
245
246          if(!empty($_REQUEST['username'])){
247                 $username=$_REQUEST['username'];
248
249              }
250
251
252
253          if($flag == 0 && $counter > 0){
254              $line = join(',',$lines);
255              $this->save($stranka, $line, $perm);//save user
256          }
257
258       }
259
260
261     if(isset($_REQUEST['cmd']['moderator'])) //set moderator
262      {
263         $same = false;
264         $save='';
265         $user=$_REQUEST['select_user'];
266         if(!empty($_REQUEST['id']))
267           $page = $_REQUEST['id'];
268          elseif(!empty($_REQUEST['ns']))
269           $page = $_REQUEST['ns'].":*";
270         if($page == "*:*")
271           $page = "*";
272
273         $moderators = file(DOKU_PLUGIN.'/autlogin/settings/moderators.php');
274
275         foreach($moderators as $line){
276            $unit = preg_split('/\s+/',$line);
277            if($unit[0]==$user && $unit[1]==$page)
278              $same = true;   //already exist
279          }
280         if($same == false){ //only if dont exist the same line
281            $moderators = file_get_contents(DOKU_PLUGIN.'/autlogin/settings/moderators.php');
282            $save = "$user\t$page\n";
283            $moderators.= $save;
284            io_saveFile(DOKU_PLUGIN.'/autlogin/settings/moderators.php', $moderators);
285            $this->add_group($user); //add group 'moderator' to $user
286         }
287      }
288
289
290       if(isset($_REQUEST['cmd']['update_mod'])) //if some moderators was update
291        {
292         if(isset($_REQUEST['del_m'])){
293
294          foreach((array)$_REQUEST['del_m'] as $stranka1 => $n1)
295             foreach($n1 as $alias1){
296            // remove all rules marked for deletion
297                $acl_config = file(DOKU_PLUGIN.'/autlogin/settings/moderators.php');
298                $acl_user = auth_nameencode($alias1,true);
299
300                $acl_pattern = '^'.$acl_user.'\s+'.preg_quote($stranka1,'/').'*$';
301
302                // save all non!-matching
303                $new_config = preg_grep("/$acl_pattern/", $acl_config, PREG_GREP_INVERT);
304
305                io_saveFile(DOKU_PLUGIN.'/autlogin/settings/moderators.php', join('',$new_config));
306
307                $acl_config= file_get_contents(DOKU_PLUGIN.'/autlogin/settings/moderators.php');
308                $pozice = StrPos($acl_config, $alias1);
309                if($pozice === false)//no moderator rule set
310                 $this->del_group($alias1); //remove group moderator
311              }
312            }
313
314
315         }
316
317        if(isset($_REQUEST['cmd']['set_mod'])) //set rights
318         {
319              $page = $_REQUEST['select_mod_page'];
320              $alias =$_REQUEST['select_user'];
321              $perm = $_REQUEST['manualmanual'];
322              $number = -1;
323              $save='';
324
325              if(substr($page,strlen($page)-1,1) != '*' && $perm > AUTH_EDIT)
326               $perm = AUTH_EDIT;
327
328              $this->get_perm(); //read transl.php
329              //exist the same rule?
330              if(!empty($this->acl))
331               {
332               foreach($this->acl as $stranka => $n1)
333                 foreach ($n1 as $kriterium => $n2)
334                  foreach ($n2 as $jmeno => $cislo)
335                  {
336
337                    if($stranka == $page && $alias == $jmeno){ //actualize number
338                      $save.= "$stranka\t$kriterium\t$jmeno\t$perm\n";
339                      $number = 0;
340                    }
341                    else
342                      $save.= "$stranka\t$kriterium\t$jmeno\t$cislo\n";
343                  }
344
345               }
346             io_saveFile(DOKU_PLUGIN.'/autlogin/settings/transl.php',$save);
347
348             if ($number == 0){ //same rule only different perm number
349                 $this->del_acl($alias,$page);//delete rule from acl.auth.php
350                 $this->add_acl($page,$alias,$perm);//add rule whit new number perm
351             }
352             elseif($number == -1)//new rule
353                 $visit = $this->_find_visit($alias);
354                 if(!$visit)
355                  $noexist = 1;
356                 $new = "$page\t$visit\t$alias\t$perm\n";
357                 $ACTUAL_ACL = file_get_contents(DOKU_PLUGIN.'/autlogin/settings/transl.php');
358                 $ACTUAL_ACL.= $new;
359                 io_saveFile(DOKU_PLUGIN.'/autlogin/settings/transl.php',$ACTUAL_ACL);
360                 $this->add_acl($page,$alias,$perm);//add rule whit new number perm
361
362        if($noexist){//add new rule for user, who is not a member of autlogin group
363           $this->del_acl($alias,$page);//delete rule from acl.auth.php
364           $this->add_acl($page,$alias,$perm);//add rule whit new number perm
365
366        }
367
368
369        }
370
371
372
373     }
374
375
376     $this->get_visit();
377     $this->get_perm(); //read transl.php
378     $this->_actaulize(); //actualize it
379     $this->get_perm();  //read actual transl.php
380     $this->clear_users();//remove all users, who are registered in users.auth.php but are not use in transl.php
381
382 }
383
384   function html()
385    {
386    global $ID;
387    global $conf;
388    global $USERINFO;
389
390
391              echo '<div id="auth_manager">'.NL;  // 1
392
393
394       if(auth_isadmin())  {
395
396
397              echo '<h1>'.$this->getLang('admin_auth').'</h1>'.NL;
398              echo '<a name="ZALOZKY">'.$this->getLang('select_page').'</a>';
399              echo '<br>';
400              echo '<div id="acl__tree">'.NL;
401              $this->_html_explorer();
402              echo '</div>';
403              echo '<fieldset style="width: 100%; text-align: left">';
404              echo '<legend>'.$this->getLang('from_visit').'</legend>';
405
406              echo '<div id="auth1__detail">'.NL;
407              $this->_select();
408              echo '</div>'.NL;
409              echo '</fieldset>';
410              echo '<br><br>';
411              echo '<fieldset style="width: 100%; text-align: left">';
412              echo '<legend>'.$this->getLang('from_manual').'</legend>';
413
414              echo '<div id="auth2__detail">'.NL;
415              $this->_manual_acl();
416              echo '</div>'.NL;
417              echo '</fieldset>';
418
419              echo '<br><br>';
420              echo '<fieldset style="width: 100%; text-align: left">';
421              echo '<legend>'.$this->getLang('from_table').'</legend>';
422              echo '<div id="auth__table">'.NL;
423
424              $data = $this->_get_all_pages();
425              $count = count($data);
426
427              if($count>0) for($i=0; $i<$count; $i++){
428              $pages[]=$data[$i]['id'];
429              }
430              $this->_table($pages);
431              echo '</div>'.NL;
432              echo '</fieldset>';
433
434              echo '<br><br>';
435              echo '<fieldset style="width: 100%; text-align: left">';
436              echo '<legend>'.$this->getLang('from_manage').'</legend>';
437              echo '<div id="auth3__detail">'.NL;
438              $this->_manage();
439              echo '</div>'.NL;
440
441              echo '<br><br>';
442              $this->_table_moderator();
443              echo '</fieldset>';
444
445      }
446       if(auth_ismanager()){
447              echo '<h1>'.$this->getLang('moderator_auth').'</h1>'.NL;
448              echo '<fieldset style="width: 100%; text-align: left"">';
449              echo '<legend>'.$this->getLang('mod_menu').'</legend>';
450              $this->_set_moderator();
451              echo '</fieldset>';
452
453
454              echo '<br><br>';
455              echo '<fieldset style="width: 100%; text-align: left">';
456              echo '<legend>'.$this->getLang('mod_table').'</legend>';
457              echo '<div id="mod__set">'.NL;
458              $user = $_SERVER['REMOTE_USER'];
459              $data = $this->_get_pages($user);
460              $datas= $this->_parse_ns($data);
461              $this->_table($datas);
462              echo '</div>'.NL;
463              echo '</fieldset>';
464       }
465              echo '<div class="footnotes"><div class="fn">'.NL;
466              echo '<sup><a id="fn__1" class="fn_bot" name="fn__1" href="#fnt__1">1)</a></sup>'.NL;
467              echo $this->getLang('p_include');
468              echo '</div>';
469              echo '<div class="fn">'.NL;
470              echo '<sup><a id="fn__2" class="fn_bot" name="fn__2" href="#fnt__2">2)</a></sup>'.NL;
471              echo $this->getLang('max_right');
472              echo '</div></div>';
473
474              echo '</div>'.NL; // 1
475
476    }
477
478
479
480    /**
481     * Print a visitor's selector
482     */
483 function _select()
484   {
485        global $ID;
486
487
488      echo '<form action="'.wl().'" method="post" accept-charset="utf-8"><div class="no">'.NL;
489      echo '<div id="auth__select">';
490      echo '<select name="select_visit" class="edit">'.NL;
491
492        foreach($this->visitors as $datum => $n1)
493          foreach($n1 as $stranka => $kriteria)
494          {
495               $kriteria = rawurldecode($kriteria);
496               echo '  <option value="'.$datum.'">'.$datum." &lt ".$stranka." &gt  ".$kriteria.'</option>'.NL;
497          }
498
499        echo '</select>'.NL;
500        echo '<br><br>';
501        //enter alias
502        echo $this->getLang('username').'<sup><a id="fnt__1" class="fn_top" name="fnt__1" href="#fn__1">1)</a></sup>';
503        echo '<input type="text" name="username" size="20"></input>&nbsp;';
504        echo '<br><br>';
505
506        echo $this->_kriterium();
507        echo '<br><br>';
508        echo $this->getLang('right');
509        echo $this->_radio('','radio','select');
510        echo '<br><br>';
511        echo '<input type="submit" value="'.$this->getLang('btn_select').'" name="cmd[visit]" class="button" />';
512        echo '</div>'.NL;
513
514        echo '<input type="hidden" name="ns" value="'.hsc($this->ns).'" />'.NL;
515        echo '<input type="hidden" name="id" value="'.hsc($ID).'" />'.NL;
516        echo '<input type="hidden" name="do" value="admin" />'.NL;
517        echo '<input type="hidden" name="page" value="autlogin" />'.NL;
518        echo '<input type="hidden" name="sectok" value="'.getSecurityToken().'" />'.NL;
519         echo '</div></form>'.NL;
520
521   }
522
523
524  //its possible set rights manually
525  function _manual_acl()
526   {
527        global $ID;
528        global $conf;
529
530        echo '<form action="'.wl().'" method="post" accept-charset="utf-8"><div class="no">'.NL;
531        echo '<div id="auth__manual">';
532
533        //enter alias
534        echo $this->getLang('username').'<sup><a id="fnt__1" class="fn_top" name="fnt__1" href="#fn__1">1)</a></sup>';
535        echo '<input type="text" name="username" size="20"></input>&nbsp;';
536
537        echo '<a href="#ZALOZKY">'.$this->getLang('help_page').'</a>';
538
539        //enter IP adress
540        echo '<br><br>';
541        echo $this->getLang('set_ip');
542        echo '<input type="text" name="ip_address" size="20"></input>&nbsp;';
543
544        // display select for choose web browsers (from browsers.php)
545        $webs = $this->load_browser();
546        echo $this->getLang('set_browser');
547        echo '<select name="browser" class="edit">'.NL;
548        echo '  <option value=""></option>'.NL; //empty row
549        $count = count($webs);
550        if($count>0) for($i=0; $i<$count; $i++){
551         echo '  <option value="'.$webs[$i].'">'.$webs[$i].'</option>'.NL;
552         }
553        echo '</select>'.NL;
554
555        //enter verion
556        echo $this->getLang('set_version');
557        echo '<input type="text" name="version" size="20"></input>&nbsp;';
558        echo '<br><br>';
559        echo $this->getLang('set_page');
560        echo '<input type="text" name="e_page" size="30"></input>&nbsp;';
561
562
563        //select for choose the operation system (from systems.php)
564        $systems = $this->load_system();
565        echo $this->getLang('set_os');
566        echo '<select name="os" class="edit">'.NL;
567        echo '  <option value=""></option>'.NL;      //first empty row
568        $count = count($systems);
569        if($count>0) for($i=0; $i<$count; $i++){
570         echo '  <option value="'.$systems[$i].'">'.$systems[$i].'</option>'.NL;
571         }
572        echo '</select>'.NL;
573
574        echo '<br><br>';
575        echo $this->getLang('right').'<sup><a id="fnt__2" class="fn_top" name="fnt__2" href="#fn__2">2)</a></sup>';
576        echo $this->_radio('','manual','manual'); //number of permission
577        echo '<br><br>';
578        echo '</div>'.NL;
579        echo '<input type="submit" value="'.$this->getLang('btn_select').'" name="cmd[manual]" class="button" />';
580        echo '<input type="hidden" name="ns" value="'.hsc($this->ns).'" />'.NL;
581        echo '<input type="hidden" name="id" value="'.hsc($ID).'" />'.NL;
582        echo '<input type="hidden" name="do" value="admin" />'.NL;
583        echo '<input type="hidden" name="page" value="autlogin" />'.NL;
584        echo '<input type="hidden" name="sectok" value="'.getSecurityToken().'" />'.NL;
585
586        echo '</div></form>'.NL;
587   }
588
589
590
591  //this function write to table exist rules
592  function _table($data)
593   {
594
595        global $ID;
596
597        $this->get_perm();
598        $this->_actaulize(); //actualize it
599        $this->get_perm();  //read actual transl.php
600
601        echo '<form action="'.wl().'" method="post" accept-charset="utf-8"><div class="no">'.NL;
602        echo '<input type="hidden" name="ns" value="'.hsc($this->ns).'" />'.NL;
603        echo '<input type="hidden" name="id" value="'.$ID.'" />'.NL;
604        echo '<input type="hidden" name="do" value="admin" />'.NL;
605        echo '<input type="hidden" name="page" value="autlogin" />'.NL;
606        echo '<input type="hidden" name="sectok" value="'.getSecurityToken().'" />'.NL;
607        echo '<table class="inline">';
608        echo '<tr>';
609        echo '<th>'.$this->getLang('where').'</th>';
610        echo '<th>'.$this->getLang('who').'</th>';
611        echo '<th>'.$this->getLang('kriteria').'</th>';
612        echo '<th>'.$this->getLang('perm').'</th>';
613        echo '<th>'.$this->getLang('delete').'</th>';
614        echo '</tr>';
615        $this->get_acl();
616         if(!empty($this->rule))
617         {
618          foreach($this->rule as $stranka => $n1)
619            foreach ($n1 as $alias => $cislo)
620            if(substr($alias,0,1) != "@"){
621
622            {
623             if(in_array($stranka,$data)){
624              $kriterium = $this->_find_visit($alias);
625               $kriterium = rawurldecode($kriterium);
626                echo '<tr>';
627                echo '<td>';
628                echo '<span class="aclns">'.$stranka.'</span>';
629                echo '</td>';
630                echo '<td>';
631                echo '<span class="aclns">'.$alias.'</span>';
632                echo '</td>';
633                echo '<td>';
634                if($kriterium)
635                echo '<span class="aclns">'.$kriterium.'</span>';
636                else
637                echo '<span class="aclns">'.$this->getLang('novisit').'</span>';
638                echo '</td>';
639                echo '<td>';
640                echo $this->_radio($cislo,$alias,$stranka);
641                echo '</td>';
642
643                echo '<td align="center">';
644                echo '<input type="checkbox" name="del['.$stranka.'][]" value="'.$alias.'" />';
645                echo '</td>';
646                echo '</tr>';
647
648            }
649           }
650          }}
651
652        echo '<tr>';
653        echo '<th align="right" colspan="4">';
654        echo '<input type="submit" value="'.$this->getLang('update').'" name="cmd[update]" class="button" />';
655        echo '</th>';
656        echo '</tr>';
657        echo '</table>';
658        echo '</div></form>'.NL;
659
660   }
661
662   //print moderators
663   function _table_moderator()
664    {
665        global $ID;
666
667
668        echo '<form action="'.wl().'" method="post" accept-charset="utf-8"><div class="no">'.NL;
669        echo '<input type="hidden" name="ns" value="'.hsc($this->ns).'" />'.NL;
670        echo '<input type="hidden" name="id" value="'.$ID.'" />'.NL;
671        echo '<input type="hidden" name="do" value="admin" />'.NL;
672        echo '<input type="hidden" name="page" value="autlogin" />'.NL;
673        echo '<input type="hidden" name="sectok" value="'.getSecurityToken().'" />'.NL;
674        echo '<table class="inline">';
675        echo '<tr>';
676        echo '<th>'.$this->getLang('where').'</th>';
677        echo '<th>'.$this->getLang('who_m').'</th>';
678        echo '<th>'.$this->getLang('delete').'</th>';
679        echo '</tr>';
680         $actual_moderator = file(DOKU_PLUGIN.'/autlogin/settings/moderators.php');
681        foreach($actual_moderator as $line)
682         {
683             $user = preg_split('/\s+/',$line);
684             $stranka = $user[1];
685             $alias = $user[0];
686
687                echo '<tr>';
688                echo '<td>';
689                echo '<span class="aclns">'.$stranka.'</span>';
690                echo '</td>';
691                echo '<td>';
692                echo '<span class="aclns">'.$alias.'</span>';
693                echo '</td>';
694
695                echo '<td align="center">';
696                echo '<input type="checkbox" name="del_m['.$stranka.'][]" value="'.$alias.'" />';
697                echo '</td>';
698                echo '</tr>';
699            }
700
701
702        echo '<tr>';
703        echo '<th align="right" colspan="4">';
704        echo '<input type="submit" value="'.$this->getLang('update').'" name="cmd[update_mod]" class="button" />';
705        echo '</th>';
706        echo '</tr>';
707        echo '</table>';
708        echo '</div></form>'.NL;
709
710    }
711
712   //set moderators
713   function _manage()
714    {
715      global $ID;
716
717        echo '<form action="'.wl().'" method="post" accept-charset="utf-8"><div class="no">'.NL;
718
719        $user = $this->get_users(); //load all users and display them
720        $count = count($user);
721        echo $this->getLang('s_user');
722        echo '<select name="select_user" class="edit">'.NL;
723        if($count>0) for($i=0; $i<$count; $i++){
724         echo '  <option value="'.$user[$i].'">'.$user[$i].'</option>'.NL;
725         }
726        echo '</select>'.NL;
727
728        echo '<a href="#ZALOZKY">'.$this->getLang('help_page').'</a>&nbsp;';
729
730        echo '<input type="submit" value="'.$this->getLang('btn_select').'" name="cmd[moderator]" class="button" />';
731        echo '<input type="hidden" name="ns" value="'.hsc($this->ns).'" />'.NL;
732        echo '<input type="hidden" name="id" value="'.hsc($ID).'" />'.NL;
733        echo '<input type="hidden" name="do" value="admin" />'.NL;
734        echo '<input type="hidden" name="page" value="autlogin" />'.NL;
735        echo '<input type="hidden" name="sectok" value="'.getSecurityToken().'" />'.NL;
736        echo '</div></form>'.NL;
737  }
738
739
740  //print set rights, bud only for some page
741  function _set_moderator()
742   {
743
744        echo '<form action="'.wl().'" method="post" accept-charset="utf-8"><div class="no">'.NL;
745        echo '<div id="auth__set_mod">';
746        $user = $_SERVER['REMOTE_USER'];
747        $data = $this->_get_pages($user);
748
749
750        $pages=$this->_parse_ns($data);
751
752
753        $count = count($pages);
754
755        echo $this->getLang('s_page');
756        echo '<select name="select_mod_page" class="edit">'.NL;
757        if($count>0) for($i=0; $i<$count; $i++){
758         echo '  <option value="'.$pages[$i].'">'.$pages[$i].'</option>'.NL;
759         }
760        echo '</select>'.NL;
761
762        $user = $this->get_users(); //load all users and display them
763        $count = count($user);
764        echo $this->getLang('mod_user');
765        echo '<select name="select_user" class="edit">'.NL;
766        if($count>0) for($i=0; $i<$count; $i++){
767         echo '  <option value="'.$user[$i].'">'.$user[$i].'</option>'.NL;
768         }
769        echo '</select>'.NL;
770
771        echo $this->getLang('right').'<sup><a id="fnt__2" class="fn_top" name="fnt__2" href="#fn__2">2)</a></sup>';
772        echo $this->_radio('','manual','manual'); //number of permission
773
774
775        echo '<input type="submit" value="'.$this->getLang('btn_select').'" name="cmd[set_mod]" class="button" />';
776        echo '</div>'.NL;
777        echo '<input type="hidden" name="ns" value="'.hsc($this->ns).'" />'.NL;
778        echo '<input type="hidden" name="id" value="'.$ID.'" />'.NL;
779        echo '<input type="hidden" name="do" value="admin" />'.NL;
780        echo '<input type="hidden" name="page" value="autlogin" />'.NL;
781        echo '<input type="hidden" name="sectok" value="'.getSecurityToken().'" />'.NL;
782        echo '</div></form>'.NL;
783   }
784
785
786
787
788   function _radio($cislo,$jmeno,$stranka)
789    {
790
791     static $label = 0; //number labels
792     $ret = '';
793        foreach(array(AUTH_NONE,AUTH_READ,AUTH_EDIT,AUTH_CREATE,AUTH_UPLOAD,AUTH_DELETE) as $perm){
794            $label += 1;
795
796            //general checkbox attributes
797            $atts = array( 'type'  => 'radio',
798                           'id'    => 'pbox'.$label,
799                           'name'  => $jmeno.$stranka,
800                           'value' => $perm );
801
802            if($cislo == $perm) $atts['checked']  = 'checked';
803            if((substr($stranka,strlen($stranka)-1,1) != '*' && $perm > AUTH_EDIT) || ($stranka == 'select' && $perm > AUTH_EDIT))
804             $atts['disabled'] = 'disabled';
805            if($stranka == 'manual')
806             unset($atts['disabled']);
807            //build code
808            $ret .= '<label for="pbox'.$label.'" title="'.$this->getLang('acl_perm'.$perm).'">';
809            $ret .= '<input '.html_attbuild($atts).' />&nbsp;';
810            $ret .= $this->getLang('acl_perm'.$perm);
811            $ret .= '</label>'.NL;
812        }
813        return $ret;
814    }
815
816
817
818
819  function _kriterium()
820   {
821
822   static $label = 0; //number labels
823     $ret = '';
824      foreach(array(IP, BROWSER, VERSION, ENTRY_PAGE, OS) as $type){
825            $label += 1;
826
827            //general checkbox attributes
828            $atts = array( 'type'  => 'checkbox',
829                           'id'    => 'chbox'.$label,
830                           'name'  => 'check'.$label,
831                           'value' => $type );
832
833            if($cislo == $type) $atts['checked']  = 'checked';
834            //build code
835            $ret .= '<label for="chbox'.$label.'" title="'.$this->getLang($type).'">';
836            $ret .= '<input '.html_attbuild($atts).' />&nbsp;';
837            $ret .= $this->getLang($type);
838            $ret .= '</label>'.NL;
839        }
840       return $ret;
841
842   }
843
844
845
846
847 /*
848 $who .... what host will by save
849 $perm ... number of permission
850 $ip ... ip address
851 $wb ... web browser
852 $version .. version of wb
853 $ep ... entry page
854 $os ... operating system
855 */
856
857  function _save_user($who, $perm, $IP, $WB, $VERSION, $EP, $OS)
858    {
859
860
861      $this->get_visit();
862
863      //now find the right host
864      foreach($this->visitors as $datum => $n1)
865       foreach($n1 as $page1 => $criteria)
866        {
867         if ($who == $datum)
868          {
869           $kriterium = $criteria;
870           $stranka = $page1;
871          }
872        }
873
874        $rules = preg_split('/,/',$kriterium);
875
876        if(isset($IP)) //if is set IP addres
877         {
878           foreach($rules as $now)  //parse concrete ip
879            if(preg_match("(IP=)",$now))
880              {
881              $concr_ip = $now ;    //save concrete ip
882              }
883         }
884
885
886         if(isset($WB))
887          {
888            foreach($rules as $now)
889             if(preg_match("(WB=)",$now))
890              {
891              $concr_wb = $now;    //save concrete WB
892              }
893          }
894
895        if(isset($VERSION)) //if is set IP addres
896         {
897           foreach($rules as $now)
898             if(preg_match("(VER=)",$now))
899              {
900              $concr_ver = $now;    //save concrete WB
901              }
902         }
903
904        if(isset($EP))
905          {
906            foreach($rules as $now)
907             if(preg_match("(EP=)",$now))
908              {
909              $concr_ep = $now ;    //save concrete WB
910              }
911          }
912
913         if(isset($OS))
914          {
915            foreach($rules as $now)
916             if(preg_match("(OS=)",$now))
917              {
918              $concr_os = $now;    //save concrete WB
919              }
920          }
921
922          if(!empty($concr_ip))
923           $visit.=$concr_ip.",";
924          if(!empty($concr_wb))
925           $visit.=$concr_wb.",";
926          if(!empty($concr_ver))
927           $visit.=$concr_ver.",";
928          if(!empty($concr_ep))
929           $visit.=$concr_ep.",";
930          if(!empty($concr_os))
931           $visit.=$concr_os;
932          if(empty($concr_os))
933           $visit = substr($visit,0,(strlen($visit)-1)); //erase last ","
934
935
936          $this->save($stranka,$visit,$perm);
937
938
939
940
941    }
942
943  // $stranka = name of page
944  // $visit = criteria
945  // $perm = number of permission
946 function save($stranka,$visit,$perm)
947  {
948     global $auth;
949     global $username;
950     $already = false; //same criteria, but other page
951     $same = false;  //the same rule yet exist
952
953   //already exist same page whit same criteria ??
954         $this->get_perm(); //read transl.php
955         if(!empty($this->acl))
956         {
957            foreach($this->acl as $page => $n1)
958              foreach ($n1 as $kriterium => $n2)
959               foreach ($n2 as $alias => $cislo)
960                 {
961
962                  if(($page == $stranka) && ($kriterium == $visit))
963                  {
964                   $same = true;   // already exist?
965
966                  }
967                  // same sriteria but for different page
968                  elseif(($kriterium == $visit) && ($page != $stranka ))
969                  {
970
971                   $already = true;
972                   $concr_alias = $alias;
973                  }
974                 }
975
976          }
977
978
979          //new user
980          if(($already == false) && ($same == false))
981           {
982             if(isset($username)){
983              $crit=$this->_find_visit($username);
984              if($crit)
985                $username.="2";
986             }
987
988             if(!isset($username))
989               $concr_alias = $this->rand_alias();
990             else
991               $concr_alias = $username;
992
993             $name = 'plugin autlogin';
994             $email = $concr_alias.'@false.cz';
995             $grps[] = 'autlogin';
996             if (!$auth->canDo('addUser')) return false;
997             $auth->triggerUserMod('create', array($concr_alias,$passw,$name,$email,$grps));//cretae new user
998
999           }
1000
1001          //if exist the same criteria, but for other page, save as the same alias
1002         if($same == false)
1003           {
1004             $save='';
1005             $save = "$stranka\t$visit\t$concr_alias\t$perm\n";
1006             $ACTUAL_ACL = file_get_contents(DOKU_PLUGIN.'/autlogin/settings/transl.php');
1007             $ACTUAL_ACL.= $save;
1008             io_saveFile(DOKU_PLUGIN.'/autlogin/settings/transl.php',$ACTUAL_ACL);
1009             $this->add_acl($stranka,$concr_alias,$perm);
1010           }
1011
1012  }
1013
1014    /*
1015 ********************************
1016 *********************************
1017 *********************************
1018 */
1019
1020
1021 //load info from visit.php
1022  function get_visit()
1023   {
1024
1025
1026    $ACT_VISIT = file(DOKU_PLUGIN.'/autlogin/settings/visit.php');
1027    foreach($ACT_VISIT as $line){
1028            $line = trim(preg_replace('/#.*$/','',$line)); //ignore comments
1029            if(!$line) continue;
1030
1031            $acl = preg_split('/\s+/',$line);
1032            //0 is page, 1 kriterium, 2 alias, 3 is acl
1033
1034            //$acl[2] = rawurldecode($acl[2]);
1035            $acl_config[$acl[0]][$acl[1]] = $acl[2];
1036        }
1037        $this->visitors = $acl_config;
1038
1039
1040   }
1041
1042
1043     //load actual setttings store in transl.php
1044  function get_acl()
1045  {
1046     $ACTUAL_ACL = file(DOKU_CONF.'acl.auth.php');
1047
1048
1049        foreach($ACTUAL_ACL as $line){
1050            $line = trim(preg_replace('/#.*$/','',$line)); //ignore comments
1051            if(!$line) continue;
1052
1053            $acl = preg_split('/\s+/',$line);
1054            //0 is page, 1 criteria, 2 alias, 3 is acl
1055
1056            //$acl[1] = rawurldecode($acl[1]);
1057            $acl_config[$acl[0]][$acl[1]] = $acl[2];
1058        }
1059        $this->rule = $acl_config;
1060 }
1061
1062
1063     //load actual setttings store in transl.php
1064  function get_perm()
1065  {
1066     $ACTUAL_ACL = file(DOKU_PLUGIN.'/autlogin/settings/transl.php');
1067
1068
1069        foreach($ACTUAL_ACL as $line){
1070            $line = trim(preg_replace('/#.*$/','',$line)); //ignore comments
1071            if(!$line) continue;
1072
1073            $acl = preg_split('/\s+/',$line);
1074            //0 is page, 1 criteria, 2 alias, 3 is acl
1075
1076            //$acl[1] = rawurldecode($acl[1]);
1077            $acl_config[$acl[0]][$acl[1]][$acl[2]] = $acl[3];
1078        }
1079        $this->acl = $acl_config;
1080 }
1081
1082
1083
1084/*This function actualize file transl.php
1085**if some change was made in acl plugin
1086**this change must write it to transl.php
1087*/
1088 function _actaulize()
1089  {
1090      global $conf;
1091
1092         $users = $this->get_users_autlogin();
1093
1094        $data = $this->_get_all_pages();
1095         $count = count($data);
1096         if($count>0) for($i=0; $i<$count; $i++){
1097            $pages[]=$data[$i]['id'];
1098            }
1099
1100       $AUTH_ACL = file(DOKU_CONF.'acl.auth.php');
1101
1102       if($users && $pages){
1103       foreach($users as $user)
1104        foreach($pages as $page)
1105          {
1106              $matches = preg_grep('/^'.preg_quote($page,'/').'\s+('.$user.')\s+/'.$ci,$AUTH_ACL);
1107
1108              if(count($matches)){
1109                 foreach($matches as $match){
1110
1111                     $match = preg_replace('/#.*$/','',$match); //ignore comments
1112                     $acll   = preg_split('/\s+/',$match);
1113
1114                     $perm = $acll[2];
1115
1116                 }
1117                 if($perm > -1){
1118                 $visit= $this->_find_visit($user);
1119                     //we had a match - return it
1120                $save.= "$page\t$visit\t$user\t$perm\n";
1121                 }
1122               }
1123
1124          }
1125
1126    io_saveFile(DOKU_PLUGIN.'/autlogin/settings/transl.php',$save);
1127     }
1128  }
1129
1130
1131 //return all pages and namespaces
1132 function _get_all_pages()
1133  {
1134   global $conf;
1135        $data = array();
1136
1137           $dir = '';
1138         $media = array();
1139         $opts['skipacl'] = 0; // no ACL skipping
1140         search($data, $conf['datadir'], 'search_allpages', $opts, $dir);
1141         search($media, $conf['datadir'], 'search_namespaces', $opts, $dir);
1142         $count = count($media);
1143         if($count>0) for($i=0; $i<$count; $i++)
1144            $media[$i]['id']=$media[$i]['id'].":*";
1145         $media[$i+1]['id']="*";
1146         $data = array_merge($data,$media);
1147         return $data;
1148  }
1149
1150  //remove all users, who are registered in users.auth.php but are not use in transl.php
1151  // and are in authlogin group
1152  function clear_users()
1153   {
1154   $user_config=array();
1155
1156    $actual_users = file(DOKU_CONF.'users.auth.php');
1157
1158       foreach($actual_users as $line){
1159            $line = trim(preg_replace('/#.*$/','',$line)); //ignore comments
1160            if(!$line) continue;
1161
1162            $user = preg_split('/:/',$line);
1163            //0 is user, 1 psswr, 2 real name, 3 email, 4 are groups
1164
1165      //store all users when one of group is authlogin
1166            $user2 = preg_split('/,/',$user[4]);
1167            foreach($user2 as $group)
1168            if($group == 'autlogin')
1169            {
1170              $user_config[] = $user[0];
1171            }
1172        }
1173
1174        $this->get_perm;
1175         if(!empty($this->acl))
1176          {
1177           foreach($this->acl as $page => $n1)
1178            foreach ($n1 as $kriterium => $n2)
1179              foreach ($n2 as $alias => $cislo)
1180               {
1181               //erase all hosts who are use in transl.php
1182               if(in_array($alias, $user_config)){
1183
1184                $count = count($user_config);
1185                if($count>0)
1186
1187                for($i=0; $i<$count; $i++){
1188                 if($user_config[$i] == $alias)
1189                  $user_config[$i]= '';
1190                }
1191
1192               }
1193              }
1194          }
1195    //now are in $user_config store all host who ar not active
1196
1197       $new_user = '';
1198         $actual_users = file(DOKU_CONF.'users.auth.php');
1199       foreach($actual_users as $line)
1200       {
1201            if(($pozice = SubStr($line,0,1)) == '#')
1202              $new_user.=$line;
1203
1204            $line = trim(preg_replace('/#.*$/','',$line)); //ignore comments
1205            if(!$line) continue;
1206
1207            $user = preg_split('/:/',$line);
1208            //0 is user, 1 psswr, 2 real name, 3 email, 4 are groups
1209            if(!in_array($user[0],$user_config))
1210             $new_user.=$line."\n";
1211       }
1212       //clear not exist moderators
1213      $new_moderator = '';
1214      $actual_moderator = file(DOKU_PLUGIN.'/autlogin/settings/moderators.php');
1215      foreach($actual_moderator as $line)
1216        {
1217             $user  = preg_split('/\s+/',$line);
1218             if(!in_array($user[0],$user_config))
1219               $new_moderator.=$line;
1220        }
1221
1222      io_saveFile(DOKU_PLUGIN.'/autlogin/settings/moderators.php',$new_moderator);
1223      io_saveFile(DOKU_CONF.'users.auth.php',$new_user);
1224
1225
1226   }
1227
1228//add moderator group to user $moderator
1229 function add_group($moderator)
1230  {
1231
1232  $flag = 0;
1233  $actual_users = file(DOKU_CONF.'users.auth.php');
1234       foreach($actual_users as $line)
1235       {
1236            if(($pozice = SubStr($line,0,1)) == '#')
1237              $new_user.=$line;
1238
1239            $line = trim(preg_replace('/#.*$/','',$line)); //ignore comments
1240            if(!$line) continue;
1241
1242            $user = preg_split('/:/',$line);
1243            //0 is user, 1 psswr, 2 real name, 3 email, 4 are groups
1244            if(($user[0] != $moderator))
1245             $new_user.=$line."\n";
1246            else
1247             {
1248              $grps = preg_split('/,/',$user[4]);
1249              foreach($grps as $group)
1250                if($group == 'moderator')
1251                 $flag = 1;
1252
1253              if($flag == 0)
1254                 $user[4].=',moderator';
1255              $line=$user[0].":".$user[1].":".$user[2].":".$user[3].":".$user[4];
1256              $new_user.=$line."\n";
1257             }
1258       }
1259           io_saveFile(DOKU_CONF.'users.auth.php',$new_user);
1260
1261   }
1262
1263
1264 //delete moderator group
1265  function del_group($moderator)
1266   {
1267    $flag = 0;
1268   $actual_users = file(DOKU_CONF.'users.auth.php');
1269       foreach($actual_users as $line)
1270       {
1271            if(($pozice = SubStr($line,0,1)) == '#')
1272              $new_user.=$line;
1273
1274            $line = trim(preg_replace('/#.*$/','',$line)); //ignore comments
1275            if(!$line) continue;
1276
1277            $user = preg_split('/:/',$line);
1278            //0 is user, 1 psswr, 2 real name, 3 email, 4 are groups
1279            if(($user[0] != $moderator))
1280             $new_user.=$line."\n";
1281            else
1282             {
1283              $grps = preg_split('/,/',$user[4]);
1284              foreach($grps as $group)
1285               {
1286                $save.=$group;
1287                if($group != 'moderator'){
1288                 $groups[]=$group;
1289                 $flag = 1;
1290                }
1291               }
1292
1293              if($flag == 1)
1294              $user[4] = join(',',$groups);
1295              $line=$user[0].":".$user[1].":".$user[2].":".$user[3].":".$user[4];
1296              $new_user.=$line."\n";
1297             }
1298       }
1299           io_saveFile(DOKU_CONF.'users.auth.php',$new_user);
1300
1301   }
1302
1303
1304 // delete user
1305 function del_acl($acl_user,$acl_scope)
1306  {
1307        $acl_config = file(DOKU_CONF.'acl.auth.php');
1308        $acl_user = auth_nameencode($acl_user,true);
1309
1310        $acl_pattern = '^'.preg_quote($acl_scope,'/').'\s+'.$acl_user.'\s+[0-8].*$';
1311
1312        // save all non!-matching
1313        $new_config = preg_grep("/$acl_pattern/", $acl_config, PREG_GREP_INVERT);
1314
1315        return io_saveFile(DOKU_CONF.'acl.auth.php', join('',$new_config));
1316
1317  }
1318
1319  //add new user to acl.auth.php
1320  function add_acl($stranka,$concr_alias,$perm)
1321   {
1322
1323       $acl_config = file_get_contents(DOKU_CONF.'acl.auth.php');
1324       $save = "$stranka\t$concr_alias\t$perm\n";
1325       $acl_config.= $save;
1326       io_saveFile(DOKU_CONF.'acl.auth.php', $acl_config);
1327
1328
1329   }
1330
1331 //return criterias what are $user
1332 function _find_visit($user)
1333  {
1334      $data = 0;
1335      $this->get_perm();
1336
1337      if(!empty($this->acl))
1338      {
1339       foreach($this->acl as $page => $n1)
1340        foreach ($n1 as $kriterium => $n2)
1341          foreach ($n2 as $alias => $cislo)
1342           {
1343            if($user == trim($alias))
1344             $data = $kriterium;
1345           }
1346       }
1347     return $data;
1348  }
1349
1350
1351
1352   //load pages who are set on moderators.php and moderator is $user
1353 function _get_pages($user)
1354    {
1355      $ACTUAL_MOD = file(DOKU_PLUGIN.'/autlogin/settings/moderators.php');
1356
1357        foreach($ACTUAL_MOD as $line){
1358
1359            $mod = preg_split('/\s+/',$line);
1360            //0 is name, 1 page
1361            if($mod[0] == $user)
1362              $data[] = $mod[1];
1363        }
1364        if(empty ($data))
1365         $data[]='';
1366
1367      return $data;
1368    }
1369
1370
1371   //load all users
1372  function get_users()
1373   {
1374        global $conf;
1375
1376         $AUTH_ACL = file(DOKU_CONF.'users.auth.php');
1377         foreach($AUTH_ACL as $line){
1378                  $line = trim(preg_replace('/#.*$/','',$line)); //ignore comments
1379                  if(!$line) continue;
1380
1381                  $acl = preg_split('/:/',$line);
1382                  //0 is username, 1 passw, 2 name,...
1383
1384                  // store non-special users and groups for later selection dialog
1385                  $ug = $acl[0];
1386                  $cast_textu = SubStr($ug, 0, 1);
1387                  if($cast_textu != '@')
1388                  $usersgroups[] = $ug;
1389              }
1390        $result = count($usersgroups);
1391        if($result > 0)
1392        $usersgroups = array_unique($usersgroups);
1393    return $usersgroups;
1394   }
1395
1396
1397  //load users who group is autlogin
1398 function get_users_autlogin()
1399   {
1400        global $conf;
1401        global $auth;
1402
1403
1404         $AUTH_ACL = file(DOKU_CONF.'users.auth.php');
1405         foreach($AUTH_ACL as $line){
1406                  $line = trim(preg_replace('/#.*$/','',$line)); //ignore comments
1407                  if(!$line) continue;
1408
1409                  $acl = preg_split('/:/',$line);
1410                  //0 is username, 1 passw, 2 name,...
1411
1412                 $user = auth_nameencode($acl[0]);
1413                  $info = $auth->getUserData($user);
1414                  if($info === false){
1415                          $exist = false;
1416                      }else{
1417                         $groups = $info['grps'];
1418                          $exist = true;
1419                      }
1420                  if($exist){
1421                     foreach($groups as $group)
1422                     if($group == 'autlogin')
1423                     {
1424
1425                          // store non-special users and groups for later selection dialog
1426                          $ug = $acl[0];
1427                          $cast_textu = SubStr($ug, 0, 1);
1428                          if($cast_textu != '@')
1429                          $usersgroups[] = $ug;
1430                    }
1431                    }
1432              }
1433        $result = count($usersgroups);
1434        if($result > 0)
1435        $usersgroups = array_unique($usersgroups);
1436        return $usersgroups;
1437   }
1438
1439
1440
1441  // exist ip?
1442  function control_ip($ip)
1443   {
1444   $regular = '/^0*([1-9]?\d|1\d\d|2[0-4]\d|25[0-5])\.0*([1-9]?\d|1\d\d|2[0-4]\d|25[0-5])\.0*([1-9]?\d|1\d\d|2[0-4]\d|25[0-5])\.0*([1-9]?\d|1\d\d|2[0-4]\d|25[0-5])$/';
1445
1446   if(preg_match($regular,$ip)) //IPv4
1447    return 1;
1448   else {
1449      $IPV6_REGEX = '/^\s*((([0-9A-Fa-f]{1,4}:){7}(([0-9A-Fa-f]{1,4})|:))|(([0-9A-Fa-f]{1,4}:){6}(:|((25[0-5]|2[0-4]\d|[01]?\d{1,2})(\.(25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})|(:[0-9A-Fa-f]{1,4})))|(([0-9A-Fa-f]{1,4}:){5}((:((25[0-5]|2[0-4]\d|[01]?\d{1,2})(\.(25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})?)|((:[0-9A-Fa-f]{1,4}){1,2})))|(([0-9A-Fa-f]{1,4}:){4}(:[0-9A-Fa-f]{1,4}){0,1}((:((25[0-5]|2[0-4]\d|[01]?\d{1,2})(\.(25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})?)|((:[0-9A-Fa-f]{1,4}){1,2})))|(([0-9A-Fa-f]{1,4}:){3}(:[0-9A-Fa-f]{1,4}){0,2}((:((25[0-5]|2[0-4]\d|[01]?\d{1,2})(\.(25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})?)|((:[0-9A-Fa-f]{1,4}){1,2})))|(([0-9A-Fa-f]{1,4}:){2}(:[0-9A-Fa-f]{1,4}){0,3}((:((25[0-5]|2[0-4]\d|[01]?\d{1,2})(\.(25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})?)|((:[0-9A-Fa-f]{1,4}){1,2})))|(([0-9A-Fa-f]{1,4}:)(:[0-9A-Fa-f]{1,4}){0,4}((:((25[0-5]|2[0-4]\d|[01]?\d{1,2})(\.(25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})?)|((:[0-9A-Fa-f]{1,4}){1,2})))|(:(:[0-9A-Fa-f]{1,4}){0,5}((:((25[0-5]|2[0-4]\d|[01]?\d{1,2})(\.(25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})?)|((:[0-9A-Fa-f]{1,4}){1,2})))|(((25[0-5]|2[0-4]\d|[01]?\d{1,2})(\.(25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})))(%.+)?\s*$/';
1450     if(preg_match($IPV6_REGEX,$ip)) //IPv6
1451       return 1;
1452       }
1453
1454    return -1;
1455   }
1456
1457 //is entry page ok?
1458  function control_page($url)
1459   {
1460    return (preg_match('$(http|https|ftp)\://([a-zA-Z0-9\.\-]+(\:[a-zA-Z0-9\.&%\$\ -]+)*@)?((25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]) \.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25 [0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5] |2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])|([a-zA-Z0-9\-]+\ .)*[a-zA-Z0-9\-]+\.[a-zA-Z]{2,4})(\:[0-9]+)?(/[^/][a-zA-Z0-9\.\,\?\'\\ /\+&%\$#\=~_\-@]*)*$', $url));
1461
1462   }
1463
1464
1465 //load all possible browsers from browsers.php
1466 function load_browser()
1467  {
1468     $file = file(DOKU_PLUGIN.'/autlogin/settings/browsers.php');
1469     foreach($file as $line){
1470        $line = trim($line);
1471        $data[] = $line;
1472        }
1473
1474    return $data;
1475  }
1476
1477 //load all possible OS from systems.php
1478 function load_system()
1479  {
1480     $file = file(DOKU_PLUGIN.'/autlogin/settings/systems.php');
1481     foreach($file as $line){
1482        $line = trim($line);
1483        $data[] = $line;
1484        }
1485
1486    return $data;
1487  }
1488
1489
1490 //is login user a moderator?
1491 function _ismoderator(){
1492    global $auth;
1493
1494    $user = $_SERVER['REMOTE_USER'];
1495    $user = auth_nameencode($user);
1496        $info = $auth->getUserData($user);
1497        if($info === false){
1498                $exist = false;
1499            }else{
1500                $groups = $info['grps'];
1501                $exist = true;
1502            }
1503        if($exist == true){
1504         foreach($groups as $lines)
1505          if($lines == 'moderator')
1506           return 1;
1507        }
1508
1509
1510    return 0;
1511   }
1512
1513
1514 //this parse namaspaces and return all namespaces and pages who are in this namespaces
1515 function _parse_ns($data)
1516 {
1517       global $conf;
1518
1519        $pages = array();
1520        $count = count($data);
1521        if($count>0)
1522        for($i=0; $i<$count; $i++){
1523
1524         if($data[$i] == '*'){
1525
1526           $page = $this->_get_all_pages();
1527           $counta = count($page);
1528           if($counta>0) for($a=0; $a<$counta; $a++)
1529             $pages[]=$page[$a]['id'];
1530
1531
1532         }
1533
1534         elseif(substr($data[$i],strlen($data[$i])-1,1)== '*'){
1535           $dir = substr($data[$i],0,(strlen($data[$i])-2)); //erase last ":*"
1536           $flag=$flag+1;
1537           //$dir = $data[$i];
1538           //$dir = '';
1539           $dir  = utf8_encodeFN(str_replace(':','/',$dir));
1540           $media = array();
1541           $datas = array();
1542           $opts['skipacl'] = 0; // no ACL skipping
1543           search($datas, $conf['datadir'], 'search_allpages', $opts, $dir);
1544           search($media, $conf['datadir'], 'search_namespaces', $opts, $dir);
1545
1546           $countq = count($media);
1547           if($countq>0) for($q=0; $q<$countq; $q++)
1548              $pages[]=$media[$q]['id'].":*";
1549           //$datas = array_merge($datas,$media);
1550           $countr = count($datas);
1551           if($countr>0) for($e=0; $e<$countr; $e++)
1552              $pages[]=$datas[$e]['id'];
1553
1554
1555           unset($datas);
1556           unset($media);
1557          }
1558
1559         else{
1560          $flag=$flag+1;
1561          $pages[]=$data[$i];
1562          }
1563
1564       }
1565        $pages = array_merge($pages,$data);
1566        $pages = array_unique($pages);
1567        usort($pages,array($this,'_tree_sort'));
1568
1569  return $pages;
1570 }
1571
1572
1573 //return random alias
1574 function rand_alias()
1575  {
1576      $letter = 'abcdefghijklmnopqrstuvwxyz'; // possible letters
1577
1578       $str = ''; // initialization string
1579
1580       $letter_num = 8; // the alias will have eight letter
1581
1582       SRand((double)MicroTime()*1e6); // random generator
1583
1584
1585
1586      for($i=0;$i<$letter_num;$i++):
1587
1588        $rand = Rand(0, StrLen($letter)-1); //we select random position
1589
1590        $str .= SubStr($letter, $rand, 1); // add char to $rand position
1591
1592      endfor;
1593
1594      return "host".$str;
1595
1596  }
1597
1598 /**
1599     * returns array with set options for building links
1600     *
1601     */
1602    function _get_opts($addopts=null){
1603        global $ID;
1604        $opts = array(
1605                    'do'=>'admin',
1606                    'page'=>'autlogin',
1607                );
1608        if($this->ns) $opts['ns'] = $this->ns;
1609
1610        if(is_null($addopts)) return $opts;
1611        return array_merge($opts, $addopts);
1612    }
1613
1614
1615    /**
1616     * Display a tree menu to select a page or namespace
1617     */
1618    function _html_explorer(){
1619        global $conf;
1620        global $ID;
1621        global $lang;
1622
1623        $dir = $conf['datadir'];
1624        $ns  = $this->ns;
1625        if(empty($ns)){
1626            $ns = dirname(str_replace(':','/',$ID));
1627            if($ns == '.') $ns ='';
1628        }elseif($ns == '*'){
1629            $ns ='';
1630        }
1631        $ns  = utf8_encodeFN(str_replace(':','/',$ns));
1632
1633        $data = $this->_get_tree($ns);
1634
1635        // wrap a list with the root level around the other namespaces
1636        $item = array( 'level' => 0, 'id' => '*', 'type' => 'd',
1637                   'open' =>'true', 'label' => '['.$lang['mediaroot'].']');
1638
1639        echo '<ul class="acltree">';
1640        echo $this->_html_li_acl($item);
1641        echo '<div class="li">';
1642        echo $this->_html_list_acl($item);
1643        echo '</div>';
1644        echo html_buildlist($data,'acl',
1645                            array($this,'_html_list_acl'),
1646                            array($this,'_html_li_acl'));
1647        echo '</li>';
1648        echo '</ul>';
1649
1650    }
1651
1652    /**
1653     * get a combined list of media and page files
1654     *
1655     * @param string $folder an already converted filesystem folder of the current namespace
1656     * @param string $limit  limit the search to this folder
1657     */
1658    function _get_tree($folder,$limit=''){
1659        global $conf;
1660
1661        // read tree structure from pages and media
1662        $data = array();
1663        search($data,$conf['datadir'],'search_index',array('ns' => $folder),$limit);
1664        $media = array();
1665        search($media,$conf['mediadir'],'search_index',array('ns' => $folder, 'nofiles' => true),$limit);
1666        $data = array_merge($data,$media);
1667        unset($media);
1668
1669        // combine by sorting and removing duplicates
1670        usort($data,array($this,'_tree_sort'));
1671        $count = count($data);
1672        if($count>0) for($i=1; $i<$count; $i++){
1673            if($data[$i-1]['id'] == $data[$i]['id'] && $data[$i-1]['type'] == $data[$i]['type']) unset($data[$i]);
1674        }
1675        return $data;
1676    }
1677
1678    /**
1679     * usort callback
1680     *
1681     * Sorts the combined trees of media and page files
1682     */
1683    function _tree_sort($a,$b){
1684        // handle the trivial cases first
1685        if ($a['id'] == '') return -1;
1686        if ($b['id'] == '') return 1;
1687        // split up the id into parts
1688        $a_ids = explode(':', $a['id']);
1689        $b_ids = explode(':', $b['id']);
1690        // now loop through the parts
1691        while (count($a_ids) && count($b_ids)) {
1692            // compare each level from upper to lower
1693            // until a non-equal component is found
1694            $cur_result = strcmp(array_shift($a_ids), array_shift($b_ids));
1695            if ($cur_result) {
1696                // if one of the components is the last component and is a file
1697                // and the other one is either of a deeper level or a directory,
1698                // the file has to come after the deeper level or directory
1699                if (empty($a_ids) && $a['type'] == 'f' && (count($b_ids) || $b['type'] == 'd')) return 1;
1700                if (empty($b_ids) && $b['type'] == 'f' && (count($a_ids) || $a['type'] == 'd')) return -1;
1701                return $cur_result;
1702            }
1703        }
1704        // The two ids seem to be equal. One of them might however refer
1705        // to a page, one to a namespace, the namespace needs to be first.
1706        if (empty($a_ids) && empty($b_ids)) {
1707            if ($a['type'] == $b['type']) return 0;
1708            if ($a['type'] == 'f') return 1;
1709            return -1;
1710        }
1711        // Now the empty part is either a page in the parent namespace
1712        // that obviously needs to be after the namespace
1713        // Or it is the namespace that contains the other part and should be
1714        // before that other part.
1715        if (empty($a_ids)) return ($a['type'] == 'd') ? -1 : 1;
1716        if (empty($b_ids)) return ($b['type'] == 'd') ? 1 : -1;
1717    }
1718
1719
1720    /**
1721     * Item formatter for the tree view
1722     *
1723     * User function for html_buildlist()
1724     */
1725    function _html_list_acl($item){
1726        global $ID;
1727        $ret = '';
1728        // what to display
1729        if($item['label']){
1730            $base = $item['label'];
1731        }else{
1732            $base = ':'.$item['id'];
1733            $base = substr($base,strrpos($base,':')+1);
1734        }
1735
1736        // highlight?
1737        if( ($item['type']== $this->current_item['type'] && $item['id'] == $this->current_item['id']))
1738            $cl = ' cur';
1739
1740        // namespace or page?
1741        if($item['type']=='d'){
1742            if($item['open']){
1743                $img   = DOKU_BASE.'lib/images/minus.gif';
1744                $alt   = '&minus;';
1745            }else{
1746                $img   = DOKU_BASE.'lib/images/plus.gif';
1747                $alt   = '+';
1748            }
1749            $ret .= '<img src="'.$img.'" alt="'.$alt.'" />';
1750            $ret .= '<a href="'.wl('',$this->_get_opts(array('ns'=>$item['id'],'sectok'=>getSecurityToken()))).'" class="idx_dir'.$cl.'">';
1751            $ret .= $base;
1752            $ret .= '</a>';
1753        }else{
1754            $ret .= '<a href="'.wl('',$this->_get_opts(array('id'=>$item['id'],'ns'=>'','sectok'=>getSecurityToken()))).'" class="wikilink1'.$cl.'">';
1755            $ret .= noNS($item['id']);
1756            $ret .= '</a>';
1757        }
1758        return $ret;
1759    }
1760
1761
1762    function _html_li_acl($item){
1763            return '<li class="level'.$item['level'].'">';
1764    }
1765
1766}
1767