예제 #1
0
 public static function createTemplate($destination, $origin, array $variables = array())
 {
     self::init();
     $template_content = self::buildTemplate($origin);
     $template_content = self::evalContent($origin, $template_content, $variables);
     if (!$template_content) {
         Backend::addError('Could not generate template');
         return false;
     }
     $template_loc = ConfigValue::get('settings.TemplateLocation', 'templates');
     if (defined('SITE_FOLDER')) {
         $dest_file = SITE_FOLDER . '/' . $template_loc . '/' . $destination;
     } else {
         $dest_file = APP_FOLDER . '/' . $template_loc . '/' . $destination;
     }
     if (@file_put_contents($dest_file, $template_content)) {
         if (SITE_STATE != 'production') {
             chmod($dest_file, 0664);
         }
         return true;
     } else {
         $error = error_get_last();
         if (strpos($error['message'], 'Permission denied') !== false) {
             if (Controller::$debug) {
                 Backend::addError('Permission denied. Check writeability of templates folder ' . dirname($dest_file) . '.');
             } else {
                 Backend::addError('Permission denied. Check writeability of templates folder.');
             }
         }
     }
     return false;
 }
예제 #2
0
 private static function filter($word, $count = null)
 {
     $word = preg_replace('/[^A-Za-z0-9_\\-]/', '', $word);
     if (strlen($word) < ConfigValue::get('backend_search.MinimumWordLength', 4)) {
         return false;
     }
     return strtolower($word);
 }
예제 #3
0
    public function action_create()
    {
        if (is_post()) {
            $parameters = get_previous_parameters();
            $object = new CommentObj();
            $object = $object->fromRequest();
            $object['foreign_id'] = empty($object['foreign_id']) ? reset($parameters) : $object['foreign_id'];
            $object['foreign_table'] = empty($object['foreign_table']) ? table_name(get_previous_area()) : $object['foreign_table'];
            //If we don't have a logged in user, create a dummy account
            if (!BackendUser::check()) {
                $query = new SelectQuery('BackendUser');
                $query->filter('`email` = :email');
                if ($old_user = Controller::getVar('user')) {
                    $existing_user = $query->fetchAssoc(array(':email' => $old_user['email']));
                }
                switch (true) {
                    case $existing_user && $existing_user['confirmed'] && $existing_user['active']:
                        //Attribute quote to user? Seems risque, actually, if I know a user's email address, I can just attribute to him. Auth first
                        Backend::addError('Comment not added. Please login first');
                        return false;
                        break;
                    case $existing_user && !$existing_user['confirmed'] && $existing_user['active']:
                        //Unregistered user commented before
                        $object['user_id'] = $existing_user['id'];
                        break;
                    default:
                    case !$existing_user:
                        $user_data = array('name' => $old_user['name'], 'surname' => '', 'email' => $old_user['email'], 'website' => $old_user['website'], 'username' => $old_user['email'], 'password' => get_random(), 'confirmed' => 0, 'active' => 1);
                        $user = self::getObject('BackendUser');
                        if ($user->create($user_data)) {
                            $object['user_id'] = $user->array['id'];
                            $url = SITE_LINK . '/?q=backend_user/confirm/' . $user->array['salt'];
                            $app_name = ConfigValue::get('Title');
                            $message = <<<END
Hi {$user->array['name']}!

Thank you for your comment on {$app_name}. An account has automatically been created for you. To activate it, please click on the following link:

{$url}

Please note that you don't need to do this for your comments to show, but this account will be deleted if it isn't confirmed in a weeks time.

Regards
END;
                            send_email($user->array['email'], 'Thank you for your comment.', $message);
                        } else {
                            Backend::addError('Could not create user to add Comment');
                            return false;
                        }
                        break;
                }
            }
            $object = array_filter($object, create_function('$var', 'return !is_null($var);'));
            Controller::setVar('obj', $object);
        }
        return parent::action_create();
    }
 public function check()
 {
     $result = parent::check();
     if ($result === false && ($password = Controller::getVar('lock_password_' . $this->array['name']))) {
         if ($password == ConfigValue::get('LockPassword_' . $this->array['name'], false)) {
             return true;
         }
     }
     return $result;
 }
예제 #5
0
 public static function check($challenge, $response)
 {
     self::$error_msg = false;
     if (empty($challenge) || empty($response)) {
         self::$error_msg = 'Invalid challenge or response';
         return false;
     }
     $params = array('privatekey' => ConfigValue::get('recaptcha.PrivateKey'), 'remoteip' => $_SERVER['REMOTE_ADDR'], 'challenge' => $challenge, 'response' => $response);
     $result = curl_request('http://api-verify.recaptcha.net/verify', $params, array('method' => 'post'));
     if (!$result) {
         self::$error_msg = 'Could not contact reCAPTCHA server';
         return false;
     }
     $result = explode("\n", $result);
     if ($result[0] != 'true') {
         self::$error_msg = $result[1];
         return false;
     }
     return true;
 }
