summaryrefslogtreecommitdiff
path: root/platform/www/lib/plugins/farmer/admin/new.php
blob: 8cbf94f46a3883d25124ea560a635cad8d569ada (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
<?php
/**
 * DokuWiki Plugin farmer (Admin Component)
 *
 * @license GPL 2 http://www.gnu.org/licenses/gpl-2.0.html
 * @author  Michael Große <grosse@cosmocode.de>
 */

// must be run within Dokuwiki
if(!defined('DOKU_INC')) die();

class admin_plugin_farmer_new extends DokuWiki_Admin_Plugin {

    /** @var helper_plugin_farmer $helper */
    protected $helper;

    /**
     * @return bool true if only access for superuser, false is for superusers and moderators
     */
    public function forAdminOnly() {
        return true;
    }

    /**
     * admin_plugin_farmer_new constructor.
     */
    public function __construct() {
        $this->helper = plugin_load('helper', 'farmer');
    }

    /**
     * Should carry out any processing required by the plugin.
     */
    public function handle() {
        global $INPUT;
        global $ID;
        if(!$INPUT->has('farmer__submit')) return;

        $data = $this->validateAnimalData();
        if(!$data) return;
        if($this->createNewAnimal($data['name'], $data['admin'], $data['pass'], $data['template'], $data['aclpolicy'], $data['allowreg'])) {
            $url = $this->helper->getAnimalURL($data['name']);
            $link = '<a href="' . $url . '">' . hsc($data['name']) . '</a>';

            msg(sprintf($this->getLang('animal creation success'), $link), 1);
            $link = wl($ID, array('do' => 'admin', 'page' => 'farmer', 'sub' => 'new'), true, '&');
            send_redirect($link);
        }
    }

    /**
     * Render HTML output, e.g. helpful text and a form
     */
    public function html() {
        global $lang;
        $farmconfig = $this->helper->getConfig();

        $form = new \dokuwiki\Form\Form();
        $form->addClass('plugin_farmer')->id('farmer__create_animal_form');

        $form->addFieldsetOpen($this->getLang('animal configuration'));
        $form->addTextInput('animalname', $this->getLang('animal'));
        $form->addFieldsetClose();

        $animals = $this->helper->getAllAnimals();
        array_unshift($animals, '');
        $form->addFieldsetOpen($this->getLang('animal template'));
        $form->addDropdown('animaltemplate', $animals)->addClass('farmer_chosen_animals');
        $form->addFieldsetClose();

        $form->addFieldsetOpen($lang['i_policy'])->attr('id', 'aclPolicyFieldset');
        $policyOptions = array('open' => $lang['i_pol0'],'public' => $lang['i_pol1'], 'closed' => $lang['i_pol2']);
        $form->addDropdown('aclpolicy', $policyOptions)->addClass('acl_chosen');
        if ($farmconfig['inherit']['main']) {
            $form->addRadioButton('allowreg',$this->getLang('inherit user registration'))->val('inherit')->attr('checked', 'checked');
            $form->addRadioButton('allowreg',$this->getLang('enable user registration'))->val('allow');
            $form->addRadioButton('allowreg',$this->getLang('disable user registration'))->val('disable');
        } else {
            $form->addCheckbox('allowreg', $lang['i_allowreg'])->attr('checked', 'checked');
        }

        $form->addFieldsetClose();

        $form->addFieldsetOpen($this->getLang('animal administrator'));
        $btn = $form->addRadioButton('adminsetup', $this->getLang('noUsers'))->val('noUsers');
        if($farmconfig['inherit']['users']) {
            $btn->attr('checked', 'checked');  // default when inherit available
        } else {
            // no user copying when inheriting
            $form->addRadioButton('adminsetup', $this->getLang('importUsers'))->val('importUsers');
            $form->addRadioButton('adminsetup', $this->getLang('currentAdmin'))->val('currentAdmin');
        }
        $btn = $form->addRadioButton('adminsetup', $this->getLang('newAdmin'))->val('newAdmin');
        if(!$farmconfig['inherit']['users']) {
            $btn->attr('checked', 'checked'); // default when inherit not available
        }
        $form->addPasswordInput('adminPassword', $this->getLang('admin password'));
        $form->addFieldsetClose();

        $form->addButton('farmer__submit', $this->getLang('submit'))->attr('type', 'submit')->val('newAnimal');
        echo $form->toHTML();
    }

    /**
     * Validate the data for a new animal
     *
     * @return array|bool false on errors, clean data otherwise
     */
    protected function validateAnimalData() {
        global $INPUT;

        $animalname = $INPUT->filter('trim')->str('animalname');
        $adminsetup = $INPUT->str('adminsetup');
        $adminpass = $INPUT->filter('trim')->str('adminPassword');
        $template = $INPUT->filter('trim')->str('animaltemplate');
        $aclpolicy = $INPUT->filter('trim')->str('aclpolicy');
        $allowreg = $INPUT->str('allowreg');

        $errors = array();

        if($animalname === '') {
            $errors[] = $this->getLang('animalname_missing');
        } elseif(!$this->helper->validateAnimalName($animalname)) {
            $errors[] = $this->getLang('animalname_invalid');
        }

        if($adminsetup === 'newAdmin' && $adminpass === '') {
            $errors[] = $this->getLang('adminPassword_empty');
        }

        if($animalname !== '' && file_exists(DOKU_FARMDIR . '/' . $animalname)) {
            $errors[] = $this->getLang('animalname_preexisting');
        }

        if (!is_dir(DOKU_FARMDIR . $template) && !in_array($aclpolicy,array('open', 'public', 'closed'))) {
            $errors[] = $this->getLang('aclpolicy missing/bad');
        }

        if($errors) {
            foreach($errors as $error) {
                msg($error, -1);
            }
            return false;
        }

        if(!is_dir(DOKU_FARMDIR . $template)) {
            $template = '';
        }
        if ($template != '') {
            $aclpolicy = '';
        }

        return array(
            'name' => $animalname,
            'admin' => $adminsetup,
            'pass' => $adminpass,
            'template' => $template,
            'aclpolicy' => $aclpolicy,
            'allowreg' => $allowreg
        );
    }

    /**
     * Create a new animal
     *
     * @param string $name name/title of the animal, will be the directory name for htaccess setup
     * @param string $adminSetup newAdmin, currentAdmin or importUsers
     * @param string $adminPassword required if $adminSetup is newAdmin
     * @param string $template name of animal to copy
     * @param $aclpolicy
     * @param $userreg
     * @return bool true if successful
     * @throws Exception
     */
    protected function createNewAnimal($name, $adminSetup, $adminPassword, $template, $aclpolicy, $userreg) {
        $animaldir = DOKU_FARMDIR . $name;

        // copy basic template
        $ok = $this->helper->io_copyDir(__DIR__ . '/../_animal', $animaldir);
        if(!$ok) {
            msg($this->getLang('animal creation error'), -1);
            return false;
        }

        // copy animal template
        if($template != '') {
            foreach(array('conf', 'data/pages', 'data/media', 'data/meta', 'data/media_meta', 'index') as $dir) {
                $templatedir = DOKU_FARMDIR . $template . '/' . $dir;
                if(!is_dir($templatedir)) continue;
                // do not copy changelogs in meta
                if(substr($dir, -4) == 'meta') {
                    $exclude = '/\.changes$/';
                } else {
                    $exclude = '';
                }
                if(!$this->helper->io_copyDir($templatedir, $animaldir . '/' . $dir, $exclude)) {
                    msg(sprintf($this->getLang('animal template copy error'), $dir), -1);
                    // we go on anyway
                }
            }
        }

        // append title to local config
        $ok &= io_saveFile($animaldir . '/conf/local.php', "\n" . '$conf[\'title\'] = \'' . $name . '\';' . "\n", true);

        // create a random logo and favicon
        if(!class_exists('\splitbrain\RingIcon\RingIcon', false)) {
            require(__DIR__ . '/../3rdparty/RingIcon.php');
        }
        if(!class_exists('\chrisbliss18\phpico\PHPIco', false)) {
            require(__DIR__ . '/../3rdparty/PHPIco.php');
        }
        try {
            if(function_exists('imagecreatetruecolor')) {
                $logo = $animaldir . '/data/media/wiki/logo.png';
                if(!file_exists($logo)) {
                    $ringicon = new \splitbrain\RingIcon\RingIcon(64);
                    $ringicon->createImage($animaldir, $logo);
                }

                $icon = $animaldir . '/data/media/wiki/favicon.ico';
                if(!file_exists($icon)) {
                    $icongen = new \chrisbliss18\phpico\PHPIco($logo);
                    $icongen->save_ico($icon);
                }
            }
        } catch(\Exception $ignore) {
            // something went wrong, but we don't care. this is a nice to have feature only
        }

        // create admin user
        if($adminSetup === 'newAdmin') {
            $users = "# <?php exit()?>\n" . $this->makeAdminLine($adminPassword) . "\n";
        } elseif($adminSetup === 'currentAdmin') {
            $users = "# <?php exit()?>\n" . $this->getAdminLine() . "\n";
        } elseif($adminSetup === 'noUsers') {
            if(file_exists($animaldir . '/conf/users.auth.php')) {
                // a user file exists already, probably from animal template - don't overwrite
                $users = '';
            } else {
                // create empty user file
                $users = "# <?php exit()?>\n";
            }
        } else {
            $users = io_readFile(DOKU_CONF . 'users.auth.php');
        }
        if($users) {
            $ok &= io_saveFile($animaldir . '/conf/users.auth.php', $users);
        }

        if ($aclpolicy != '') {
            $aclfile = file($animaldir . '/conf/acl.auth.php');
            $aclfile = array_map('trim', $aclfile);
            array_pop($aclfile);
            switch ($aclpolicy) {
                case 'open':
                    $aclfile[] = "* @ALL 8";
                    break;
                case 'public':
                    $aclfile[] = "* @ALL 1";
                    $aclfile[] = "* @user 8";
                    break;
                case 'closed':
                    $aclfile[] = "* @ALL 0";
                    $aclfile[] = "* @user 8";
                    break;
                default:
                    throw new Exception('Undefined aclpolicy given');
            }
            $ok &= io_saveFile($animaldir . '/conf/acl.auth.php', join("\n", $aclfile)."\n");

            global $conf;
            switch ($userreg) {
                case 'allow':
                    $disableactions = join(',', array_diff(explode(',', $conf['disableactions']), array('register')));
                    $ok &= io_saveFile($animaldir . '/conf/local.php', "\n" . '$conf[\'disableactions\'] = \''.$disableactions.'\';' . "\n", true);
                    break;
                case 'disable':
                    $disableactions = join(',', array_merge(explode(',', $conf['disableactions']), array('register')));
                    $ok &= io_saveFile($animaldir . '/conf/local.php', "\n" . '$conf[\'disableactions\'] = \''.$disableactions.'\';' . "\n", true);
                    break;
                case 'inherit':
                case true:
                    // nothing needs to be done
                    break;
                default:
                    $ok &= io_saveFile($animaldir . '/conf/local.php', "\n" . '$conf[\'disableactions\'] = \'register\';' . "\n", true);
            }
        }

        // deactivate plugins by default FIXME this should be nicer
        $deactivatedPluginsList = explode(',', $this->getConf('deactivated plugins'));
        $deactivatedPluginsList = array_map('trim', $deactivatedPluginsList);
        $deactivatedPluginsList = array_unique($deactivatedPluginsList);
        $deactivatedPluginsList = array_filter($deactivatedPluginsList);
        foreach($deactivatedPluginsList as $plugin) {
            $this->helper->setPluginState(trim($plugin), $name, 0);
        }

        return $ok;
    }

    /**
     * Creates a new user line
     *
     * @param $password
     * @return string
     */
    protected function makeAdminLine($password) {
        $pass = auth_cryptPassword($password);
        $line = join(
            ':', array(
                   'admin',
                   $pass,
                   'Administrator',
                   'admin@example.org',
                   'admin,user'
               )
        );
        return $line;
    }

    /**
     * Copies the current user as new admin line
     *
     * @return string
     */
    protected function getAdminLine() {
        $currentAdmin = $_SERVER['REMOTE_USER'];
        $masterUsers = file_get_contents(DOKU_CONF . 'users.auth.php');
        $masterUsers = ltrim(strstr($masterUsers, "\n" . $currentAdmin . ":"));
        $newAdmin = substr($masterUsers, 0, strpos($masterUsers, "\n") + 1);
        return $newAdmin;
    }

}

// vim:ts=4:sw=4:et: