1<?php
2/**
3 *
4 */
5
6if(!defined('DOKU_INC')) die();
7if(!defined('DOKU_PLUGIN')) define('DOKU_PLUGIN',DOKU_INC.'lib/plugins/');
8define('FCK_ACTION_SUBDIR',  DOKU_PLUGIN . 'ckgdoku/action/');
9require_once(DOKU_PLUGIN.'action.php');
10
11class action_plugin_ckgdoku_meta extends DokuWiki_Action_Plugin {
12  var $session_id = false;
13  var $draft_file;
14  var $user_rewrite = false;
15  var $helper;
16  var $dokuwiki_priority;
17  var $profile_dwpriority;
18  var $wiki_text;
19  var $dw_priority_group;
20  var $dw_priority_metafn;
21  var $captcha = false;
22  function __construct() {
23      $this->helper = plugin_load('helper', 'ckgdoku');
24      $this->dokuwiki_priority = $this->getConf('dw_priority');
25      $this->dw_priority_group = $this->getConf('dw_users');
26      $this->dw_priority_metafn=metaFN(':ckgdoku:dw_priority', '.ser');
27      if(!file_exists($this->dw_priority_metafn)) {
28          io_saveFile($this->dw_priority_metafn, serialize(array()));
29      }
30
31       if(!plugin_isdisabled('captcha')) {
32           $this->captcha = true;
33        }
34  }
35  /*
36   * Register its handlers with the dokuwiki's event controller
37   */
38  function register(Doku_Event_Handler $controller) {
39
40            if($this->helper->is_outOfScope()) return;
41            $controller->register_hook( 'TPL_METAHEADER_OUTPUT', 'AFTER', $this, 'loadScript');
42            $controller->register_hook( 'HTML_EDITFORM_INJECTION', 'AFTER', $this, 'preprocess');
43            $controller->register_hook( 'HTML_EDITFORM_OUTPUT', 'BEFORE', $this, 'insertFormElement');
44            $controller->register_hook('DOKUWIKI_STARTED', 'BEFORE', $this, 'file_type');
45            $controller->register_hook('TPL_CONTENT_DISPLAY', 'AFTER', $this, 'setupDWEdit');
46            $controller->register_hook('DOKUWIKI_STARTED', 'AFTER', $this, 'reset_user_rewrite_check');
47            $controller->register_hook('DOKUWIKI_DONE', 'BEFORE', $this, 'restore_conf');
48            $controller->register_hook('AJAX_CALL_UNKNOWN', 'BEFORE', $this,'_ajax_call');
49            $controller->register_hook('HTML_UPDATEPROFILEFORM_OUTPUT', 'BEFORE', $this, 'handle_profile_form');
50  }
51
52  function handle_profile_form(Doku_Event $event, $param) {
53         if(!$this->getConf('dw_priority')) { return;	}
54          global $INFO;
55            $client =   $_SERVER['REMOTE_USER']; //$INFO['client'];
56            $ar = unserialize(file_get_contents($this->dw_priority_metafn));
57            $which = $ar[$client];
58            $dwed = ""; $cked = "";
59            if($which == 'N') {
60                $cked = "checked";
61            }
62            else if($which ==  'Y') {
63                $dwed = "checked";
64            }
65
66            $pos = $event->data->findElementByAttribute('type', 'reset');
67            $_form = '</div></form><br /><form name="ckgdokuform" action="#"><div class="no">';
68            $_form.= '<fieldset ><legend>' . $this->getLang('uprofile_title') .'</legend>';
69
70            $_form.= '<label><span><b>DW Editor</b></span> ';
71            $_form .='<input type="radio" value = "Y" name="cked_selector" ' . $dwed .'></label>&nbsp;';
72            $_form .='<label><span><b>CK Editor</b></span> ';
73            $_form .='<input type="radio"  value = "N" name="cked_selector" ' . $cked . '></label>';
74
75            $_form.= '<br /><label><span><b>User Name: </b></span> ';
76            $_form.= '<input type="textbox" name="cked_client" disabled value="' .  $client .'"/></label>';
77            $_form.= '<br /><br /><input type="button" value="Save" class="button" ' . "onclick='ckgdoku_seteditor_priority(this.form.cked_selector.value,this.form.cked_client.value,this.form.cked_selector);' />&nbsp;";
78            $_form.= '<input type="reset" value="Reset" class="button" />';
79           $_form.= '</fieldset>';
80            $event->data->insertElement($pos+2, $_form);
81  }
82
83function _ajax_call(Doku_Event $event, $param) {
84       if ($event->data == 'cked_upload') {
85          global $lang;
86           $event->stopPropagation();
87          $event->preventDefault();
88           global $INPUT;
89           $id = urldecode($INPUT->str('ckedupl_id'));
90           $id = str_replace('/', ':',$id);
91           $this->ajax_debug($id);
92          $fn = mediaFN($id);
93          $this->ajax_debug($fn);
94          $delete = $INPUT->str('ckedupl_del');
95           if(file_exists($fn)) {
96              $size =  filesize($fn);
97              $this->ajax_debug("$fn:  $size");
98           }
99          else $this->ajax_debug("$fn not found");
100
101          if($delete && $delete == 'D') {
102               $size = ""; $ft = "";
103               $oldf  = $id;
104              $size_tm =  $INPUT->str('delsize');
105               $this->ajax_debug('size_tm='.$size_tm);
106              if($size_tm != 'undefined' && isset($size_tm))   {
107                  list($size,$ft) = explode(';',$size_tm);
108                  $size=trim($size);
109                  $ft=trim($ft);
110                  $size =  '-' . $size;
111              }
112              else if(file_exists($fn)) {
113                  if(!$size) {
114                      $size = filesize($fn);
115                   $size =  '-' . $size;
116                  }
117                  if(!$ft) {
118                   $ft=filemtime($fn) ;
119              }
120              }
121              else {
122                  $this->ajax_debug("$fn not found");
123                  return;
124              }
125              if(isset($ft) && file_exists($fn)) {
126                $newf = mediaFN($id,$ft);
127                $this->ajax_debug("newf:  $newf fn:  $fn");
128                 if(file_exists($fn)){
129                    $this->ajax_debug("old file: $oldf; $fn");
130               }
131                 else  $this->ajax_debug("no old file: $fn");
132
133                 io_makeFileDir($newf);
134                 if(copy($fn, $newf)) {
135                    $this->ajax_debug("Copying $fn  to $newf");
136                    chmod($newf, $conf['fmode']);
137                   $this->ajax_debug("deleting: $fn");
138                    if(!unlink($fn)) $this->ajax_debug("delete failed");
139                }
140                 else $this->ajax_debug("copy failed");
141             }
142              if(file_exists($fn)) {
143                  if(!copy($fn, $newf)) {
144                     $this->ajax_debug ("(2nd try) could not copy $fn to $newf");
145                     return;
146                     }
147                  if(!unlink($fn))  {
148                     $this->ajax_debug ("could not delete $fn");
149                     return;
150                  }
151              }
152              addMediaLogEntry($ft, $id, DOKU_CHANGE_TYPE_DELETE, $lang['deleted'],'', null, $size);
153          }
154          else addMediaLogEntry(time(), $id, DOKU_CHANGE_TYPE_CREATE, $lang['created'],'', null, $size);
155          echo 'done';
156          return;
157      }
158      //cked_deletedsize
159      if ($event->data == 'cked_deletedsize') {
160          $event->stopPropagation();
161          $event->preventDefault();
162           global $INPUT;
163           $id = urldecode($INPUT->str('cked_delid'));
164           $fn = mediaFN($id);
165           if(file_exists($fn)) {
166            $this->ajax_debug(filesize ($fn) . ';' .filemtime($fn) );
167           }
168           else echo ("$fn not found");
169          return;
170      }
171      if ($event->data == 'use_heads') {
172         $event->stopPropagation();
173          $event->preventDefault();
174          global $INPUT;
175          $page = $INPUT->str('dw_id');
176          $page = urldecode($page);
177          $page = ltrim($page, ':');
178         $t= trim(p_get_first_heading($page));
179         echo $t;
180         return;
181     }
182
183     if ($event->data == 'wrap_lang') {
184         $event->stopPropagation();
185          $event->preventDefault();
186         global $INPUT;
187         $which = $INPUT->str('lang');
188         $path = DOKU_PLUGIN . 'wrap/lang/' . $which . '/lang.php';
189         if(file_exists($path)) {
190                $data = file($path, FILE_IGNORE_NEW_LINES|FILE_SKIP_EMPTY_LINES );
191                array_shift($data);
192         }
193        $result = array();
194        for($i=0; $i<count($data); $i++) {
195              list($name, $val) = explode('=',$data[$i]);
196              $name = str_replace('$lang',"",$name);
197              $name = trim($name,' ][\'');
198              if($name == 'picker') $name ='title';
199             $val = trim($val,' ;\'');
200              $result[$name] = $val;
201        }
202         echo json_encode($result);
203         return;
204       }
205
206     if ($event->data == 'cked_selector') {  //choose profile editor priority
207         $event->stopPropagation();
208         $event->preventDefault();
209        global $INPUT, $USERINFO,$INFO;
210        if(!isset($USERINFO)) return;
211
212        $ar = unserialize(file_get_contents($this->dw_priority_metafn));
213        $dwp = $INPUT->str('dw_val');
214        $client = $INPUT->str('dwp_client');
215         $ar[$client] = $dwp;
216         $retv = file_put_contents($this->dw_priority_metafn,serialize($ar));
217         if($retv === false) {
218             echo $this->dw_priority_metafn;
219         }
220         else echo "done";
221         return;
222    }
223
224
225   if ($event->data == 'geshi_sel') {     //get geshi file names , return as ;; separated string w/o php extensions
226      $event->stopPropagation();
227       $event->preventDefault();
228
229       if( class_exists('GeSHi')) {
230            if(defined('GESHI_LANG_ROOT') )  $geshi_dir =GESHI_LANG_ROOT;
231      }
232     else {
233         echo "ENotfound\n";
234         return ;
235     }
236    $gfiles = scandir ($geshi_dir);
237    $selects = array();
238    foreach($gfiles as $gfile){
239        if(is_dir($gfile)) continue;
240       $gfile =  preg_replace("/\.php\n?$/","",$gfile);
241        $selects[] = $gfile;
242    }
243    $selects = implode ( ';;', $selects );
244    echo $selects;
245    return;
246    }
247
248    if ($event->data !== 'refresh_save') {  // save ckgedit backups in native dw format
249        return;
250    }
251
252    $event->stopPropagation();
253    $event->preventDefault();
254     global  $INPUT;
255
256
257       $rsave_id = urldecode($INPUT->str('rsave_id'));
258       $path = pathinfo($rsave_id);
259       if($path['extension'] != 'ckgdoku') {
260             echo "failed";
261             return;
262        }
263
264       $this->wiki_text = urldecode($INPUT->str('wikitext'));
265
266        if(!preg_match('/^\s+(\-|\*)/',$this->wiki_text)){
267              $this->wiki_text = trim($this->wiki_text);
268        }
269
270          /* preserve newlines in code blocks */
271          $this->wiki_text = preg_replace_callback(
272            '/(<code>|<file>)(.*?)(<\/code>|<\/file>)/ms',
273            create_function(
274                '$matches',
275                'return  str_replace("\n", "__code_NL__",$matches[0]);'
276            ),
277            $this->wiki_text
278          );
279
280        $this->wiki_text = preg_replace('/^\s*[\r\n]$/ms',"__n__", $this->wiki_text);
281        $this->wiki_text = preg_replace('/\r/ms',"", $this->wiki_text);
282        $this->wiki_text = preg_replace('/^\s+(?=\^|\|)/ms',"", $this->wiki_text);
283        $this->wiki_text = preg_replace('/__n__/',"\n", $this->wiki_text);
284        $this->wiki_text = str_replace("__code_NL__","\n", $this->wiki_text);
285
286
287       $this->wiki_text .= "\n";
288
289
290        $pos = strpos($this->wiki_text, 'MULTI_PLUGIN_OPEN');
291        if($pos !== false) {
292           $this->wiki_text = preg_replace_callback(
293            '|MULTI_PLUGIN_OPEN.*?MULTI_PLUGIN_CLOSE|ms',
294            create_function(
295                '$matches',
296                  'return  preg_replace("/\\\\\\\\/ms","\n",$matches[0]);'
297            ),
298            $this->wiki_text
299          );
300
301           $this->wiki_text = preg_replace_callback(
302            '|MULTI_PLUGIN_OPEN.*?MULTI_PLUGIN_CLOSE|ms',
303            create_function(
304                '$matches',
305                  'return  preg_replace("/^\s+/ms","",$matches[0]);'
306            ),
307            $this->wiki_text
308          );
309
310        }
311
312     $this->replace_entities();
313     $this->wiki_text = preg_replace('/\<\?php/i', '&lt;?php',$this->wiki_text) ;
314     $this->wiki_text = preg_replace('/\?>/i', '?&gt;',$this->wiki_text) ;
315     file_put_contents($rsave_id, $this->wiki_text);
316     echo 'done';
317
318}
319
320function replace_entities() {
321    global $ents;
322    $serialized = FCK_ACTION_SUBDIR . 'ent.ser';
323    $ents = unserialize(file_get_contents($serialized));
324
325       $this->wiki_text = preg_replace_callback(
326            '|(&(\w+);)|',
327            create_function(
328                '$matches',
329                'global $ents; return $ents[$matches[2]];'
330            ),
331            $this->wiki_text
332        );
333
334}
335
336 function  insertFormElement(Doku_Event $event, $param) {
337   global $FCKG_show_preview;
338
339  $param = array();
340
341   global $ID;
342   $dwedit_ns = @$this->getConf('dwedit_ns');
343   if(isset($dwedit_ns) && $dwedit_ns) {
344       $ns_choices = explode(',',$dwedit_ns);
345       foreach($ns_choices as $ns) {
346         $ns = trim($ns);
347         if(preg_match("/$ns/",$ID)) {
348            echo "<style type = 'text/css'>#edbtn__preview,#edbtn__save, #edbtn__save { display: inline; } </style>";
349            break;
350         }
351       }
352   }
353   $act = $event->data;
354   if(is_string($act) && $act != 'edit') {
355        return;
356   }
357
358  // restore preview button if standard DW editor is in place
359  // $FCKG_show_preview is set in edit.php in the register() function
360if($_REQUEST['fck_preview_mode'] != 'nil' && !isset($_COOKIE['FCKG_USE']) && !$FCKG_show_preview) {
361     echo '<style type="text/css">#edbtn__preview { display:none; }</style>';
362 }
363 elseif($FCKG_show_preview) {
364      echo '<style type="text/css">#edbtn__preview { display: inline; } </style>';
365 }
366 else {
367    echo '<style type="text/css">#edbtn__preview, .btn_show { position:absolute; visibility:hidden; }</style>';
368 }
369
370 global $ckgdoku_lang;
371
372  if($_REQUEST['fck_preview_mode']== 'preview'){
373    return;
374  }
375
376 $param = array();
377 $this->preprocess($event, $param);  // create the setDWEditCookie() js function
378 $button = array
379        (
380            '_elem' => 'button',
381            'type' => 'submit',
382            '_action' => 'cancel',
383            'value' => $this->getLang('btn_fck_edit'),
384            'class' => 'button',
385            'id' => 'edbtn__edit',
386            'title' => $this->getLang('btn_fck_edit')
387        );
388
389     $pos = strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE');
390     if($pos === false) {
391                 $button['onclick'] = 'return setDWEditCookie(1, this);';
392     }
393     else {
394                $button['onmousedown'] = 'return setDWEditCookie(1, this);';
395     }
396
397    $pos = $event->data->findElementByAttribute('type','submit');
398       //inserts HTML data after that position.
399    $event->data->insertElement(++$pos,$button);
400
401   return;
402
403  }
404
405
406 function preprocess(Doku_Event $event, $param) {
407    $act = $event->data;
408
409   if(is_string($act) && $act != 'edit') {
410        return;
411   }
412  global $INFO, $ckgdoku_lang;
413
414  $discard = $this->getLang('discard_edits');
415  echo "<script type='text/javascript'>\n//<![CDATA[ \n";
416  echo "var useDW_Editor =   $this->profile_dwpriority;";
417  echo "\n //]]> </script>\n";
418  echo <<<SCRIPT
419    <script type="text/javascript">
420    //<![CDATA[
421    var ckgdoku_dwedit_reject = false;
422    var ckgdoku_to_dwedit = false;
423    function setDWEditCookie(which, e) {
424
425        var dom = document.getElementById('ckgdoku_mode_type');
426
427         if(useDW_Editor) {
428                document.cookie = 'FCKG_USE=other;expires=';
429              }
430             else {
431                document.cookie='FCKG_USE=other;expires=Thu,01-Jan-70 00:00:01 GMT;'
432           }
433        if(which == 1) {
434           if(e && e.form) {
435                    if(e.form['mode']) {
436                       e.form['mode'].value = 'fck';
437                    }
438                    else {
439                       e.form['mode'] = new Object;
440                       e.form['mode'].value = 'fck';
441                    }
442           }
443           else dom.value = 'fck';
444           e.form.submit();
445       }
446        else {
447            document.cookie = 'FCKG_USE=_false_;expires=';
448            dom.value = 'dwiki';
449           if(JSINFO['chrome_version'] >= 56 && window.dwfckTextChanged) {
450           }
451            else if(window.dwfckTextChanged  && !window.confirm("$discard")) {
452               var dom = GetE('dwsave_select');
453               ckgdoku_dwedit_reject=true;
454               window.dwfckTextChanged = false;
455        }
456       }
457
458    }
459
460
461    //]]>
462
463    </script>
464SCRIPT;
465
466  }
467
468function check_userfiles() {
469
470    if($this->getConf('no_symlinks')) {
471	   return;
472	}
473
474    global $INFO;
475    global $conf;
476
477    $save_dir = trim($conf['savedir']);
478    $animal = isset($conf['animal']) ? $conf['animal'] : 'userfiles';
479
480   $userfiles = DOKU_PLUGIN . "ckgdoku/fckeditor/$animal/";
481    if(isset($conf['animal']) && $conf['animal'] !== 'userfiles') {
482        setcookie('FCK_animal',$animal, $expire, '/');
483		setcookie('FCK_animal_inc',$conf['animal_inc'], $expire, '/');
484        preg_match('#^(.*?' . $conf['animal'] . ')#', $save_dir,$matches);
485        $save_dir=$matches[1] . '/data/pages';
486        setcookie('FCK_farmlocal',$save_dir, $expire, '/');
487
488        return;
489    }
490// msg('BASE='. DOKU_BASE);
491// msg(DOKU_URL);
492// msg('REL='. DOKU_REL);
493    if(!preg_match('#^\.\/data$#',$save_dir)) {
494        $data_media = $conf['savedir']  . '/media/';
495
496        $domain = trim(DOKU_BASE,'/');
497
498        $expire = null;
499
500        if(! empty($domain )) {
501        list($prefix,$mdir) = explode(trim(DOKU_BASE, '/'),$userfiles);
502           $mdir = ltrim($mdir, '/');
503        $media_dir = DOKU_BASE . $mdir . 'image/';
504        }
505        else $media_dir = '/lib/plugins/ckgdoku/fckeditor/'. $animal . '/image/';
506        setcookie('FCK_media',$media_dir, $expire, '/');
507
508     }
509     else {
510         $data_media = DOKU_INC.'data/media/';
511     }
512
513     if($this->getConf('winstyle'))  {
514         $htaccess = $data_media . '.htaccess';
515          if(!file_exists($htaccess)) {
516               $security = $userfiles . '.htaccess.security';
517               if(file_exists($security)) {
518                   if(!copy($security, $htaccess)) {
519                       msg($this->getLang("ws_cantcopy") . $htaccess);
520                   }
521                   else msg($this->getLang("ws_copiedhtaccess"));
522               }
523          }
524         return;
525     }
526     if(!is_readable($userfiles) && !is_writable($userfiles)){
527              msg($this->getLang("userfiles_perm" ) . ' ' . $userfiles) ;
528		      return;
529     }
530	$version = io_readFile(DOKU_PLUGIN . 'ckgdoku/version');
531	if(!$version) return;
532    $meta = metaFN('fckl:symchk','.meta');
533	$symcheck = io_readFile($meta);
534    if($symcheck) {
535	   if(trim($version)== trim($symcheck)) {  //symlinks should already have been created
536		  return;
537	   }
538    }
539
540	if (function_exists('php_uname')) {
541	   $sys = php_uname() ;
542	   if( preg_match('/Windows/i',  $sys) ) {
543		     preg_match('/build\s+(\d+)/',$sys, $matches);
544		    if($matches[1]  < 6000) {  // we can make symlinks for vista (6000) or later
545			   return;
546		   }
547
548		   $winlinks =  array();
549		   $userfiles = str_replace('/', '\\',$userfiles);
550		   exec("dir " . $userfiles, $output);
551		   foreach($output as $line) {
552		      if(preg_match('/<SYMLINKD>\s+(.*?)\s+\[/i',$line,$matches)) {
553			     $winlinks[] = $matches[1];
554			  }
555		   }
556		}
557
558    }
559	else if( preg_match('/WINNT/i',  PHP_OS) ) {    // if we can't get php_uname and a build and this is Windows, just return
560         return;
561    }
562
563       $show_msg = false;
564	   if($INFO['isadmin'] || $INFO['ismanager'] )    {  // only admins and mgrs get messages
565	       $show_msg = true;
566	   }
567	   $link_names = array('flash',  'image',  'media', 'file', 'image');
568	   if(is_array($winlinks) && count($winlinks)) {
569	       $link_names = array_diff($link_names, $winlinks);
570	   }
571	   $links = array();
572	   foreach ($link_names as $ln) {
573	        $links[$ln] = $userfiles . $ln;
574	   }
575
576      $bad_create = false;
577	  $successes =  array();
578	  if(@file_exists($userfiles)) {
579		   foreach($links as $name => $path) {
580			  if(!is_link($path)) {
581                     if(file_exists($path) && is_file($path) ){
582					       unlink($path);
583                       }
584                    if(file_exists($path) && is_dir($path) ){
585					       rmdir($path);
586                       }
587					 if(!@symlink($data_media,$path) ) {
588					     $bad_create = true;
589						  if($show_msg)   msg($this->getLang("sym_not created_1") . " $name link:  $path",-1);
590				   }
591				   else {
592				     $successes[] = $name;
593				   }
594			 }
595		  }
596      }
597	  else {
598	     if($show_msg)  {
599	        msg($this->getLang("sym_not created_2") ." $userfiles",-1);
600		 }
601	  }
602
603	  if($bad_create) {
604	       if($show_msg)  {
605		       msg($this->getLang("sym_not created_3") . " $userfiles");
606				}
607      }
608	  else {
609	       if(count($successes)) {
610				$links_created = implode(', ',$successes);
611				 msg($this->getLang("syms_created") . " $links_created",2);
612			 }
613	  }
614	  			io_saveFile($meta,$version);
615                chmod($meta, 0666);
616}
617
618
619  function set_session() {
620      global $USERINFO, $INFO;
621      global $conf;
622      global $ID;
623      global $ACT;
624
625      if($this->session_id) return;
626
627           $cname = getCacheName($INFO['client'].$ID,'.draft');
628           $fckl_draft = $cname . '.fckl';
629           if((isset($ACT) && is_array($ACT)) || isset($_REQUEST['dwedit_preview'])) {
630              if(isset($ACT['draftdel']) || isset($ACT['cancel']) || isset($_REQUEST['dwedit_preview'])) {
631                 @unlink($fckl_draft);
632                 @unlink($cname);
633              }
634           }
635
636           if(file_exists($cname)) {
637              if(file_exists($fckl_draft)) {
638                    unlink($fckl_draft);
639              }
640              @rename($cname, $fckl_draft);
641           }
642
643
644           $session_string =  session_id();
645           $this->session_id = $session_string;
646
647
648           $_SESSION['dwfck_id'] = $session_string;
649           $default_fb = $this->getConf('default_fb');
650
651           if($default_fb == 'none') {
652               $acl = 255;
653           }
654           else {
655              $acl = auth_quickaclcheck($ID);
656           }
657           $_SESSION['dwfck_acl'] = $acl;
658
659           if($this->getConf('openfb') || $acl == 255) {
660             $_SESSION['dwfck_openfb'] = 'y';
661           }
662           else {
663              $_SESSION['dwfck_openfb'] = 'n';
664           }
665
666           $_SESSION['dwfck_grps'] = isset($USERINFO['grps']) ? $USERINFO['grps'] : array();
667           $_SESSION['dwfck_client'] = $INFO['client'];
668           $_SESSION['dwfck_sepchar'] = $conf['sepchar'] ;
669           $_SESSION['dwfck_conf'] = array('sepchar'=> $conf['sepchar'],
670                  'isadmin'=>($INFO['isadmin'] || $INFO['ismanager']),
671                  'deaccent'=>$conf['deaccent'], 'useslash'=>$conf['useslash']);
672           $elems = explode(':', $ID);
673           array_pop($elems);
674
675           $_SESSION['dwfck_ns'] = implode(':',$elems);
676           $_SESSION['dwfck_top'] = implode('/',$elems);
677           $_SESSION['dwfck_del'] = $this->getConf('acl_del');
678
679            // temp fix for puzzling encoding=url bug in frmresourceslist.html,
680           // where image loading is processed in GetFileRowHtml()
681
682           if(preg_match('/ckgdoku:fckeditor:userfiles:image/',$ID)) {
683                      $_SESSION['dwfck_ns'] = "";
684                      $_SESSION['dwfck_top'] = "";
685
686            }
687
688          // $expire = time()+60*60*24*30;
689           $expire = null;
690           setcookie('FCK_NmSp_acl',$session_string, $expire, '/');
691
692           setcookie('FCK_SCAYT',$this->getConf('scayt'), $expire, '/');
693           setcookie('FCK_SCAYT_AUTO',$this->getConf('scayt_auto'), $expire, '/');
694           $scayt_lang = $this->getConf('scayt_lang');
695           if(isset($scayt_lang)) {
696               list($scayt_lang_title,$scayt_lang_code) = explode('/',$scayt_lang);
697               if($scayt_lang_code!="en_US") {
698                  setcookie('FCK_SCAYT_LANG',$scayt_lang_code, $expire, '/');
699               }
700           }
701           if ($this->getConf('winstyle')) {
702              setcookie('FCKConnector','WIN', $expire, DOKU_BASE);
703           }
704
705           if ($this->dokuwiki_priority && $this->in_dwpriority_group() ) {
706               if(isset($_COOKIE['FCKG_USE']) && $_COOKIE['FCKG_USE'] == 'other') {
707                   $expire = time() -60*60*24*30;
708                   setcookie('FCKG_USE','_false_', $expire, '/');
709               }
710               else {
711                  setcookie('FCKG_USE','_false_', $expire, '/');
712                }
713           }
714  }
715
716  function file_type(Doku_Event $event, $param) {
717       global $ACT;
718       global $ID;
719       global $JSINFO,$USERINFO;
720       global  $INPUT;
721       global $updateVersion;
722       global $conf;
723
724        $do = $INPUT->str('do','NOTADMIN');
725	    if($do === 'admin' && isset($USERINFO)){
726			msg($this->getLang('deprecation').
727		   ' <a href="https://www.dokuwiki.org/plugin:ckgdoku#important_notice">CKGDOKU</a>',2);
728		}
729        $plist = plugin_list('helper');
730        if(in_array('ckgedit', $plist)) {
731            msg($this->getLang('ckgcke_conflict'),2);
732        }
733
734       $acl_defines = array('EDIT'=> 2,'CREATE'=> 4,'UPLOAD'=> 8,'DELETE'=> 16,'ADMIN'=> 255);
735       $_auth =  $this->getConf('captcha_auth');
736       $auth_captcha = (int)$acl_defines[$_auth];
737       $auth = auth_quickaclcheck($ID);
738
739       if($auth >= $auth_captcha && $this->captcha) {
740           $conf['plugin']['captcha']['forusers']=0;
741        }
742       $JSINFO['confirm_delete']= $this->getLang('confirm_delete');
743       $JSINFO['doku_base'] = DOKU_BASE ;
744       $JSINFO['cg_rev'] = $INPUT->str('rev');
745       $JSINFO['dw_version']  = (float)$updateVersion;
746       if(preg_match("/Chrome\/(\d+)/", $_SERVER['HTTP_USER_AGENT'],$cmatch)) {
747           $JSINFO['chrome_version']  = (float) $cmatch[1];
748       }
749       else $JSINFO['chrome_version'] = 0;
750       $JSINFO['hide_captcha_error'] = $INPUT->str('ckged_captcha_err','none');
751       $dbl_click_auth  =  $this->getConf('dw_edit_display');
752       if($dbl_click_auth == 'none' || empty($_SERVER['REMOTE_USER'])) {
753           $JSINFO['ckg_dbl_click']  = "";
754       }
755       else if($dbl_click_auth == 'all' ||$auth == 255 ) {
756           $JSINFO['ckg_dbl_click']  = "1";
757       }
758       $onoff = $this->getConf('dblclk');
759       if($onoff == 'off') $JSINFO['ckg_dbl_click'] = "";
760       $JSINFO['ckg_canonical'] =$conf['canonical'];
761       $JSINFO['doku_base'] = DOKU_BASE;
762        $JSINFO['doku_url'] = DOKU_URL;
763       if($this->helper->has_plugin('tag'))  $JSINFO['has_tags'] = "Tag";
764       if($this->helper->has_plugin('wrap') && ! plugin_isdisabled('wrap'))  {
765           $JSINFO['has_wrap'] = "Wrap";
766        $wrap_helper =  plugin_load('helper','wrap');
767           if($wrap_helper ) {
768        $syntaxDiv = $wrap_helper->getConf('syntaxDiv');
769        if(!empty($syntaxDiv)) {
770            $JSINFO['wrapDiv'] = $syntaxDiv;
771          }
772          else $JSINFO['wrapDiv'] = "";
773          $JSINFO['template'] = $conf['template'];
774        $syntaxSpan = $wrap_helper->getConf('syntaxSpan');
775        if(!empty($syntaxSpan)) {
776            $JSINFO['wrapSpan'] = $syntaxSpan;
777        }
778        else $JSINFO['wrapSpan'] = "";
779           }
780       }
781
782        if(!isset($_COOKIE['ckgEdPaste'])) {
783            $JSINFO['ckgEdPaste'] = 'off';
784        }
785        else {
786            $JSINFO['ckgEdPaste'] = $_COOKIE['ckgEdPaste'];
787        }
788        $JSINFO[ 'rel_links'] = $this->getConf('rel_links');
789	   $this->check_userfiles();
790	   $this->profile_dwpriority=($this->dokuwiki_priority && $this->in_dwpriority_group()) ? 1 :  0;
791       if(isset($_COOKIE['FCK_NmSp'])) $this->set_session();
792       /* set cookie to pass namespace to FCKeditor's media dialog */
793      // $expire = time()+60*60*24*30;
794       $expire = null;
795       setcookie ('FCK_NmSp',$ID, $expire, '/');
796
797
798
799      /* Remove TopLevel cookie */
800       if(isset($_COOKIE['TopLevel'])) {
801            setcookie("TopLevel", $_REQUEST['TopLevel'], time()-3600, '/');
802       }
803
804
805       if(!isset($_REQUEST['id']) || isset($ACT['preview'])) return;
806       if(isset($_REQUEST['do']) && isset($_REQUEST['do']['edit'])) {
807              $_REQUEST['do'] = 'edit';
808       }
809  }
810
811function loadScript(Doku_Event $event) {
812  echo <<<SCRIPT
813
814    <script type="text/javascript">
815    //<![CDATA[
816    function LoadScript( url )
817    {
818     document.write( '<scr' + 'ipt type="text/javascript" src="' + url + '"><\/scr' + 'ipt>' ) ;
819
820    }
821   function LoadScriptDefer( url )
822    {
823     document.write( '<scr' + 'ipt type="text/javascript" src="' + url + '" defer><\/scr' + 'ipt>' ) ;
824
825    }
826//]]>
827
828 </script>
829
830SCRIPT;
831
832}
833
834/**
835 *  Handle features need for DW Edit:
836 *    1. load script, if not loaded
837 *    2. Re-label Cancel Button "Exit" when doing a preview
838 *    3. set up $REQUEST value to identify a preview when in DW Edit , used in
839 *       set_session to remove ckgdoku and DW drafts if present after a DW preview
840*/
841  function setupDWEdit(Doku_Event $event) {
842  global $ACT;
843
844  $url = DOKU_URL . 'lib/plugins/ckgdoku/scripts/script-cmpr.js';
845  if(($ACT == 'login' || $this->session_id == false) && $this->getConf('preload_ckeditorjs')) {
846     $url2 = DOKU_BASE.'lib/plugins/ckgdoku/ckeditor/ckeditor.js';
847  }
848  else $url2 = "";
849  echo <<<SCRIPT
850
851    <script type="text/javascript">
852    //<![CDATA[
853
854    try {
855    if(!window.HTMLParserInstalled || !HTMLParserInstalled){
856         LoadScript("$url");
857    }
858    }
859    catch (ex) {
860         LoadScript("$url");
861    }
862    if("$url2") {
863       LoadScriptDefer("$url2");
864    }
865    function createRequestValue() {
866        try{
867        var inputNode=document.createElement('input');
868        inputNode.setAttribute('type','hidden');
869        inputNode.setAttribute('value','yes');
870        inputNode.setAttribute('name','dwedit_preview');
871        inputNode.setAttribute('id','dwedit_preview');
872        var dwform = GetE("dw__editform");
873        dwform.appendChild(inputNode);
874        }catch(e) { alert(e); }
875    }
876//]]>
877 </script>
878
879SCRIPT;
880
881  if(isset($_REQUEST['do']) && is_array($_REQUEST['do'])) {
882    if(isset($_REQUEST['do']['preview'])) {
883           echo '<script type="text/javascript">';
884           echo ' var dwform = GetE("dw__editform"); dwform["do[draftdel]"].value = "Exit";';
885           echo "\ncreateRequestValue()\n";
886           echo  '</script>';
887    }
888  }
889
890
891  }
892
893
894
895function reset_user_rewrite_check() {
896
897      global $ACT;
898       global $conf;
899	   global $JSINFO;
900
901       if(isset($_COOKIE['FCKG_USE']) && $_COOKIE['FCKG_USE'] =='_false_' ) return;
902       if($ACT == 'login') $this->chk_dbl_clk_time();
903       if($ACT == 'edit') {
904          $this->user_rewrite = $conf['userewrite'];
905	     $conf['userewrite']  = 0;
906       }
907
908       if($conf['htmlok'] || $this->getConf('htmlblock_ok')) {
909         $JSINFO['htmlok'] = 1;
910    }
911    else $JSINFO['htmlok'] = 0;
912    }
913
914function chk_dbl_clk_time() {
915   global $INFO;
916   if($INFO['isadmin'] || $INFO['ismanager'] )    {  // only admins and mgrs get messages
917	       $show_msg = true;
918	}
919   if(!$show_msg)  return;
920  $filename =  metaFN('fckl:dblck','.meta');
921  $msg = $this->getLang('dblclk');
922   if (file_exists($filename)) {
923           $reps = io_readFile($filename);
924           if($reps <2) {
925              $reminder =  $this->getLang('dblclk_reminder');
926              msg("($reminder) " . $msg,2 );
927              io_saveFile($filename,$reps+1);
928              return;
929           }
930   }
931   else
932       {
933       io_saveFile($filename,'1');
934       msg($msg,2);
935   }
936}
937/**
938  checked for additional dw priority possibilities only if the dw priority option is set to true
939*/
940function in_dwpriority_group() {
941        global $USERINFO,$INFO;
942        if(!isset($USERINFO)) return false;
943         if(empty($this->dw_priority_group)) return true;  // all users get dw_priority if no dw_priority group has been set in config
944         $client =   $_SERVER['REMOTE_USER'];
945         $ar = unserialize(file_get_contents($this->dw_priority_metafn));  // check user profile settings
946         $expire = time() -60*60*24*30;
947         if(isset($ar[$client])) {
948             if($ar[$client] =='Y') return true;    // Y = dw_priority selected
949             if($ar[$client] =='N') {
950                 setcookie('FCKG_USE','_false_', $expire, '/');
951                 return false;  // N = CKEditor selected
952             }
953         }
954        $user_groups = $USERINFO['grps'];
955
956        if(in_array($this->dw_priority_group, $user_groups) || in_array("admin", $user_groups)) {
957           return true;
958        }
959
960         setcookie('FCKG_USE','_false_', $expire, '/');
961
962      return false;
963}
964
965function restore_conf() {
966    global $conf;
967    global $ACT;
968    if($ACT == 'edit') { return; }
969
970    if($this->user_rewrite !==false) {
971         $conf['userewrite']   = $this->user_rewrite;
972    }
973
974}
975function ajax_debug($data) {
976    return;
977    echo "$data\n";
978}
979function write_debug($data) {
980  return;
981  if (!$handle = fopen(DOKU_INC .'meta.txt', 'a')) {
982    return;
983    }
984  if(is_array($data)) {
985     $data = print_r($data,true);
986  }
987    // Write $somecontent to our opened file.
988    fwrite($handle, "$data\n");
989    fclose($handle);
990
991}
992
993}
994
995
996
997