예제 #6
0
 public static function checkParameters($parameters)
 {
     if (Controller::$action == 'index') {
         Controller::setAction('list');
     }
     if (Controller::$action == 'list' && !isset(Controller::$parameters[0])) {
         $parameters[0] = 0;
     }
     if (Controller::$action == 'list' && !isset(Controller::$parameters[1])) {
         $parameters[1] = ConfigValue::get('table.ListLength', 9);
     }
     return parent::checkParameters($parameters);
 }
예제 #7
0
 function html_display($content)
 {
     if ($content instanceof DBObject) {
         Backend::add('Sub Title', $content->array['title']);
         if ($content->array['from_file']) {
             //Move this to the object ??
             $filename = 'content/static/' . $content->array['name'] . '.html';
             $template = 'content/' . $content->array['name'] . '.tpl.php';
             if (Render::checkTemplateFile($template)) {
                 $content->object->body = Render::file($template);
             } else {
                 if (file_exists(SITE_FOLDER . '/' . $filename)) {
                     $content->object->body = file_get_contents(APP_FOLDER . '/' . $filename);
                 } else {
                     if (file_exists(APP_FOLDER . '/' . $filename)) {
                         $content->object->body = file_get_contents(APP_FOLDER . '/' . $filename);
                     } else {
                         if (file_exists(BACKEND_FOLDER . '/' . $filename)) {
                             $content->object->body = file_get_contents(BACKEND_FOLDER . '/' . $filename);
                             //SITE FOLDER too?
                         }
                     }
                 }
             }
         }
         $meta_desc = Backend::get('meta_description');
         if (empty($meta_desc)) {
             Backend::add('meta_description', plain(self::createPreview($content->object->body, false)));
         }
         $http_equiv = Backend::get('meta_http_equiv', array());
         $http_equiv['Last-Modified'] = $content->object->modified;
         Backend::add('meta_http_equiv', $http_equiv);
         if (!headers_sent()) {
             $max_age = ConfigValue::get('content.MaxAge', 86400);
             header('Last-Modified: ' . $content->object->modified);
             header('Expires: ' . gmdate('r', strtotime('+1 day')));
             header('Cache-Control: max-age=' . $max_age . ', must-revalidate');
             header('Pragma: cache');
         }
     }
     if (Backend::getDB('default')) {
         //TODO Make some of the content values (such as added and lastmodified) available
         //So you can add Last Modified on #lastmodified# to the content.
         $content = parent::html_display($content);
     }
     return $content;
 }
예제 #8
0
/**
 * Send an HTTP request using CURL
 *
 * @param string the URL at which the request should be directed
 * @param array An associative array with the data to include. It will be converted to GET or POST as needed
 * @param array An associative array with which to alter the behaviour of curl_request
 */
