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