xref: /plugin/farmer/helper.php (revision da0ae2c0252db3e5c2ed377b5e8c5f4d93cc81bb)
1<?php
2/**
3 * DokuWiki Plugin farmer (Helper 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 helper_plugin_farmer extends DokuWiki_Plugin {
13
14    private $allPlugins = array();
15
16    /**
17     * Returns the name of the current animal if any, false otherwise
18     *
19     * @return string|false
20     */
21    public function getAnimal() {
22        if(defined('DOKU_FARM_ANIMAL')) return DOKU_FARM_ANIMAL;
23        return false;
24    }
25
26    /**
27     * Copy a file, or recursively copy a folder and its contents. Adapted for DokuWiki.
28     *
29     * @todo: needs tests
30     *
31     * @author      Aidan Lister <aidan@php.net>
32     * @author      Michael Große <grosse@cosmocode.de>
33     * @version     1.0.1
34     * @link        http://aidanlister.com/2004/04/recursively-copying-directories-in-php/
35     *
36     * @param       string $source       Source path
37     * @param       string $destination  Destination path
38     *
39     * @return      bool     Returns TRUE on success, FALSE on failure
40     */
41    function io_copyDir($source, $destination) {
42        if (is_link($source)) {
43            io_lock($destination);
44            $result=symlink(readlink($source), $destination);
45            io_unlock($destination);
46            return $result;
47        }
48
49        if (is_file($source)) {
50            io_lock($destination);
51            $result=copy($source, $destination);
52            io_unlock($destination);
53            return $result;
54        }
55
56        if (!is_dir($destination)) {
57            io_mkdir_p($destination);
58        }
59
60        $dir = dir($source);
61        while (false !== ($entry = $dir->read())) {
62            if ($entry == '.' || $entry == '..') {
63                continue;
64            }
65
66            // recurse into directories
67            $this->io_copyDir("$source/$entry", "$destination/$entry");
68        }
69
70        $dir->close();
71        return true;
72    }
73
74    /**
75     * get a list of all Plugins installed in the farmer wiki, regardless whether they are active or not.
76     *
77     * @return array
78     */
79    public function getAllPlugins() {
80        $dir = dir(DOKU_PLUGIN);
81        $plugins = array();
82        while (false !== ($entry = $dir->read())) {
83            if($entry == '.' || $entry == '..' || $entry == 'testing' || $entry == 'farmer') {
84                continue;
85            }
86            if (!is_dir(DOKU_PLUGIN ."/$entry")) {
87                continue;
88            }
89            $plugins[] = $entry;
90        }
91        sort($plugins);
92        return $plugins;
93    }
94
95    /**
96     * List of all animals, i.e. directories within DOKU_FARMDIR without the template.
97     *
98     * @return array
99     */
100    public function getAllAnimals() {
101        $animals = array();
102
103        $dir = dir(DOKU_FARMDIR);
104        while (false !== ($entry = $dir->read())) {
105            if ($entry == '.' || $entry == '..' || $entry == '_animal' || $entry == '.htaccess') {
106                continue;
107            }
108            if (!is_dir(DOKU_FARMDIR . $entry)) {
109                continue;
110            }
111            $animals[] = $entry;
112        }
113        $dir->close();
114        return $animals;
115    }
116
117    /**
118     * Actiate a specific plugin in a specific animal
119     *
120     * @param string $plugin Name of the plugin to be activated
121     * @param string $animal Directory of the animal within DOKU_FARMDIR
122     */
123    public function activatePlugin($plugin, $animal) {
124        if (isset($this->allPlugins[$animal])) {
125            $plugins = $this->allPlugins[$animal];
126        } else {
127            include(DOKU_FARMDIR . $animal . '/conf/plugins.local.php');
128        }
129        if (isset($plugins[$plugin]) && $plugins[$plugin] === 0) {
130            unset($plugins[$plugin]);
131            $this->writePluginConf($plugins, $animal);
132        }
133        $this->allPlugins[$animal] = $plugins;
134    }
135
136    /**
137     * @param string $plugin Name of the plugin to be deactivated
138     * @param string $animal Directory of the animal within DOKU_FARMDIR
139     */
140    public function deactivatePlugin($plugin, $animal) {
141        if (isset($this->allPlugins[$animal])) {
142            $plugins = $this->allPlugins[$animal];
143        } else {
144            include(DOKU_FARMDIR . $animal . '/conf/plugins.local.php');
145        }
146        if (!isset($plugins[$plugin]) || $plugins[$plugin] !== 0) {
147            $plugins[$plugin] = 0;
148            $this->writePluginConf($plugins, $animal);
149        }
150        $this->allPlugins[$animal] = $plugins;
151    }
152
153    /**
154     * Write the list of (deactivated) plugins as plugin configuration of an animal to file
155     *
156     * @param array  $plugins associative array with the key being the plugin name and the value 0 or 1
157     * @param string $animal  Directory of the animal within DOKU_FARMDIR
158     */
159    public function writePluginConf($plugins, $animal) {
160        $pluginConf = '<?php' . "\n";
161        foreach ($plugins as $plugin => $status) {
162            $pluginConf .= '$plugins["' . $plugin  . '"] = ' . $status . ";\n";
163        }
164        io_saveFile(DOKU_FARMDIR . $animal . '/conf/plugins.local.php', $pluginConf);
165        touch(DOKU_FARMDIR . $animal . '/conf/local.php');
166    }
167
168    /**
169     * Show a message for all errors which occured during form validation
170     *
171     * @param \dokuwiki\Form\Form $form        The form to which the errors should be added.
172     * @param array               $errorArray  An associative array with the key being the name of the element at fault
173     *                                         and the value being the associated error message.
174     */
175    public function addErrorsToForm(\dokuwiki\Form\Form &$form, $errorArray) {
176        foreach ($errorArray as $elementName => $errorMessage) {
177            $offset = 0;
178            msg($errorMessage, -1);
179            while ($form->findPositionByAttribute('name',$elementName, $offset)) {
180                $offset = $form->findPositionByAttribute('name',$elementName, $offset);
181                $form->getElementAt($offset)->addClass('error');
182                ++$offset;
183            }
184        }
185    }
186
187    /**
188     * @param string|null $page load adminpage $page, reload the current page if $page is ommited or null
189     */
190    public function reloadAdminPage($page = null) {
191        global $ID;
192        $get = $_GET;
193        if(isset($get['id'])) unset($get['id']);
194        if ($page !== null ) {
195            $get['page'] = $page;
196        }
197        $self = wl($ID, $get, false, '&');
198        send_redirect($self);
199    }
200
201    /**
202     * Download and extract the animal template
203     *
204     * @param string $animalpath
205     *
206     * @throws \splitbrain\PHPArchive\ArchiveIOException
207     */
208    public function downloadTemplate($animalpath) {
209        file_put_contents($animalpath . '/_animal.zip',fopen('https://www.dokuwiki.org/_media/dokuwiki_farm_animal.zip','r'));
210        $zip = new splitbrain\PHPArchive\Zip();
211        $zip->open($animalpath.'/_animal.zip');
212        $zip->extract($animalpath);
213        $zip->close();
214        unlink($animalpath.'/_animal.zip');
215    }
216
217    /**
218     * checks wether $path is in under $container
219     *
220     * @param string $path
221     * @param string $container
222     * @return bool
223     */
224    public function isInPath ($path, $container) {
225        return (strpos(fullpath($path), fullpath($container)) === 0);
226    }
227
228    /**
229     * Check if the farm is correctly configured for this farmer plugin
230     *
231     * @return bool
232     */
233    public function checkFarmSetup () {
234        return defined('DOKU_FARMDIR') && isset($GLOBALS['FARMCORE']);
235    }
236
237    /**
238     * The subdomain must contain at least two dots
239     *
240     * @link http://stackoverflow.com/questions/17986371/regular-expression-to-validate-fqdn-in-c-sharp-and-javascript
241     *
242     * @param string $subdomain
243     *
244     * @return bool
245     */
246    public function validateSubdomain ($subdomain) {
247        return preg_match("/^(?=.{1,254}$)((?=[a-z0-9-]{1,63}\.)(xn--+)?[a-z0-9]+(-[a-z0-9]+)*\.){2,}[a-z]{2,63}$/i",$subdomain) === 1;
248    }
249
250    /**
251     * @param string $animalname
252     *
253     * @return bool
254     */
255    public function validateAnimalName ($animalname) {
256        return preg_match("/^[a-z0-9]+(-[a-z0-9]+)*$/i",$animalname) === 1;
257    }
258
259    /**
260     * @return string
261     */
262    public function getUserLine($currentAdmin) {
263        $masterUsers = file_get_contents(DOKU_CONF . 'users.auth.php');
264        $masterUsers = ltrim(strstr($masterUsers, "\n" . $currentAdmin . ":"));
265        $newAdmin = substr($masterUsers, 0, strpos($masterUsers, "\n") + 1);
266        return $newAdmin;
267    }
268
269}
270