Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

file 322 lines (269 sloc) 9.894 kb
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 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 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 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321
<?php

/*
* Copyright © 2010 - 2012 Modo Labs Inc. All rights reserved.
*
* The license governing the contents of this file is located in the LICENSE
* file located at the root directory of this distribution. If the LICENSE file
* is missing, please contact sales@modolabs.com.
*
*/

abstract class APIModule extends Module
{
    protected $responseVersion;
    protected $requestedVersion;
    protected $requestedVmin;
    protected $vmin;
    protected $vmax;
    protected $command = '';
    protected $response; //response object
    protected $warnings = array();
  
    public function getVmin() {
        return $this->vmin;
    }

    public function getVmax() {
        return $this->vmax;
    }
    
    public function getPayload() {
        return null;
    }

    public function getWebBridgeConfig() {
        return KurogoWebBridge::getHelloMessageForModule($this->configModule);
    }

    protected function warningHandler($errno, $str, $file, $line) {
        if (!(error_reporting() & $errno)) {
            // This error code is not included in error_reporting
            return;
        }
        
        $this->loadResponseIfNeeded();
        $this->response->addWarning(new KurogoWarning($errno, $str, $file, $line));
        
        return true;
    }

   /**
* Set the command
* @param string the command
*/
    protected function setCommand($command) {
        $this->command = $command;
    }
    
   /**
* The module is disabled.
*/
    protected function moduleDisabled() {
        $error = new KurogoError(2, 'Module Disabled', 'This module has been disabled');
        $this->throwError($error);
    }
    
   /**
* The module must be run securely (https)
*/
    protected function secureModule() {
        $error = new KurogoError(3, 'Secure access required', 'This module must be used using https');
        $this->throwError($error);
    }
  
   /**
* The user cannot access this module
*/
    protected function unauthorizedAccess() {
        $error = new KurogoError(4, 'Unauthorized', 'You are not permitted to use the '.$this->getModuleVar('title', 'module').' module');
        $this->throwError($error);
    }
  
   /**
* An unrecognized command was requested
*/
    protected function invalidCommand() {
        $error = new KurogoError(5, 'Invalid Command', "The $this->id module does not understand $this->command");
        $this->throwError($error);
    }
  
   /**
* The module was unable to load the version requested
*/
    protected function noVersionAvailable() {
        $error = new KurogoError(6, 'No version available', "A command matching the specified version could not be processed");
        $this->throwError($error);
    }
  
   /**
* Sets the error portion of the response. Some messages can return both a response and an error
* @param KurogoError $error an error object
*/
    protected function setResponseError(KurogoError $error) {
        $this->loadResponseIfNeeded();
        $this->response->setError($error);
    }
  
   /**
* Set the response text. Typically an object or associate array (a dictionary)
*/
    protected function setResponse($response) {
        $this->loadResponseIfNeeded();
        $this->response->setResponse($response);
    }
   
   /**
* Throw a fatal error in the API. Used for user created errors like invalid parameters. Stops
* execution and displays the error
* @param KurogoError $user a valid error object
*/
    protected function throwError(KurogoError $error) {
        $this->loadResponseIfNeeded();
        $this->setResponseError($error);
        if (is_null($this->responseVersion)) {
            $this->setResponseVersion(0);
        }
        $this->response->display();
        exit();
    }
  
    protected function redirectTo($command, $args=array()) {
        $url = URL_BASE . API_URL_PREFIX . "/$this->id/$command";
    
        if (count($args)) {
          $url .= http_build_query($args);
        }
        
        //error_log('Redirecting to: '.$url);
        Kurogo::redirectToURL($url);
    }

   /**
* Factory method
* @param string $id the module id to load
* @param string $command the command to execute
* @param array $args an array of arguments
* @return APIModule
*/
    public static function factory($id, $command='', $args=array()) {

        if (!$module = parent::factory($id, 'api')) {
            return false;
        }
        if ($command) {
            $module->init($command, $args);
        }

        return $module;
    }

    protected function getAPIConfig($name, $opts=0) {
        $opts = $opts | ConfigFile::OPTION_CREATE_WITH_DEFAULT;
        $config = ModuleConfigFile::factory($this->configModule, "api-$name", $opts, $this);
        return $config;
    }

    protected function getAPIConfigData($name) {
        $config = $this->getAPIConfig($name);
        return $config->getSectionVars(Config::EXPAND_VALUE);
    }

