/**
  * @brief Initializes the API Request Process.
  *
  * ## Overview
  * This will parse various request parameters and attemp to call the 
  * respective action on an object controller.
  *
  * @uses spl_autoload_register()
  * @see index.php
  *
  * @return {Null} Always unless fatal error or exception is thrown.
  *
  * @author TronNet DevOps [Sean Murray] <*****@*****.**>
  * @date 02/19/2014
  */
 public static function Init($params = null)
 {
     try {
         if (count($_POST)) {
             // Auth always required
             $method = 'post';
             $params = $_POST;
         } else {
             // Some auth may be required
             $method = 'get';
             $params = $_GET;
         }
         DebugHandler::Log(var_export($params, true));
         DebugHandler::Log(var_export($method, true));
         DebugHandler::Log(var_export($_SERVER['REQUEST_URI'], true));
         $noGet = explode('?', $_SERVER['REQUEST_URI']);
         $delReqParams = explode('/', $noGet[0]);
         DebugHandler::Log(var_export($delReqParams, true));
         array_shift($delReqParams);
         DebugHandler::Log(var_export($delReqParams, true));
         if (isset($delReqParams[0]) && !empty($delReqParams[0])) {
             $params['_action'] = $delReqParams[0];
             if (isset($delReqParams[1]) && !empty($delReqParams[1])) {
                 $params['_target'] = $delReqParams[1];
                 array_shift($delReqParams);
             }
         }
         if (!isset($params['_target'])) {
             throw new Exception('No target was provided');
         }
         DebugHandler::Log(var_export($params, true));
         $className = $params['_target'];
         $action = $params['_action'];
         $controller = $className . 'Controller';
         DebugHandler::Log(var_export(SATANBARBARA_API_NAMESPACE . $controller . '::ValidRequestMethod::' . $action, true));
         if (call_user_func(SATANBARBARA_API_NAMESPACE . $controller . '::ValidRequestMethod', $method, $action)) {
             $filteredParams = call_user_func(SATANBARBARA_API_NAMESPACE . $controller . '::FilterParams', $method, $action, $params);
             $data = call_user_func(SATANBARBARA_API_NAMESPACE . $controller . '::' . $action, $filteredParams);
         } else {
             throw new Exception('This action cannot be envoked through the get method!');
         }
         AJAX::Response('json', $data);
     } catch (Exception $e) {
         AJAX::Response('json', array(), 1, $e->getMessage());
     }
 }
 public static function Fetch($ids = array(-1), $fields = array('*'), $limit = 20, $offset = 0, $orderBy = 'id', $orderByDir = 'ASC', $groupBy = 'id', $criteria = null, $delineation = null, $operator = null)
 {
     $obj = SATANBARBARA_API_NAMESPACE . static::$_ENTITY;
     $objSet = array();
     $mergers = array();
     $results = array();
     $visible = array_keys(self::GetProperties(BaseEntity::EAP_READ_ONLY));
     $start = $end = null;
     if (!is_array($ids)) {
         $ids = explode(',', $ids);
     }
     if (!is_array($fields)) {
         $fields = explode(',', $fields);
     }
     /**
      * @todo maybe make this more smart and search the array and slice, instead of first index
      */
     if (in_array('*', $fields)) {
         $filteredFields = $visible;
     } else {
         if (in_array('count', $fields)) {
             $filteredFields = $fields;
         } else {
             $filteredFields = array_intersect($fields, $visible);
             if (!count($filteredFields)) {
                 $filteredFields = $visible;
             }
         }
     }
     if (isset($criteria)) {
         if (isset($criteria['dateStart'])) {
             $start = $criteria['dateStart'];
         }
         if (isset($criteria['dateEnd'])) {
             $end = $criteria['dateEnd'];
         }
         $filteredCriteria = static::Filter($criteria);
     } else {
         $filteredCriteria = null;
     }
     if (isset(static::$mergers) && in_array("mergers", $fields)) {
         unset($fields[array_search("mergers", $fields)]);
         foreach (static::$mergers as $entity => $merger) {
             if ($merger['fields'] == '*') {
                 $manager = SATANBARBARA_API_NAMESPACE . $entity . 'Manager';
                 $propertyDirectives = call_user_func($manager . '::GetProperties', BaseEntity::EAP_READ_ONLY);
                 $merger['fields'] = array_keys($propertyDirectives);
             }
             $mergers[$entity] = $merger;
         }
     }
     if ($ids[0] == -1) {
         $resultSet = Storage::FetchAll(Storage::MYSQL, $filteredFields, $limit, $offset, $orderBy, $orderByDir, $groupBy, $filteredCriteria, $delineation, $operator, $mergers, $start, $end, self::$_STORAGE_NAMESPACE, static::$_KEY);
         DebugHandler::Log(var_export($resultSet, true));
         foreach (array_keys($resultSet) as $id) {
             $results[$id] = $resultSet[$id][0];
             $results[$id]['id'] = $id;
         }
     } else {
         $resultSet = Storage::FetchByIDs(Storage::MYSQL, $ids, $filteredFields, $mergers, self::$_STORAGE_NAMESPACE, static::$_KEY);
         DebugHandler::Log(var_export($resultSet, true));
         foreach (array_keys($resultSet) as $id) {
             $results[$id] = $resultSet[$id][0];
             $results[$id]['id'] = $id;
         }
     }
     DebugHandler::Log(var_export($results, true));
     return $results;
 }
 public static function FetchAll($table, $fields, $limit, $offset, $orderBy = 'id', $orderByDir = 'ASC', $groupBy = 'id', $criteria = null, $delineation = null, $operator = null, $associations = null, $start = null, $end = null)
 {
     $db = self::getHandle();
     $isCount = false;
     if ($groupBy == 'none') {
         $groupBy = null;
     }
     if (in_array('count', $fields)) {
         $isCount = true;
         $fieldsCondenced = '`' . $table . '`.`id`';
         $countSubWrapBegin = 'SELECT COUNT(*) AS `total` FROM (';
         $countSubWrapEnd = ') `' . $table . '`';
         array_shift($fields);
     } else {
         $fieldsCondenced = '`' . $table . '`.`' . implode($fields, '`, `' . $table . '`.`') . '`';
         if ($groupBy) {
             if (!in_array($groupBy, $fields)) {
                 if (!in_array('id', $fields)) {
                     $groupBy = $fields[0];
                 } else {
                     $groupBy = 'id';
                 }
             }
         }
         if ($orderBy) {
             if (!in_array($orderBy, $fields)) {
                 if (!in_array('id', $fields)) {
                     $orderBy = $fields[0];
                 } else {
                     $orderBy = 'id';
                 }
             }
         }
     }
     if (empty($orderByDir) || $orderByDir != 'ASC' && $orderByDir != 'DESC') {
         $orderByDir = 'ASC';
     }
     $association = '';
     $where = 'WHERE ';
     $whereParams = array();
     $counter = 0;
     $bindParamKey = '';
     if (is_array($criteria)) {
         foreach ($criteria as $key => $value) {
             if ($counter) {
                 switch ($delineation) {
                     case 'and':
                         $where .= ' AND ';
                         break;
                     case 'or':
                         $where .= ' OR ';
                         break;
                 }
             }
             $bindParamKey = ':crit' . $counter++;
             switch ($operator) {
                 case 'like':
                     $where .= ' `' . $table . '`.`' . $key . '` LIKE ' . $bindParamKey;
                     $whereParams[$bindParamKey] = $value . '%';
                     break;
                 case 'fuzzy':
                     $where .= ' `' . $table . '`.`' . $key . '` LIKE ' . $bindParamKey;
                     $whereParams[$bindParamKey] = '%' . $value . '%';
                     break;
                 case 'eq':
                     $where .= ' `' . $table . '`.`' . $key . '`=' . $bindParamKey;
                     $whereParams[$bindParamKey] = $value;
                     break;
             }
         }
     }
     if (is_array($associations)) {
         foreach ($associations as $key => $assocIdentity) {
             $association = ' LEFT JOIN `' . $assocIdentity['to']['key'] . '` ON `' . $assocIdentity['from']['key'] . '`.`' . $assocIdentity['from']['field'] . '` = `' . $assocIdentity['to']['key'] . '`.`' . $assocIdentity['to']['field'] . '`';
             foreach ($assocIdentity['fields'] as $field) {
                 $fieldsCondenced .= ', ' . '`' . $assocIdentity['to']['key'] . '`.`' . $field . '` AS `' . $key . '_' . $field . '`';
             }
         }
     }
     if ($start) {
         $bindParamKey = ':crit' . $counter++;
         if (count($whereParams)) {
             $where .= ' AND ';
         }
         $where .= '`' . $table . '`.`date` > ' . $bindParamKey;
         $whereParams[$bindParamKey] = $start;
     }
     if ($end) {
         $bindParamKey = ':crit' . $counter++;
         if (count($whereParams)) {
             $where .= ' AND ';
         }
         $where .= '`' . $table . '`.`date` < ' . $bindParamKey;
         $whereParams[$bindParamKey] = $end;
     }
     if (!count($whereParams)) {
         $where = '';
     }
     if ($orderBy) {
         $orderQuery = ' ORDER BY `' . $table . '`.`' . $orderBy . '` ' . $orderByDir . ' ';
     } else {
         $orderQuery = '';
     }
     if ($groupBy) {
         $groupQuery = ' GROUP BY `' . $table . '`.`' . $groupBy . '` ';
     } else {
         $groupQuery = '';
     }
     $query = 'SELECT ' . $fieldsCondenced . ' FROM `' . $table . '` ' . $association . ' ' . $where . $groupQuery . $orderQuery . ' LIMIT :lim OFFSET :ofs';
     if ($isCount) {
         $query = $countSubWrapBegin . $query . $countSubWrapEnd;
     }
     DebugHandler::Log($query);
     $statement = $db->prepare($query);
     $statement->bindValue(':lim', (int) $limit, \PDO::PARAM_INT);
     $statement->bindValue(':ofs', (int) $offset, \PDO::PARAM_INT);
     DebugHandler::Log(var_export($whereParams, true));
     foreach ($whereParams as $paramName => $paramValue) {
         $statement->bindValue($paramName, $paramValue);
     }
     if ($statement->execute() === false) {
         /**
          * @todo make better error
          */
         throw new Exception('There was a problem with the search query! ' . var_export($statement->errorInfo(), true));
     }
     return $statement->fetchAll(\PDO::FETCH_ASSOC | \PDO::FETCH_GROUP);
 }