xref: /plugin/farmer/admin/new.php (revision c4c8e953c2820a8d49bd83ac58883b01f220312b)
1<?php
2/**
3 * DokuWiki Plugin farmer (Admin Component)
4 *
5 * @license GPL 2 http://www.gnu.org/licenses/gpl-2.0.html
6 * @author  Michael Große <grosse@cosmocode.de>
7 */
8
9// must be run within Dokuwiki
10if(!defined('DOKU_INC')) die();
11
12class admin_plugin_farmer_new extends DokuWiki_Admin_Plugin {
13
14    /** @var helper_plugin_farmer $helper */
15    protected $helper;
16
17    /**
18     * @return bool true if only access for superuser, false is for superusers and moderators
19     */
20    public function forAdminOnly() {
21        return true;
22    }
23
24    /**
25     * admin_plugin_farmer_new constructor.
26     */
27    public function __construct() {
28        $this->helper = plugin_load('helper', 'farmer');
29    }
30
31    /**
32     * Should carry out any processing required by the plugin.
33     */
34    public function handle() {
35        global $INPUT;
36        global $ID;
37        if(!$INPUT->has('farmer__submit')) return;
38
39        $data = $this->validateAnimalData();
40        if(!$data) return;
41        if($this->createNewAnimal($data['name'], $data['admin'], $data['pass'])){
42            msg($this->getLang('animal creation success'), 1);
43            $link = wl($ID, array('do'=>'admin', 'page'=>'farmer', 'sub'=>'new'), true, '&');
44            send_redirect($link);
45        }
46    }
47
48    /**
49     * Render HTML output, e.g. helpful text and a form
50     */
51    public function html() {
52
53        $form = new \dokuwiki\Form\Form();
54        $form->addClass('plugin_farmer')->id('farmer__create_animal_form');
55
56        $form->addFieldsetOpen($this->getLang('animal configuration'));
57        $form->addTextInput('animalname', $this->getLang('animal name'));
58        $form->addFieldsetClose();
59
60        $form->addFieldsetOpen($this->getLang('animal administrator'));
61        $form->addRadioButton('adminsetup', $this->getLang('importUsers'))->val('importUsers');
62        $form->addRadioButton('adminsetup', $this->getLang('currentAdmin'))->val('currentAdmin');
63        $form->addRadioButton('adminsetup', $this->getLang('newAdmin'))->val('newAdmin')->attr('checked', 'checked');
64        $form->addPasswordInput('adminPassword', $this->getLang('admin password'));
65        $form->addFieldsetClose();
66
67        $form->addButton('farmer__submit', $this->getLang('submit'))->attr('type', 'submit')->val('newAnimal');
68        echo $form->toHTML();
69
70        echo $this->locale_xhtml('tab_new_help');
71    }
72
73    /**
74     * Validate the data for a new animal
75     *
76     * @return array|bool false on errors, clean data otherwise
77     */
78    protected function validateAnimalData() {
79        global $INPUT;
80
81        $animalname = $INPUT->filter('trim')->str('animalname');
82        $adminsetup = $INPUT->str('adminsetup');
83        $adminpass = $INPUT->filter('trim')->str('adminPassword');
84
85        $errors = array();
86
87        if($animalname === '') {
88            $errors[] = $this->getLang('animalname_missing');
89        } elseif(!$this->helper->validateAnimalName($animalname)) {
90            $errors[] = $this->getLang('animalname_invalid');
91        }
92
93        if($adminsetup === 'newAdmin' && $adminpass === '') {
94            $errors[] = $this->getLang('adminPassword_empty');
95        }
96
97        if($animalname !== '' && file_exists(DOKU_FARMDIR . '/' . $animalname)) {
98            $errors[] = $this->getLang('animalname_preexisting');
99        }
100
101        if($errors) {
102            foreach($errors as $error) {
103                msg($error, -1);
104            }
105            return false;
106        }
107
108        return array(
109            'name' => $animalname,
110            'admin' => $adminsetup,
111            'pass' => $adminpass
112        );
113    }
114
115    /**
116     * Create a new animal
117     *
118     * @param string $name name/title of the animal, will be the directory name for htaccess setup
119     * @param string $adminSetup newAdmin, currentAdmin or importUsers
120     * @param string $adminPassword required if $adminSetup is newAdmin
121     * @return bool true if successful
122     */
123    protected function createNewAnimal($name, $adminSetup, $adminPassword) {
124        $animaldir = DOKU_FARMDIR . '/' . $name;
125
126        // copy basic template
127        $ok = $this->helper->io_copyDir(__DIR__ . '/../_animal', $animaldir);
128        if(!$ok) {
129            msg($this->getLang('animal creation error'), -1);
130            return false;
131        }
132
133        // append title to local config
134        $ok &= io_saveFile($animaldir.'/conf/local.php', "\n".'$conf[\'title\'] = \''.$name.'\';'."\n", true);
135
136        // create a random logo and favicon
137        if(!class_exists('\splitbrain\RingIcon\RingIcon', false)) {
138            require(__DIR__ . '/../3rdparty/RingIcon.php');
139        }
140        if(!class_exists('\chrisbliss18\phpico\PHPIco', false)) {
141            require(__DIR__ . '/../3rdparty/PHPIco.php');
142        }
143        try {
144            $ringicon = new \splitbrain\RingIcon\RingIcon(64);
145            $ringicon->createImage($animaldir, $animaldir . '/data/media/wiki/logo.png');
146            $icongen = new \chrisbliss18\phpico\PHPIco($animaldir . '/data/media/wiki/logo.png');
147            $icongen->save_ico($animaldir . '/data/media/wiki/favicon.ico');
148        } catch(\Exception $ignore) {
149            // something went wrong, but we don't care. this is a nice to have feature only
150        }
151
152        // create admin user
153        if($adminSetup === 'newAdmin') {
154            $users = "# <?php exit()?>\n".$this->makeAdminLine($adminPassword)."\n";
155        } elseif($adminSetup === 'currentAdmin') {
156            $users = "# <?php exit()?>\n".$this->getAdminLine()."\n";
157        } else {
158            $users = io_readFile(DOKU_CONF . 'users.auth.php');
159        }
160        $ok &= io_saveFile($animaldir . '/conf/users.auth.php', $users);
161
162        /* FIXME handle deactivated plugins
163        if($this->getConf('deactivated plugins') === '') {
164            $deactivatedPluginsList = array('farmer',);
165        } else {
166            $deactivatedPluginsList = explode(',', $this->getConf('deactivated plugins'));
167            array_push($deactivatedPluginsList, 'farmer');
168        }
169        foreach($deactivatedPluginsList as $plugin) {
170            $this->helper->deactivatePlugin(trim($plugin), $animal);
171        }
172        */
173
174        return $ok;
175    }
176
177    /**
178     * Creates a new user line
179     *
180     * @param $password
181     * @return string
182     */
183    protected function makeAdminLine($password) {
184        $pass = auth_cryptPassword($password);
185        $line = join("\t", array(
186            'admin',
187            $pass,
188            'Administrator',
189            'admin@example.org',
190            'admin,user'
191        ));
192        return $line;
193    }
194
195    /**
196     * Copies the current user as new admin line
197     *
198     * @return string
199     */
200    protected function getAdminLine() {
201        $currentAdmin = $_SERVER['REMOTE_USER'];
202        $masterUsers = file_get_contents(DOKU_CONF . 'users.auth.php');
203        $masterUsers = ltrim(strstr($masterUsers, "\n" . $currentAdmin . ":"));
204        $newAdmin = substr($masterUsers, 0, strpos($masterUsers, "\n") + 1);
205        return $newAdmin;
206    }
207
208
209}
210
211// vim:ts=4:sw=4:et:
212