ServiceController.php 8.23 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
<?php
/**
 *    Copyright (C) 2015 Deciso B.V.
 *
 *    All rights reserved.
 *
 *    Redistribution and use in source and binary forms, with or without
 *    modification, are permitted provided that the following conditions are met:
 *
 *    1. Redistributions of source code must retain the above copyright notice,
 *       this list of conditions and the following disclaimer.
 *
 *    2. Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *
 *    THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
 *    INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
 *    AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *    AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
 *    OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 *    SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 *    INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 *    CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 *    ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *    POSSIBILITY OF SUCH DAMAGE.
 *
 */
namespace OPNsense\CaptivePortal\Api;

use \OPNsense\Base\ApiControllerBase;
use \OPNsense\Core\Backend;
33
use \OPNsense\CaptivePortal\CaptivePortal;
34 35
use \OPNsense\Core\Config;
use \OPNsense\Base\UIModelGrid;
36
use \Phalcon\Filter;
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58

/**
 * Class ServiceController
 * @package OPNsense\CaptivePortal
 */
class ServiceController extends ApiControllerBase
{

    /**
     * reconfigure captive portal
     */
    public function reconfigureAction()
    {
        if ($this->request->isPost()) {
            // close session for long running action
            $this->sessionClose();

            $backend = new Backend();
            // the ipfw rules need to know about all the zones, so we need to reload ipfw for the portal to work
            $backend->configdRun("template reload OPNsense.IPFW");
            $bckresult = trim($backend->configdRun("ipfw reload"));
            if ($bckresult == "OK") {
59
                // generate captive portal config
60 61 62 63 64 65 66 67 68 69 70
                $bckresult = trim($backend->configdRun("template reload OPNsense.Captiveportal"));
                if ($bckresult == "OK") {
                    $mdlCP = new CaptivePortal();
                    if ($mdlCP->isEnabled()) {
                        $bckresult = trim($backend->configdRun("captiveportal restart"));
                        if ($bckresult == "OK") {
                            $status = "ok";
                        } else {
                            $status = "error reloading captive portal";
                        }
                    } else {
71
                        $backend->configdRun("captiveportal stop");
72 73 74 75 76
                        $status = "ok";
                    }
                } else {
                    $status = "error reloading captive portal template";
                }
77
            } else {
78
                $status = "error reloading captive portal rules (" . $bckresult . ")";
79 80 81 82 83 84 85
            }

            return array("status" => $status);
        } else {
            return array("status" => "failed");
        }
    }
86 87

    /**
88
     * @param null $fileid unique template id (fileid field)
89 90 91
     * @return mixed
     * @throws \Exception
     */
92
    public function getTemplateAction($fileid = null)
93 94 95
    {
        // get template name
        $paramfilter = new Filter();
96 97
        if ($fileid != null) {
            $templateFileId = $paramfilter->sanitize($fileid, 'alphanum');
98
        } else {
99
            $templateFileId = 'default';
100 101 102 103
        }

        // request template data and output result (zipfile)
        $backend = new Backend();
104
        $response = $backend->configdpRun("captiveportal fetch_template", array($templateFileId));
105 106 107 108 109
        $result = json_decode($response, true);
        if ($result != null) {
            $response = $result['payload'];
            $this->response->setContentType('application/octet-stream', 'UTF-8');
            $this->response->setHeader(
110 111
                'Content-Disposition:',
                "Attachment; filename=\"template_" . $templateFileId . ".zip\""
112
            );
113
            $this->response->setHeader('Content-Type:', 'application/zip');
114 115 116 117 118 119 120
            return base64_decode($response);
        } else {
            // return empty response on error
            return "";
        }
    }

121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141

    /**
     * save template, updates existing or create new.
     * @return string
     */
    public function saveTemplateAction()
    {
        if ($this->request->isPost() && $this->request->hasPost("name")) {
            $this->sessionClose();
            $templateName = $this->request->getPost("name", "striptags");
            $mdlCP = new CaptivePortal();
            if ($this->request->hasPost("uuid")) {
                $uuid = $this->request->getPost("uuid", "striptags");
                $template = $mdlCP->getNodeByReference('templates.template.'.$uuid);
                if ($template == null) {
                    return array("name" => $templateName, "error" => "node not found");
                }
            } else {
                $template = $mdlCP->getTemplateByName($templateName);
            }

142
            // cleanse input content, we only want to save changed files into our config
143 144 145
            if (strlen($this->request->getPost("content", "striptags", "")) > 20
                || strlen((string)$template->content) == 0
            ) {
146
                $temp_filename = 'cp_' . (string)$template->getAttributes()['uuid'] . '.tmp';
147
                file_put_contents('/tmp/'.$temp_filename, $this->request->getPost("content", "striptags", ""));
148
                // strip defaults and unchanged files from template (standard js libs, etc)
149 150
                $backend = new Backend();
                $response = $backend->configdpRun("captiveportal strip_template", array($temp_filename));
151
                unlink('/tmp/'.$temp_filename);
152 153 154 155 156 157
                $result = json_decode($response, true);
                if ($result != null && !array_key_exists('error', $result)) {
                    $template->content = $result['payload'];
                } else {
                    return array("name" => $templateName, "error" => $result['error']);
                }
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178
            }

            $template->name = $templateName;
            $valMsgs = $mdlCP->performValidation();
            $errorMsg = "";
            foreach ($valMsgs as $field => $msg) {
                if ($errorMsg != "") {
                    $errorMsg .= " , ";
                }
                $errorMsg .= $msg->getMessage();
            }

            if ($errorMsg != "") {
                return array("name" => (string)$template->name, "error" => $errorMsg);
            } else {
                // data is valid, save and return.
                $mdlCP->serializeToConfig();
                Config::getInstance()->save();
                return array("name" => (string)$template->name);
            }
        }
Ad Schellevis's avatar
Ad Schellevis committed
179
        return null;
180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
    }

    /**
     * delete template by uuid
     * @param $uuid item unique id
     * @return array status
     */
    public function delTemplateAction($uuid)
    {
        $result = array("result"=>"failed");
        if ($this->request->isPost()) {
            $mdlCP = new CaptivePortal();
            if ($uuid != null) {
                if ($mdlCP->templates->template->del($uuid)) {
                    // if item is removed, serialize to config and save
                    $mdlCP->serializeToConfig();
                    Config::getInstance()->save();
                    $result['result'] = 'deleted';
                } else {
                    $result['result'] = 'not found';
                }
            }
        }
        return $result;
    }


    /**
     * search captive portal zones
     * @return array
     */
    public function searchTemplatesAction()
    {
213 214 215 216 217 218 219 220
        $this->sessionClose();
        $mdlCP = new CaptivePortal();
        $grid = new UIModelGrid($mdlCP->templates->template);
        return $grid->fetchBindRequest(
            $this->request,
            array("name", "fileid"),
            "name"
        );
221
    }
222
}