    protected function getModuleNavigationData() {
        $moduleNavConfig = $this->getModuleNavigationConfig();
        $modules = array(
            'primary' => $moduleNavConfig->getOptionalSection('primary_modules'),
            'secondary'=> $moduleNavConfig->getOptionalSection('secondary_modules')
        );

        return $modules;
    }

    protected function getModuleNavigationIDs() {
        $moduleNavConfig = $this->getModuleNavigationConfig();
        
        $modules = array(
            'primary' => array_keys($moduleNavConfig->getOptionalSection('primary_modules')),
            'secondary'=> array_keys($moduleNavConfig->getOptionalSection('secondary_modules'))
        );

        return $modules;
    }
   
    public static function getAllModules() {
        $configFiles = glob(SITE_CONFIG_DIR . "/*/module.ini");
        $modules = array();
    
        foreach ($configFiles as $file) {
            if (preg_match("#" . preg_quote(SITE_CONFIG_DIR,"#") . "/([^/]+)/module.ini$#", $file, $bits)) {
                $id = $bits[1];
                try {
                    if ($module = APIModule::factory($id)) {
                       $modules[$id] = $module;
                    }
                } catch (KurogoException $e) {
                }
            }
        }
        ksort($modules);
        return $modules;
      }


   /**
* Lazy load the response object
*/
    private function loadResponseIfNeeded() {
        if (!isset($this->response)) {
            $this->response = new APIResponse($this->id, $this->configModule, $this->command);
        }
    }
    
   /**
* Sets the requested version and minimum accepted version
*/
    private function setRequestedVersion($requestedVersion, $minimumVersion) {
        if ($requestedVersion) {
            $this->requestedVersion = intval($requestedVersion);
    
            if ($minimumVersion) {
                $this->requestedVmin = intval($minimumVersion);
            } else {
                $this->requestedVmin = $this->requestedVersion;
            }
        } else {
            $this->requestedVersion = null;
            $this->requestedVmin = null;
        }
    }
    
   /**
* Called by the modules to set what version we are returning to the client_info
* @param int $version the version we are returning
*/
    protected function setResponseVersion($version) {
        $this->loadResponseIfNeeded();
        $this->response->setVersion($version);
        $this->responseVersion = $this->response->getVersion();
    }
    
    protected function setContext($context) {
        $this->loadResponseIfNeeded();
        $this->context = $context;
        $this->response->setContext($context);
    }
  
   /**
* Initialize the request
*/
    protected function init($command='', $args=array()) {
        set_error_handler(array($this, 'warningHandler'), E_WARNING | E_NOTICE | E_STRICT);
        
        parent::init();
        $this->setArgs($args);
        $this->setRequestedVersion($this->getArg('v', null), $this->getArg('vmin', null));
        if ($context = $this->getArg('context', null)) {
            $this->setContext($context);
        }
        $this->setCommand($command);
    }
  
    protected function loadSiteConfigFile($name, $opts=0) {
        $config = ConfigFile::factory($name, 'site', $opts);
        Kurogo::siteConfig()->addConfig($config);
    
        return $config->getSectionVars(true);
    }
    
   /**
* Execute the command. Will call initializeForCommand() which should set the version, error and response
* values appropriately
*/
    public function executeCommand() {
        if (empty($this->command)) {
            throw new KurogoException("Command not specified");
        }
        $this->loadResponseIfNeeded();
        $this->loadSiteConfigFile('strings');
    
        $this->initializeForCommand();
        
        $json = $this->response->getJSONOutput();
        $size = strlen($json);
        if ($this->logView) {
            $this->logCommand($size);
        }
        header("Content-Length: " . $size);
        header("Content-Type: application/json; charset=utf-8");
        echo $json;
        exit();
    }
    
    protected function logCommand($size=null) {
        KurogoStats::logView('api', $this->configModule, $this->command, $this->logData, $this->logDataLabel, $size);
    }
      
   /**
* All modules must implement this method to handle the logic of each command.
*/
    abstract protected function initializeForCommand();
  
    /**
* Implement if your app supports the buildNative command for native app shim modules.
* Return a list of pages supported by your native app shim templates.
*/
    protected function getNativePagelist() {
        return array();
    }
}



Something went wrong with that request. Please try again.