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