function curl_request($url, array $parameters = array(), array $options = array())
{
    $cache_file = false;
    if (!empty($options['cache']) && $options['cache'] > 0) {
        $cache = $options['cache'];
        if (count($parameters)) {
            $cache_file = $url . '?' . http_build_query($parameters);
        } else {
            $cache_file = $url;
        }
        $cache_file = md5($cache_file);
        if (defined('SITE_FOLDER')) {
            $cache_file = SITE_FOLDER . '/cache/' . $cache_file;
        } else {
            $cache_file = APP_FOLDER . '/cache/' . $cache_file;
        }
        if (file_exists($cache_file) && filemtime($cache_file) >= time() - $cache) {
            return file_get_contents($cache_file);
        }
    } else {
        $cache = false;
    }
    $ch = curl_init($url);
    if (!empty($options['debug'])) {
        var_dump('cURL Request:', $url);
    }
    if (empty($options['user_agent'])) {
        curl_setopt($ch, CURLOPT_USERAGENT, 'Backend / PHP');
    } else {
        curl_setopt($ch, CURLOPT_USERAGENT, $options['user_agent']);
    }
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    if (!empty($options['bypass_ssl'])) {
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    }
    if (empty($options['dont_follow'])) {
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    } else {
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
    }
    if (array_key_exists('output', $options) && $options['output']) {
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
    } else {
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    }
    if (array_key_exists('header_function', $options) && is_callable($options['header_function'])) {
        curl_setopt($ch, CURLOPT_HEADERFUNCTION, $options['header_function']);
        curl_setopt($ch, CURLOPT_HEADER, false);
    } else {
        if (!empty($options['return_header']) || !empty($options['debug'])) {
            curl_setopt($ch, CURLOPT_HEADER, true);
        } else {
            curl_setopt($ch, CURLOPT_HEADER, false);
        }
    }
    if (!empty($options['referer'])) {
        curl_setopt($ch, CURLOPT_REFERER, $options['referer']);
    }
    if (!empty($options['headers']) && is_array($options['headers'])) {
        curl_setopt($ch, CURLOPT_HTTPHEADER, $options['headers']);
    }
    if (!empty($options['cookie_jar'])) {
        curl_setopt($ch, CURLOPT_COOKIEJAR, $options['cookie_jar']);
        curl_setopt($ch, CURLOPT_COOKIEFILE, $options['cookie_jar']);
    }
    //Use this carefully...
    if (!empty($options['interface'])) {
        curl_setopt($ch, CURLOPT_INTERFACE, $options['interface']);
    }
    if (!empty($options['username']) && !empty($options['password'])) {
        curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
        curl_setopt($ch, CURLOPT_USERPWD, $options['username'] . ':' . $options['password']);
    }
    if (!empty($options['proxy'])) {
        if (Controller::$debug) {
            var_dump('Using proxy: ' . $options['proxy']);
        }
        curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
        curl_setopt($ch, CURLOPT_PROXY, $options['proxy']);
    }
    $method = array_key_exists('method', $options) && in_array(strtolower($options['method']), array('get', 'post', 'put')) ? strtolower($options['method']) : 'get';
    switch ($method) {
        case 'put':
            curl_setopt($ch, CURLOPT_PUT, true);
            break;
        case 'post':
            curl_setopt($ch, CURLOPT_POST, true);
            if (count($parameters)) {
                curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($parameters));
            }
            break;
        case 'get':
        default:
            curl_setopt($ch, CURLOPT_HTTPGET, true);
            if (count($parameters)) {
                curl_setopt($ch, CURLOPT_URL, $url . '?' . http_build_query($parameters));
            }
            break;
    }
    if ($filename = ConfigValue::get('LogCurlRequests', false)) {
        $fp = fopen($filename, 'a');
        if ($method == 'post') {
            fwrite($fp, date('Y-m-d H:i:s') . "\t" . $method . "\t" . $url . "\t" . http_build_query($parameters) . PHP_EOL);
        } else {
            fwrite($fp, date('Y-m-d H:i:s') . "\t" . $method . "\t" . $url . PHP_EOL);
        }
        fclose($fp);
    }
    $toret = curl_exec($ch);
    if (!empty($options['debug'])) {
        @(list($headers, $toret) = preg_split("/\n\n|\n\r\n\r|\r\n\r\r/", $toret, 2));
        var_dump('cURL Response Headers:');
        echo "<pre>{$headers}</pre>";
        var_dump('cURL Response:', $toret);
    }
    if (!empty($options['callback']) && is_callable($options['callback'])) {
        $toret = call_user_func_array($options['callback'], array($ch, $toret, $options));
        if (!empty($options['debug'])) {
            var_dump('cURL Response After Callback:', $toret);
        }
    } else {
        if ($curl_error = curl_errno($ch)) {
            if (!empty($options['debug'])) {
                var_dump('cURL Error:', $curl_error);
            }
            $toret = false;
        } else {
            $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            if (!empty($options['debug'])) {
                var_dump('cURL HTTP Code:', $http_code);
            }
            if (!in_array($http_code, array(200))) {
                $toret = false;
            }
        }
    }
    curl_close($ch);
    if (!empty($options['debug'])) {
        var_dump('cURL Precache:', $toret, $cache, $cache_file);
    }
    if ($toret && $cache) {
        file_put_contents($cache_file, $toret);
    }
    //Don't know if this is a good idea, but if we couldn't fetch the file, and an older one exists, return it
    if (!$toret && $cache && file_exists($cache_file)) {
        $toret = file_get_contents($cache_file);
    }
    return $toret;
}
예제 #9
0
    public static function userStats()
    {
        $msg = array();
        $query = new SelectQuery('BackendUser');
        $query->field('COUNT(*) AS `Total`, SUM(IF(TO_DAYS(NOW()) - TO_DAYS(`added`) < 7, 1, 0)) AS `New`')->filter('`active` = 1')->filter('`confirmed` = 1');
        if ($stats = $query->fetchAssoc()) {
            $msg[] = 'There are a total of ' . $stats['Total'] . ' **active** users,
of which ' . $stats['New'] . ' signed up in the last 7 days';
        }
        $query = new SelectQuery('BackendUser');
        $query->field('COUNT(*) AS `Total`, SUM(IF(TO_DAYS(NOW()) - TO_DAYS(`added`) < 7, 1, 0)) AS `New`')->filter('`active` = 1')->filter('`confirmed` = 1');
        if ($stats = $query->fetchAssoc()) {
            $msg[] = 'There are a total of ' . $stats['Total'] . ' **unconfirmed** users,
of which ' . $stats['New'] . ' signed up in the last 7 days';
        }
        $msg = implode(PHP_EOL . PHP_EOL, $msg);
        send_email(ConfigValue::get('author.Email', ConfigValue::get('application.Email', 'info@' . SITE_DOMAIN)), 'User stats for ' . Backend::get('Title'), $msg);
        return true;
    }
