xref: /plugin/farmer/helper.php (revision a646d51957345f8381be2a22b73b0bf048cf637d)
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        $list = glob(DOKU_FARMDIR . '/*/conf/', GLOB_ONLYDIR);
103        foreach($list as $path) {
104            $animal = basename(dirname($path));
105            if($animal == '_animal') continue; // old template
106            $animals[] = $animal;
107        }
108        sort($animals);
109        return $animals;
110    }
111
112    /**
113     * Actiate a specific plugin in a specific animal
114     *
115     * @param string $plugin Name of the plugin to be activated
116     * @param string $animal Directory of the animal within DOKU_FARMDIR
117     */
118    public function activatePlugin($plugin, $animal) {
119        if (isset($this->allPlugins[$animal])) {
120            $plugins = $this->allPlugins[$animal];
121        } else {
122            include(DOKU_FARMDIR . $animal . '/conf/plugins.local.php');
123        }
124        if (isset($plugins[$plugin]) && $plugins[$plugin] === 0) {
125            unset($plugins[$plugin]);
126            $this->writePluginConf($plugins, $animal);
127        }
128        $this->allPlugins[$animal] = $plugins;
129    }
130
131    /**
132     * @param string $plugin Name of the plugin to be deactivated
133     * @param string $animal Directory of the animal within DOKU_FARMDIR
134     */
135    public function deactivatePlugin($plugin, $animal) {
136        if (isset($this->allPlugins[$animal])) {
137            $plugins = $this->allPlugins[$animal];
138        } else {
139            include(DOKU_FARMDIR . $animal . '/conf/plugins.local.php');
140        }
141        if (!isset($plugins[$plugin]) || $plugins[$plugin] !== 0) {
142            $plugins[$plugin] = 0;
143            $this->writePluginConf($plugins, $animal);
144        }
145        $this->allPlugins[$animal] = $plugins;
146    }
147
148    /**
149     * Write the list of (deactivated) plugins as plugin configuration of an animal to file
150     *
151     * @param array  $plugins associative array with the key being the plugin name and the value 0 or 1
152     * @param string $animal  Directory of the animal within DOKU_FARMDIR
153     */
154    public function writePluginConf($plugins, $animal) {
155        $pluginConf = '<?php' . "\n";
156        foreach ($plugins as $plugin => $status) {
157            $pluginConf .= '$plugins["' . $plugin  . '"] = ' . $status . ";\n";
158        }
159        io_saveFile(DOKU_FARMDIR . $animal . '/conf/plugins.local.php', $pluginConf);
160        touch(DOKU_FARMDIR . $animal . '/conf/local.php');
161    }
162
163    /**
164     * Show a message for all errors which occured during form validation
165     *
166     * @param \dokuwiki\Form\Form $form        The form to which the errors should be added.
167     * @param array               $errorArray  An associative array with the key being the name of the element at fault
168     *                                         and the value being the associated error message.
169     */
170    public function addErrorsToForm(\dokuwiki\Form\Form &$form, $errorArray) {
171        foreach ($errorArray as $elementName => $errorMessage) {
172            $offset = 0;
173            msg($errorMessage, -1);
174            while ($form->findPositionByAttribute('name',$elementName, $offset)) {
175                $offset = $form->findPositionByAttribute('name',$elementName, $offset);
176                $form->getElementAt($offset)->addClass('error');
177                ++$offset;
178            }
179        }
180    }
181
182    /**
183     * @param string|null $page load adminpage $page, reload the current page if $page is ommited or null
184     */
185    public function reloadAdminPage($page = null) {
186        global $ID;
187        $get = $_GET;
188        if(isset($get['id'])) unset($get['id']);
189        if ($page !== null ) {
190            $get['page'] = $page;
191        }
192        $self = wl($ID, $get, false, '&');
193        send_redirect($self);
194    }
195
196    /**
197     * Download and extract the animal template
198     *
199     * @param string $animalpath
200     *
201     * @throws \splitbrain\PHPArchive\ArchiveIOException
202     */
203    public function downloadTemplate($animalpath) {
204        file_put_contents($animalpath . '/_animal.zip',fopen('https://www.dokuwiki.org/_media/dokuwiki_farm_animal.zip','r'));
205        $zip = new splitbrain\PHPArchive\Zip();
206        $zip->open($animalpath.'/_animal.zip');
207        $zip->extract($animalpath);
208        $zip->close();
209        unlink($animalpath.'/_animal.zip');
210    }
211
212    /**
213     * checks wether $path is in under $container
214     *
215     * @param string $path
216     * @param string $container
217     * @return bool
218     */
219    public function isInPath ($path, $container) {
220        return (strpos(fullpath($path), fullpath($container)) === 0);
221    }
222
223    /**
224     * Check if the farm is correctly configured for this farmer plugin
225     *
226     * @return bool
227     */
228    public function checkFarmSetup () {
229        return defined('DOKU_FARMDIR') && isset($GLOBALS['FARMCORE']);
230    }
231
232    /**
233     * The subdomain must contain at least two dots
234     *
235     * @link http://stackoverflow.com/questions/17986371/regular-expression-to-validate-fqdn-in-c-sharp-and-javascript
236     *
237     * @param string $subdomain
238     *
239     * @return bool
240     */
241    public function validateSubdomain ($subdomain) {
242        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;
243    }
244
245    /**
246     * @param string $animalname
247     *
248     * @return bool
249     */
250    public function validateAnimalName ($animalname) {
251        return preg_match("/^[a-z0-9]+(-[a-z0-9]+)*$/i",$animalname) === 1;
252    }
253
254    /**
255     * @return string
256     */
257    public function getUserLine($currentAdmin) {
258        $masterUsers = file_get_contents(DOKU_CONF . 'users.auth.php');
259        $masterUsers = ltrim(strstr($masterUsers, "\n" . $currentAdmin . ":"));
260        $newAdmin = substr($masterUsers, 0, strpos($masterUsers, "\n") + 1);
261        return $newAdmin;
262    }
263
264}
265