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