예제 #10
0
">
		<?php 
}
?>
		<?php 
if ($author = ConfigValue::get('Author')) {
    ?>
			<meta name="author" content="<?php 
    echo $author;
    ?>
">
		<?php 
}
?>
		<?php 
if (!empty($meta_description) || ($meta_description = ConfigValue::get('Description'))) {
    ?>
			<meta name="description" content="<?php 
    echo $meta_description;
    ?>
">
		<?php 
}
?>
		<meta name="generator" content="backend-php.net">
		<?php 
if (!empty($keywords)) {
    $keywords = is_array($keywords) ? implode(', ', $keywords) : $keywords;
    ?>
			<meta name="keywords" content="<?php 
    echo $keywords;
예제 #11
0
    echo htmlspecialchars($sub_title);
    ?>
</subtitle><?php 
}
?>
	<link href="<?php 
echo $link;
?>
" rel="self" />
	<id><?php 
echo $link;
?>
</id>
	<updated>#AtomLastDate#</updated>
	<?php 
$author = ConfigValue::get('Author');
?>
	<?php 
if (is_string($author)) {
    ?>
		<author><name><?php 
    echo $author;
    ?>
</name></author>
	<?php 
} elseif (is_array($author)) {
    ?>
		<author>
			<?php 
    if (array_key_exists('name', $author)) {
        ?>
예제 #12
0
 /**
  * Use this function to set default parameters for specific actions
  *
  * It's also a good way to transform request variables to proper parameters
  */
 public static function checkParameters($parameters)
 {
     //If there's no action, only a ID, use the request verb to determine the action
     if (is_numeric(Controller::$action)) {
         $parameters[0] = Controller::$action;
         switch (strtoupper($_SERVER['REQUEST_METHOD'])) {
             case 'DELETE':
                 Controller::setAction('delete');
                 break;
             case 'PUT':
                 Controller::setAction('create');
                 break;
             case 'POST':
                 Controller::setAction('update');
                 break;
             case 'GET':
             default:
                 Controller::setAction('display');
                 break;
         }
     }
     //List instead of index
     if (Controller::$action == 'index') {
         Controller::setAction('list');
     }
     switch (Controller::$action) {
         case 'list':
             //Defaults for List
             if (!isset(Controller::$parameters[0])) {
                 $parameters[0] = 0;
             }
             if (!isset(Controller::$parameters[1])) {
                 $parameters[1] = ConfigValue::get('table.ListLength', 5);
             }
             break;
         case 'search':
             //Defaults for Search
             //Get the search term from the request variable. It's always the first parameter
             if ($term = Controller::getVar('term')) {
                 array_unshift($parameters, $term);
             } else {
                 if (!count($parameters)) {
                     $parameters[0] = '';
                 }
             }
             if (!isset(Controller::$parameters[1])) {
                 $start = Controller::getVar('start', FILTER_VALIDATE_INT);
                 $parameters[1] = is_null($start) ? 0 : $start;
             }
             if (!isset(Controller::$parameters[2])) {
                 $count = Controller::getVar('count', FILTER_VALIDATE_INT);
                 $parameters[2] = is_null($count) ? ConfigValue::get('table.ListLength', 5) : $count;
             }
             break;
     }
     //Get the delete_id from the request variable
     if (Controller::$action == 'delete' && empty($parameters[0]) && ($delete_id = Controller::getVar('delete_id', FILTER_VALIDATE_INT))) {
         $parameters[0] = $delete_id;
     }
     return $parameters;
 }
예제 #13
0
 private function generateSitemap($component)
 {
     if (!method_exists($component, 'getSitemap')) {
         return false;
     }
     if (!Component::isActive($component)) {
         Backend::addError('Could not generate sitemap: Component inactive. (' . $component . ')');
         return false;
     }
     $controller = new $component();
     $object = $component::retrieve();
     if (!$controller instanceof TableCtl) {
         Backend::addError('Could not generate sitemap: Invalid Area. (' . $component . ')');
         return false;
     }
     $filename = WEB_FOLDER . '/sitemap_' . $component . '.xml';
     if (file_exists($filename) && !is_writable($filename)) {
         Backend::addError('Could not generate sitemap: Cannot open sitemap file. (' . $filename . ')');
         return false;
     }
     $fp = fopen($filename, 'w');
     if (!$fp) {
         Backend::addError('Could not generate sitemap: Could not open sitemap file. (' . $component . ')');
         return false;
     }
     $sitemap = $controller->getSitemap();
     if (count($sitemap) == 2 && array_key_exists('list', $sitemap) && array_key_exists('options', $sitemap)) {
         $list = $sitemap['list'];
         $options = $sitemap['options'];
     } else {
         $list = $sitemap;
         $options = array();
     }
     if (!$list) {
         Backend::addError('Could not generate sitemap: Could not generate list. (' . $component . ')');
         return false;
     }
     if (Controller::$debug) {
         Backend::addNotice('Generating sitemap for ' . $component . ' at ' . WEB_FOLDER . '/sitemap_' . $component . '.xml found at ' . SITE_LINK . basename($filename));
     }
     $last_date = 0;
     $links = array();
     //Compile Links
     foreach ($list as $row) {
         $last_date = strtotime($row['modified']) > $last_date ? strtotime($row['modified']) : $last_date;
         if (empty($options['id_field'])) {
             $id = !empty($row['name']) ? $row['name'] : $row[$object->getMeta('id_field')];
         } else {
             $id = $row[$options['id_field']];
         }
         if (empty($id)) {
             var_dump($id, $row, $object->getMeta('id_field'), $object->getMeta('id'));
             die;
         }
         if (ConfigValue::get('CleanURLs', false)) {
             $url = SITE_LINK . '/' . class_for_url($component) . '/' . $id;
         } else {
             $url = SITE_LINK . '/?q=' . class_for_url($component) . '/' . $id;
         }
         $row['url'] = $url;
         $row = array_merge($row, $options);
         $links[] = $row;
     }
     //Add link to area
     //TODO Make this configurable
     if (ConfigValue::get('CleanURLs', false)) {
         $url = SITE_LINK . '/' . class_for_url($component);
     } else {
         $url = SITE_LINK . '/?q=' . class_for_url($component);
     }
     $link = array('url' => $url, 'modified' => date('Y-m-d H:i:s', $last_date));
     $link['priority'] = array_key_exists('area_priority', $options) ? $options['area_priority'] : 0.8;
     $link['frequency'] = array_key_exists('frequency', $options) ? $options['frequency'] : 'daily';
     $links[] = $link;
     fwrite($fp, Render::file('backend_sitemap/sitemap.tpl.php', array('links' => $links)));
     return $filename;
 }
예제 #14
0
echo date('r');
?>
</pubDate>

		<lastBuildDate><?php 
echo date('r');
?>
</lastBuildDate>
		<docs>http://blogs.law.harvard.edu/tech/rss</docs>
		<generator>Backend-PHP</generator>
		<managingEditor><?php 
echo ConfigValue::get('author.Email', ConfigValue::get('application.Email', 'info@' . SITE_DOMAIN));
?>
</managingEditor>
		<webMaster><?php 
echo ConfigValue::get('author.Email', ConfigValue::get('application.Email', 'info@' . SITE_DOMAIN));
?>
</webMaster>

		<?php 
if ($list) {
    foreach ($list as $item) {
        ?>
			<item>
				<title><?php 
        echo htmlspecialchars($item['title']);
        ?>
</title>
				<link><?php 
        echo $item['link'];
        ?>
<form accept-charset="utf-8" method="post" action="?q=backend_user/super_signup/">
	<table> 
		<tbody> 
			<tr> 
				<td><label class="large">Username:</label></td><td><input type="text" class="text" name="username" value="admin"/></td> 
			</tr> 
			<tr> 
				<td><label class="large">Password:</label></td><td><input type="password" class="text" name="password" value=""/></td> 
			</tr> 
			<tr> 
				<td><label class="large">Confirm Password:</label></td><td><input type="password" class="text" name="confirm_password" value=""/></td> 
			</tr> 
			<tr> 
				<td><label class="large">Email:</label></td><td><input type="text" class="text" name="email" value="<?php 
echo ConfigValue::get('author.Email');
?>
"/></td> 
			</tr> 
			<tr> 
				<td colspan="2" style="text-align: center"><input type="submit" value="Sign up!" />
			</td> 
		</tbody> 
	</table> 
</form>

예제 #16
0
 /**
  * Render the data into the correct format / as information
  *
  * This function takes data, and translates it into information.
  */
 function display($data, $controller)
 {
     $data = Hook::run('display', 'pre', array($data, $controller), array('toret' => $data));
     if (method_exists($this, 'hook_display')) {
         $data = $this->hook_display($data, $controller);
     }
     if ($controller instanceof AreaCtl && $controller->checkPermissions()) {
         $display_method = $this->mode . '_' . Controller::$action;
         $view_method = 'output_' . Controller::$action;
         $mode_method = $this->mode;
         //Controller->view
         if (method_exists($controller, $mode_method)) {
             if (Controller::$debug) {
                 Backend::addNotice('Running ' . get_class($controller) . '::' . $mode_method);
             }
             $data = $controller->{$mode_method}($data);
         }
         //Application->view
         $app_class = ConfigValue::get('settings.Class', 'Application');
         if (is_callable(array($app_class, $mode_method))) {
             if (Controller::$debug) {
                 Backend::addNotice('Running ' . $app_class . '::' . $mode_method);
             }
             $data = call_user_func(array($app_class, $mode_method), $data);
         }
         if (Controller::$debug) {
             Backend::addNotice('Checking ' . get_class($controller) . '::' . $display_method . ' and then ' . get_class($this) . '::' . $view_method);
         }
         //Controller->display_method and View->view_method
         if (method_exists($controller, $display_method)) {
             if (Controller::$debug) {
                 Backend::addNotice('Running ' . get_class($controller) . '::' . $display_method);
             }
             $data = $controller->{$display_method}($data);
         } else {
             if (method_exists($this, $view_method)) {
                 if (Controller::$debug) {
                     Backend::addNotice('Running ' . get_class($this) . '::' . $view_method);
                 }
                 $data = $this->{$view_method}($data);
             }
         }
     }
     $data = Hook::run('display', 'post', array($data, $controller), array('toret' => $data));
     if (method_exists($this, 'hook_post_display')) {
         $data = $this->hook_post_display($data, $controller);
     }
     $this->output($data);
 }
예제 #17
0
 function validate($data, $action, $options = array())
 {
     $data = parent::validate($data, $action, $options);
     if (!$data) {
         return $data;
     }
     switch ($action) {
         case 'create':
             $data['active'] = array_key_exists('active', $data) ? $data['active'] : true;
             //We need either an email, mobile number or username to register a user
             //Lower ASCII only
             if (!empty($data['username'])) {
                 $data['username'] = filter_var(trim($data['username']), FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
                 //TODO Make the banned usernames configurable
                 $banned_usernames = array('root', 'admin', 'superadmin', 'superuser', 'webadmin', 'postmaster', 'webdeveloper', 'webmaster', 'administrator', 'sysadmin');
                 if (in_array($data['username'], $banned_usernames) && BackendUser::hasSuperUser()) {
                     Backend::addError('Please choose a valid username');
                     return false;
                 }
             }
             if (empty($data['username']) && empty($data['email']) && empty($data['mobile'])) {
                 Backend::addError('Please provide a username');
             }
             //If the username is an email address, make it the email address
             if (!empty($data['username']) && filter_var($data['username'], FILTER_VALIDATE_EMAIL)) {
                 if (!empty($data['email'])) {
                     list($data['username'], $data['email']) = array($data['email'], $data['username']);
                 } else {
                     $data['email'] = $data['username'];
                     unset($data['username']);
                 }
             }
             $data['salt'] = get_random('numeric');
             $data['password'] = md5($data['salt'] . $data['password'] . Controller::$salt);
             if (ConfigValue::get('application.confirmUser')) {
                 $data['confirmed'] = false;
             } else {
                 $data['confirmed'] = array_key_exists('confirmed', $data) ? $data['confirmed'] : true;
             }
             break;
         case 'update':
             if (!empty($data['password'])) {
                 $data['password'] = md5($this->array['salt'] . $data['password'] . Controller::$salt);
             }
             break;
     }
     return $data;
 }
예제 #18
0
 private static function add($filename)
 {
     $name = preg_replace('/\\.obj\\.php$/', '', basename($filename));
     $active = in_array($name, array_flatten(self::getCoreComponents(true), null, 'name')) || $name == ConfigValue::get('settings.Class');
     $data = array('name' => $name, 'filename' => $filename, 'options' => '', 'active' => $active);
     $component = new ComponentObj();
     return $component->create($data, array('load' => false));
 }
예제 #19
0
 private static function addSomething($what, $string, $options = array())
 {
     if (is_null($string)) {
         return false;
     }
     if (is_array($string) && empty($options['as_is'])) {
         $result = true;
         foreach ($string as $one_string) {
             $result = self::addSomething($what, $one_string, $options) && $result;
         }
         return $result;
     } else {
         array_push(self::${$what}, $string);
         //Log to file if necessary
         $log_to_file = array_key_exists('log_to_file', $options) ? $options['log_to_file'] : ConfigValue::get('LogToFile', false);
         if ($log_to_file) {
             if (is_string($log_to_file)) {
                 @(list($file, $log_what) = explode('|', $log_to_file));
             }
             $file = empty($file) ? 'logfile_' . date('Ymd') . 'txt' : $file;
             $log_what = empty($log_what) ? array('success', 'notice', 'error') : explode(',', $log_what);
             if (is_array($log_what) && in_array($what, $log_what) || $log_what == '*') {
                 if (is_writable(APP_FOLDER . '/logs/' . $file)) {
                     if (!file_exists(APP_FOLDER . '/logs/')) {
                         mkdir(APP_FOLDER . '/logs/', 0755);
                     }
                     $fp = fopen(APP_FOLDER . '/logs/' . $file, 'a');
                     if ($fp) {
                         $query = Controller::$area . '/' . Controller::$action . '/' . implode('/', Controller::$parameters);
                         fwrite($fp, time() . "\t" . $query . "\t" . $what . "\t" . $string . PHP_EOL);
                     }
                 } else {
                     array_push(self::$error, 'Log location is unwriteable');
                 }
             }
         }
         return true;
     }
     return false;
 }
예제 #20
0
 public static function adminLinks()
 {
     $result = array();
     if (!($user = BackendUser::check())) {
         return false;
     }
     if (!ConfigValue::get('AdminInstalled', false) && in_array('superadmin', $user->roles)) {
         $result[] = array('text' => 'Install Application', 'href' => '?q=admin/install');
     }
     if (!BACKEND_WITH_DATABASE) {
         $result[] = array('text' => 'Install Database', 'href' => '?q=admin/install_db');
     }
     if (SITE_STATE != 'production') {
         $result[] = array('text' => 'Scaffold', 'href' => '?q=admin/scaffold');
     }
     return count($result) ? $result : false;
 }
예제 #21
0
 /**
  * Check permissions for this area
  *
  * Override this function if you want to customize the permissions for an area. BUT preferably use the DB...
  */
 public function checkPermissions(array $options = array())
 {
     $action = !empty($options['action']) ? $options['action'] : (!empty(Controller::$action) ? Controller::check_reverse_map('action', Controller::$action) : '*');
     $subject = !empty($options['subject']) ? $options['subject'] : (!empty(Controller::$area) ? Controller::check_reverse_map('area', Controller::$area) : '*');
     if (count(Controller::$parameters) === 1) {
         $subject_id = !empty($options['subject_id']) ? $options['subject_id'] : (!empty(Controller::$parameters[0]) ? Controller::check_reverse_map('id', Controller::$parameters[0]) : 0);
     } else {
         $subject_id = 0;
     }
     if (ConfigValue::get('AdminInstalled', false)) {
         return Permission::check($action, $subject, $subject_id);
     } else {
         if (!($subject == 'admin' && in_array($action, array('pre_install', 'check_install', 'install')))) {
             return false;
         }
     }
     return true;
 }
예제 #22
0
 public static function rewriteLinks($to_print)
 {
     if (ConfigValue::get('CleanURLs', false)) {
         preg_match_all('/(<a\\s+.*?href=[\'\\"]|<form\\s+.*?action=[\'"]|<link\\s+.*?href=[\'"])(|.*?[\\?&]q=.*?&?.*?)[\'"]/', $to_print, $matches);
         if (count($matches) == 3) {
             $matched = $matches[0];
             $links = $matches[1];
             $urls = $matches[2];
             $replacements = array();
             foreach ($urls as $key => $url) {
                 if (empty($url)) {
                     $url = get_current_url();
                 }
                 //Build query array
                 //workaround for parse_url acting funky with a url = ?q=something/another/
                 if (substr($url, 0, 3) == '?q=') {
                     $query = array('query' => substr($url, 1));
                 } else {
                     $query = parse_url($url);
                 }
                 if (empty($query['path'])) {
                     $query['path'] = SITE_LINK;
                 }
                 if (substr($query['path'], -1) != '/') {
                     $query['path'] .= '/';
                 }
                 if (array_key_exists('scheme', $query)) {
                     $query['scheme'] = $query['scheme'] . '://';
                 }
                 //Get the old vars
                 if (array_key_exists('query', $query)) {
                     parse_str($query['query'], $vars);
                 } else {
                     $vars = array();
                 }
                 //append q to the URL
                 if (array_key_exists('q', $vars)) {
                     $query['path'] .= $vars['q'];
                     unset($vars['q']);
                     if (substr($query['path'], -1) == '/') {
                         $query['path'] = substr($query['path'], 0, strlen($query['path']) - 1);
                     }
                 }
                 //Create query string
                 if (count($vars)) {
                     $query['query'] = '?' . http_build_query($vars);
                 } else {
                     $query['query'] = '';
                 }
                 $to_rep = $links[$key] . $query['path'] . $query['query'] . '"';
                 $replacements[] = $to_rep;
             }
             $to_print = str_replace($matched, $replacements, $to_print);
         }
     }
     return $to_print;
 }
예제 #23
0
 public function html_permissions($result)
 {
     if (is_post()) {
         if ($result === false) {
             Backend::addError('Could not update Permissions');
         } else {
             Backend::addSuccess($result . ' Permissions Updated');
         }
         Controller::redirect('previous');
     }
     //GET
     if (!empty(Controller::$parameters[0])) {
         Backend::add('Sub Title', class_name(Controller::$parameters[0]) . ' Permissions');
         Links::add('All Permissions', '?q=gate_manager/permissions', 'secondary');
     } else {
         Backend::add('Sub Title', ConfigValue::get('Title') . ' Permissions');
     }
     Backend::addContent(Render::renderFile('gate_manager.permissions.tpl.php', (array) $result));
 }
예제 #24
0
 /**
  * Redirect to a specified location.
  *
  * If the location is omitted, go to the current URL. If $location == 'previous', go the previous URL for the current mode.
  */
 public static function redirect($location = false)
 {
     if (self::$mode == self::MODE_REQUEST) {
         switch ($location) {
             case 'previous':
                 if (!empty($_SESSION['previous_url'])) {
                     if (is_array($_SESSION['previous_url'])) {
                         $location = !empty($_SESSION['previous_url'][self::$view->mode]) ? $_SESSION['previous_url'][self::$view->mode] : reset($_SESSION['previous_url']);
                     } else {
                         $location = $_SESSION['previous_url'];
                     }
                 } else {
                     $location = false;
                 }
                 break;
         }
         if (!$location) {
             $location = $_SERVER['REQUEST_URI'];
         }
         //The following is only for on site redirects
         if (substr($location, 0, 7) != 'http://' || substr($location, 0, strlen(SITE_LINK)) == SITE_LINK) {
             //This should fix most redirects, but it may happen that location == '?debug=true&q=something/or/another' or something similiar
             if (ConfigValue::get('CleanURLs', false) && substr($location, 0, 3) == '?q=') {
                 $location = SITE_LINK . substr($location, 3);
             }
             //Add some meta variables
             if (!empty($_SERVER['QUERY_STRING'])) {
                 parse_str($_SERVER['QUERY_STRING'], $vars);
                 $new_vars = array();
                 if (array_key_exists('debug', $vars)) {
                     $new_vars['debug'] = $vars['debug'];
                 }
                 if (array_key_exists('nocache', $vars)) {
                     $new_vars['nocache'] = $vars['nocache'];
                 }
                 if (array_key_exists('recache', $vars)) {
                     $new_vars['recache'] = $vars['recache'];
                 }
                 if (array_key_exists('mode', $vars)) {
                     $new_vars['mode'] = $vars['mode'];
                 }
                 $url = parse_url($location);
                 if (!empty($url['query'])) {
                     parse_str($url['query'], $old_vars);
                 } else {
                     $old_vars = array();
                 }
                 //Allow the redirect to overwrite these vars
                 $new_vars = array_merge($new_vars, $old_vars);
                 $old_url = parse_url(get_current_url());
                 $url['query'] = http_build_query($new_vars);
                 $url = array_merge($old_url, $url);
                 $location = build_url($url);
             }
         }
         try {
             if (self::$debug) {
                 Backend::addSuccess('The script should now redirect to <a href="' . $location . '">here</a>');
             } else {
                 //Redirect
                 header('X-Redirector: Controller-' . __LINE__);
                 header('Location: ' . $location);
                 die('redirecting to <a href="' . $location . '">');
             }
         } catch (Exception $e) {
             Backend::addError('Could not redirect');
         }
     }
     return true;
 }