/**
     * 
     *
     * @param Event $event An Event instance
     */
    public function filter(Event $event, Response $response)
    {
        if (!$configuration = $event->get('request')->attributes->get('_cache')) {
            return $response;
        }

        if (!$response->isSuccessful()) {
            return $response;
        }

        if (null !== $configuration->getSMaxAge()) {
            $response->setSharedMaxAge($configuration->getSMaxAge());
        }

        if (null !== $configuration->getMaxAge()) {
            $response->setMaxAge($configuration->getMaxAge());
        }

        if (null !== $configuration->getExpires()) {
            $date = \DateTime::create(\DateTime::createFromFormat('U', $configuration->getExpires(), new \DateTimeZone('UTC')));

            $response->setLastModified($date);
        }

        return $response;
    }
Example #2
0
 /**
  * Handles get requests for the dashboard
  * @todo update check should probably be cron'd and cached, not re-checked every load
  */
 public function get_dashboard()
 {
     // Not sure how best to determine this yet, maybe set an option on install, maybe do this:
     $firstpostdate = DB::get_value('SELECT min(pubdate) FROM {posts} WHERE status = ?', array(Post::status('published')));
     if ($firstpostdate) {
         $this->theme->active_time = DateTime::create($firstpostdate);
     }
     // check to see if we have updates to display
     $this->theme->updates = Options::get('updates_available', array());
     // collect all the stats we display on the dashboard
     $user = User::identify();
     $this->theme->stats = array('author_count' => Users::get(array('count' => 1)), 'post_count' => Posts::get(array('count' => 1, 'content_type' => Post::type('any'), 'status' => Post::status('published'))), 'comment_count' => Comments::count_total('approved', false), 'tag_count' => Tags::vocabulary()->count_total(), 'user_draft_count' => Posts::get(array('count' => 1, 'content_type' => Post::type('any'), 'status' => Post::status('draft'), 'user_id' => $user->id)), 'unapproved_comment_count' => User::identify()->can('manage_all_comments') ? Comments::count_total('unapproved', false) : Comments::count_by_author(User::identify()->id, Comment::status('unapproved')), 'spam_comment_count' => $user->can('manage_all_comments') ? Comments::count_total('spam', false) : Comments::count_by_author($user->id, Comment::status('spam')), 'user_scheduled_count' => Posts::get(array('count' => 1, 'content_type' => Post::type('any'), 'status' => Post::status('scheduled'), 'user_id' => $user->id)));
     // check for first run
     $u = User::identify();
     $uinfo = $u->info;
     if (!isset($uinfo->experience_level)) {
         $this->theme->first_run = true;
         $u->info->experience_level = 'user';
         $u->info->commit();
     } else {
         $this->theme->first_run = false;
     }
     $this->get_additem_form();
     Stack::add('admin_header_javascript', 'dashboard-js');
     $this->display('dashboard');
 }
Example #3
0
 public function test_delete_on_fail()
 {
     $job = CronTab::add_single_cron('test_delete_fail', 'this_cron_hook_doesnt_exist', DateTime::create(), 'Test Cron');
     for ($z = 0; $z < 10; $z++) {
         $job = CronTab::get_cronjob('test_delete_fail');
         Options::set('next_cron', 0);
         Options::delete('cron_running');
         $job->execute();
     }
     $this->assert_false($job->active, 'The cron is still active after failing more than the allowed number of times.');
     CronTab::delete_cronjob('test_delete_fail');
 }
Example #4
0
 public function __construct()
 {
     parent::__construct();
     // Let's register the options page form so we can use it with ajax
     $self = $this;
     FormUI::register('admin_options', function ($form, $name, $extra_data) use($self) {
         $option_items = array();
         $timezones = \DateTimeZone::listIdentifiers();
         $timezones = array_merge(array('' => ''), array_combine(array_values($timezones), array_values($timezones)));
         $option_items[_t('Name & Tagline')] = array('title' => array('label' => _t('Site Name'), 'type' => 'text', 'helptext' => ''), 'tagline' => array('label' => _t('Site Tagline'), 'type' => 'text', 'helptext' => ''), 'about' => array('label' => _t('About'), 'type' => 'textarea', 'helptext' => ''));
         $option_items[_t('Publishing')] = array('pagination' => array('label' => _t('Items per Page'), 'type' => 'text', 'helptext' => ''), 'atom_entries' => array('label' => _t('Entries to show in Atom feed'), 'type' => 'text', 'helptext' => ''), 'comments_require_id' => array('label' => _t('Require Comment Author Email'), 'type' => 'checkbox', 'helptext' => ''), 'spam_percentage' => array('label' => _t('Comment SPAM Threshold'), 'type' => 'text', 'helptext' => _t('The likelihood a comment is considered SPAM, in percent.')));
         $option_items[_t('Time & Date')] = array('timezone' => array('label' => _t('Time Zone'), 'type' => 'select', 'selectarray' => $timezones, 'helptext' => _t('Current Date Time: %s', array(DateTime::create()->format()))), 'dateformat' => array('label' => _t('Date Format'), 'type' => 'text', 'helptext' => _t('Current Date: %s', array(DateTime::create()->date))), 'timeformat' => array('label' => _t('Time Format'), 'type' => 'text', 'helptext' => _t('Current Time: %s', array(DateTime::create()->time))));
         $option_items[_t('Language')] = array('locale' => array('label' => _t('Locale'), 'type' => 'select', 'selectarray' => array_merge(array('' => 'default'), array_combine(Locale::list_all(), Locale::list_all())), 'helptext' => Config::exists('locale') ? _t('International language code : This value is set in your config.php file, and cannot be changed here.') : _t('International language code'), 'disabled' => Config::exists('locale'), 'value' => Config::get('locale', Options::get('locale', 'en-us'))), 'system_locale' => array('label' => _t('System Locale'), 'type' => 'text', 'helptext' => _t('The appropriate locale code for your server')));
         $option_items[_t('Troubleshooting')] = array('log_min_severity' => array('label' => _t('Minimum Severity'), 'type' => 'select', 'selectarray' => LogEntry::list_severities(), 'helptext' => _t('Only log entries with a this or higher severity.')), 'log_backtraces' => array('label' => _t('Log Backtraces'), 'type' => 'checkbox', 'helptext' => _t('Logs error backtraces to the log table\'s data column. Can drastically increase log size!')));
         $option_items = Plugins::filter('admin_option_items', $option_items);
         $tab_index = 3;
         foreach ($option_items as $name => $option_fields) {
             /** @var FormControlFieldset $fieldset  */
             $fieldset = $form->append(FormControlWrapper::create(Utils::slugify(_u($name)))->set_properties(array('class' => 'container main settings')));
             $fieldset->append(FormControlStatic::create($name)->set_static('<h2 class="lead">' . htmlentities($name, ENT_COMPAT, 'UTF-8') . '</h2>'));
             $fieldset->set_wrap_each('<div>%s</div>');
             foreach ($option_fields as $option_name => $option) {
                 /** @var FormControlLabel $label */
                 $label = $fieldset->append(FormControlLabel::create('label_for_' . $option_name, null)->set_label($option['label']));
                 /** @var FormControl $field */
                 $field = $label->append($option['type'], $option_name, $option_name);
                 $label->set_for($field);
                 if (isset($option['value'])) {
                     $field->set_value($option['value']);
                 }
                 if (isset($option['disabled']) && $option['disabled'] == true) {
                     $field->set_properties(array('disabled' => 'disabled'));
                 }
                 if ($option['type'] == 'select' && isset($option['selectarray'])) {
                     $field->set_options($option['selectarray']);
                 }
                 $field->tabindex = $tab_index;
                 $tab_index++;
                 if (isset($option['helptext'])) {
                     $field->set_helptext($option['helptext']);
                 }
             }
         }
         $buttons = $form->append(new FormControlWrapper('buttons', null, array('class' => 'container')));
         $buttons->append(FormControlSubmit::create('apply', null, array('tabindex' => $tab_index))->set_caption(_t('Apply')));
         $form->on_success(array($self, 'form_options_success'));
         $form = Plugins::filter('admin_options_form', $form);
     });
 }
Example #5
0
 public function loginform_do_login($form)
 {
     $name = $form->habari_username->value;
     $pass = $form->habari_password->value;
     if (null != $name || null != $pass) {
         $user = User::authenticate($name, $pass);
         if ($user instanceof User && $user != false) {
             $userinfo = $user->info;
             // if there's an unused password reset token, unset it to make sure there's no possibility of a compromise that way
             if (isset($userinfo->password_reset)) {
                 unset($userinfo->password_reset);
             }
             /* Successfully authenticated. */
             // Timestamp last login date and time.
             $user->info->authenticate_time = DateTime::create()->format('Y-m-d H:i:s');
             $user->update();
             // Remove left over expired session error message.
             if (Session::has_errors('expired_session')) {
                 Session::remove_error('expired_session');
             }
             $login_session = Session::get_set('login');
             if (!empty($login_session)) {
                 /* Now that we know we're dealing with the same user, transfer the form data so he does not lose his request */
                 if (!empty($login_session['post_data'])) {
                     Session::add_to_set('last_form_data', $last_form_data['post'], 'post');
                 }
                 if (!empty($login_session['get_data'])) {
                     Session::add_to_set('last_form_data', $last_form_data['get'], 'get');
                 }
                 // don't bother parsing out the URL, we store the URI that was requested, so just append that to the hostname and we're done
                 $login_dest = Site::get_url('host') . $login_session['original'];
             } else {
                 $login_session = null;
                 $login_dest = Site::get_url('admin');
             }
             // filter the destination
             $login_dest = Plugins::filter('login_redirect_dest', $login_dest, $user, $login_session);
             // finally, redirect to the destination
             Utils::redirect($login_dest);
             return true;
         }
         /* Authentication failed. */
         // Remove submitted password, see, we're secure!
         $form->habari_password->value = '';
         $this->handler_vars['error'] = _t('Bad credentials');
     }
 }
Example #6
0
 /**
  * Handles asyncronous cron calls.
  *
  * @todo next_cron should be the actual next run time and update it when new
  * crons are added instead of just maxing out at one day..
  */
 function act_poll_cron()
 {
     Utils::check_request_method(array('GET', 'HEAD', 'POST'));
     $time = doubleval($this->handler_vars['time']);
     if ($time != Options::get('cron_running')) {
         return;
     }
     // allow script to run for 10 minutes. This only works on host with safe mode DISABLED
     if (!ini_get('safe_mode')) {
         set_time_limit(600);
     }
     $time = DateTime::create();
     $crons = DB::get_results('SELECT * FROM {crontab} WHERE start_time <= ? AND next_run <= ? AND active != ?', array($time->sql, $time->sql, 0), 'CronJob');
     if ($crons) {
         foreach ($crons as $cron) {
             $cron->execute();
         }
     }
     // set the next run time to the lowest next_run OR a max of one day.
     $next_cron = DB::get_value('SELECT next_run FROM {crontab} WHERE active != ? ORDER BY next_run ASC LIMIT 1', array(0));
     Options::set('next_cron', min(intval($next_cron), $time->modify('+1 day')->int));
     Options::set('cron_running', false);
 }
Example #7
0
    /**
     * Get the fields of the post that differ from what is stored by date
     * @param DateTime|string|int $date The date to fetch the revision of
     * @return array An array of field data for the post with the values of those fields at the specified date
     */
    public function get_revision_data($date)
    {
        $sql = <<<GET_REVISION_DATA
SELECT
id, post_id, change_field, old_value, user_id, min(change_date) as change_date
FROM {revisions}
WHERE
post_id = :post_id
AND change_date > :rev_date
GROUP BY change_field
ORDER BY change_date;
GET_REVISION_DATA;
        return DB::get_results($sql, array('post_id' => $this->id, 'rev_date' => DateTime::create($date)->sql));
    }
Example #8
0
 private function fetch_logs()
 {
     // load all the values for our filter drop-downs
     $dates = $this->fetch_log_dates();
     $users = $this->fetch_log_users();
     $ips = $this->fetch_log_ips();
     extract($this->fetch_log_modules_types());
     // $modules and $types
     $severities = LogEntry::list_severities();
     // parse out the arguments we'll fetch logs for
     // the initial arguments
     $arguments = array('limit' => Controller::get_var('limit', 20), 'offset' => Controller::get_var('offset', 0));
     // filter for the search field
     $search = Controller::get_var('search', '');
     if ($search != '') {
         $arguments['criteria'] = $search;
     }
     // filter by date
     $date = Controller::get_var('date', 'any');
     if ($date != 'any') {
         $d = DateTime::create($date);
         // ! means fill any non-specified pieces with default Unix Epoch ones
         $arguments['year'] = $d->format('Y');
         $arguments['month'] = $d->format('m');
     }
     // filter by user
     $user = Controller::get_var('user', 'any');
     if ($user != 'any') {
         $arguments['user_id'] = $user;
     }
     // filter by ip
     $ip = Controller::get_var('address', 'any');
     if ($ip != 'any') {
         $arguments['ip'] = $ip;
     }
     // filter modules and types
     // @todo get events of a specific type in a specific module, instead of either of the two
     // the interface doesn't currently make any link between module and type, so we won't worry about it for now
     $module = Controller::get_var('module', 'any');
     $type = Controller::get_var('type', 'any');
     if ($module != 'any') {
         // we get a slugified key back, get the actual module name
         $arguments['module'] = $modules[$module];
     }
     if ($type != 'any') {
         // we get a slugified key back, get the actual type name
         $arguments['type'] = $types[$type];
     }
     // filter by severity
     $severity = Controller::get_var('severity', 0);
     if ($severity != 0) {
         $arguments['severity'] = $severity;
     }
     // get the logs!
     $logs = EventLog::get($arguments);
     // last, but not least, generate the list of years used for the timeline
     $months = EventLog::get(array_merge($arguments, array('month_cts' => true)));
     $years = array();
     foreach ($months as $m) {
         $years[$m->year][] = $m;
     }
     // assign all our theme values in one spot
     // first the filter options
     $this->theme->dates = $dates;
     $this->theme->users = $users;
     $this->theme->addresses = $ips;
     $this->theme->modules = $modules;
     $this->theme->types = $types;
     $this->theme->severities = $severities;
     // next the filter criteria we used
     $this->theme->search_args = $search;
     $this->theme->date = $date;
     $this->theme->user = $user;
     $this->theme->address = $ip;
     $this->theme->module = $module;
     $this->theme->type = $type;
     $this->theme->severity = $severity;
     $this->theme->logs = $logs;
     $this->theme->years = $years;
     $form = new FormUI('logs_batch', 'logs_batch');
     $form->append(FormControlAggregate::create('entries')->set_selector('.log_entry')->set_value(array())->label('None Selected'));
     $form->append($actions = FormControlDropbutton::create('actions'));
     $actions->append(FormControlSubmit::create('delete_selected')->on_success(function (FormUI $form) {
         $ids = $form->entries->value;
         $count = 0;
         /** @var LogEntry $log */
         foreach ($ids as $id) {
             $logs = EventLog::get(array('id' => $id));
             foreach ($logs as $log) {
                 $log->delete();
                 $count++;
             }
         }
         Session::notice(_t('Deleted %d logs.', array($count)));
         $form->bounce(false);
     })->set_caption(_t('Delete Selected')));
     $actions->append(FormControlSubmit::create('purge_logs')->on_success(function (FormUI $form) {
         if (EventLog::purge()) {
             Session::notice(_t('Logs purged.'));
         } else {
             Session::notice(_t('There was a problem purging the event logs.'));
         }
         $form->bounce(false);
     })->set_caption(_t('Purge Logs')));
     $this->theme->form = $form;
     $this->theme->wsse = Utils::WSSE();
     // prepare a WSSE token for any ajax calls
 }
Example #9
0
    /**
     * function get
     * Returns requested comments
     * @param array $paramarray An associated array of parameters, or a querystring
     * @return array An array of Comment objects, one for each query result
     *
     * <code>
     * $comments = comments::get( array ( "author" => "skippy" ) );
     * $comments = comments::get( array ( "slug" => "first-post", "status" => "1", "orderby" => "date ASC" ) );
     * </code>
     **/
    public static function get($paramarray = array())
    {
        $params = array();
        $fns = array('get_results', 'get_row', 'get_value');
        $select = '';
        // what to select -- by default, everything
        foreach (Comment::default_fields() as $field => $value) {
            $select .= '' == $select ? "{comments}.{$field} as {$field}" : ", {comments}.{$field} as {$field}";
        }
        // defaults
        $orderby = 'date DESC';
        $limit = Options::get('pagination');
        // Put incoming parameters into the local scope
        $paramarray = Utils::get_params($paramarray);
        // let plugins alter the param array before we use it. could be useful for modifying search results, etc.
        $paramarray = Plugins::filter('comments_get_paramarray', $paramarray);
        $join_params = array();
        // Transact on possible multiple sets of where information that is to be OR'ed
        if (isset($paramarray['where']) && is_array($paramarray['where'])) {
            $wheresets = $paramarray['where'];
        } else {
            $wheresets = array(array());
        }
        $wheres = array();
        $joins = array();
        if (isset($paramarray['where']) && is_string($paramarray['where'])) {
            $wheres[] = $paramarray['where'];
        } else {
            foreach ($wheresets as $paramset) {
                // safety mechanism to prevent empty queries
                $where = array('1=1');
                $paramset = array_merge((array) $paramarray, (array) $paramset);
                if (isset($paramset['id']) && (is_numeric($paramset['id']) || is_array($paramset['id']))) {
                    if (is_numeric($paramset['id'])) {
                        $where[] = "{comments}.id= ?";
                        $params[] = $paramset['id'];
                    } else {
                        if (is_array($paramset['id']) && !empty($paramset['id'])) {
                            $id_list = implode(',', $paramset['id']);
                            // Clean up the id list - remove all non-numeric or comma information
                            $id_list = preg_replace("/[^0-9,]/", "", $id_list);
                            // You're paranoid, ringmaster! :P
                            $limit = count($paramset['id']);
                            $where[] = '{comments}.id IN (' . addslashes($id_list) . ')';
                        }
                    }
                }
                if (isset($paramset['status']) && false !== $paramset['status']) {
                    if (is_array($paramset['status'])) {
                        $paramset['status'] = array_diff($paramset['status'], array('any'));
                        array_walk($paramset['status'], function (&$a) {
                            $a = Comment::status($a);
                        });
                        $where[] = "{comments}.status IN (" . Utils::placeholder_string(count($paramset['status'])) . ")";
                        $params = array_merge($params, $paramset['status']);
                    } else {
                        $where[] = "{comments}.status= ?";
                        $params[] = Comment::status($paramset['status']);
                    }
                }
                if (isset($paramset['type']) && false !== $paramset['type']) {
                    if (is_array($paramset['type'])) {
                        $paramset['type'] = array_diff($paramset['type'], array('any'));
                        array_walk($paramset['type'], function (&$a) {
                            $a = Comment::type($a);
                        });
                        $where[] = "type IN (" . Utils::placeholder_string(count($paramset['type'])) . ")";
                        $params = array_merge($params, $paramset['type']);
                    } else {
                        $where[] = "type= ?";
                        $params[] = Comment::type($paramset['type']);
                    }
                }
                if (isset($paramset['name'])) {
                    $where[] = "LOWER( name ) = ?";
                    $params[] = MultiByte::strtolower($paramset['name']);
                }
                if (isset($paramset['email'])) {
                    $where[] = "LOWER( email ) = ?";
                    $params[] = MultiByte::strtolower($paramset['email']);
                }
                if (isset($paramset['url'])) {
                    $where[] = "LOWER( url ) = ?";
                    $params[] = MultiByte::strtolower($paramset['url']);
                }
                if (isset($paramset['post_id'])) {
                    $where[] = "{comments}.post_id= ?";
                    $params[] = $paramset['post_id'];
                }
                if (isset($paramset['ip'])) {
                    $where[] = "ip= ?";
                    $params[] = $paramset['ip'];
                }
                /* do searching */
                if (isset($paramset['post_author'])) {
                    $joins['posts'] = ' INNER JOIN {posts} ON {comments}.post_id = {posts}.id';
                    if (is_array($paramset['post_author'])) {
                        $where[] = "{posts}.user_id IN (" . implode(',', array_fill(0, count($paramset['post_author']), '?')) . ")";
                        $params = array_merge($params, $paramset['post_author']);
                    } else {
                        $where[] = '{posts}.user_id = ?';
                        $params[] = (string) $paramset['post_author'];
                    }
                }
                if (isset($paramset['criteria'])) {
                    if (isset($paramset['criteria_fields'])) {
                        // Support 'criteria_fields' => 'author,ip' rather than 'criteria_fields' => array( 'author', 'ip' )
                        if (!is_array($paramset['criteria_fields']) && is_string($paramset['criteria_fields'])) {
                            $paramset['criteria_fields'] = explode(',', $paramset['criteria_fields']);
                        }
                    } else {
                        $paramset['criteria_fields'] = array('content');
                    }
                    $paramset['criteria_fields'] = array_unique($paramset['criteria_fields']);
                    preg_match_all('/(?<=")([\\p{L}\\p{N}]+[^"]*)(?=")|([\\p{L}\\p{N}]+)/u', $paramset['criteria'], $matches);
                    $where_search = array();
                    foreach ($matches[0] as $word) {
                        foreach ($paramset['criteria_fields'] as $criteria_field) {
                            $where_search[] .= "( LOWER( {comments}.{$criteria_field} ) LIKE ? )";
                            $params[] = '%' . MultiByte::strtolower($word) . '%';
                        }
                    }
                    if (count($where_search) > 0) {
                        $where[] = '(' . implode(" \nOR\n ", $where_search) . ')';
                    }
                }
                /*
                 * Build the pubdate
                 * If we've got the day, then get the date.
                 * If we've got the month, but no date, get the month.
                 * If we've only got the year, get the whole year.
                 * @todo Ensure that we've actually got all the needed parts when we query on them
                 * @todo Ensure that the value passed in is valid to insert into a SQL date (ie '04' and not '4')
                 */
                if (isset($paramset['day'])) {
                    /* Got the full date */
                    $where[] = 'date BETWEEN ? AND ?';
                    $start_date = sprintf('%d-%02d-%02d', $paramset['year'], $paramset['month'], $paramset['day']);
                    $start_date = DateTime::create($start_date);
                    $params[] = $start_date->sql;
                    $params[] = $start_date->modify('+1 day')->sql;
                } elseif (isset($paramset['month'])) {
                    $where[] = 'date BETWEEN ? AND ?';
                    $start_date = sprintf('%d-%02d-%02d', $paramset['year'], $paramset['month'], 1);
                    $start_date = DateTime::create($start_date);
                    $params[] = $start_date->sql;
                    $params[] = $start_date->modify('+1 month')->sql;
                } elseif (isset($paramset['year'])) {
                    $where[] = 'date BETWEEN ? AND ?';
                    $start_date = sprintf('%d-%02d-%02d', $paramset['year'], 1, 1);
                    $start_date = DateTime::create($start_date);
                    $params[] = $start_date->sql;
                    $params[] = $start_date->modify('+1 year')->sql;
                }
                // Concatenate the WHERE clauses
                if (count($where) > 0) {
                    $wheres[] = ' (' . implode(' AND ', $where) . ') ';
                }
            }
        }
        // Only show comments to which the current user has permission to read the associated post
        if (isset($paramset['ignore_permissions'])) {
            $master_perm_where = '';
            // Set up the merge params
            $merge_params = array($join_params, $params);
            $params = call_user_func_array('array_merge', $merge_params);
        } else {
            // This set of wheres will be used to generate a list of comment_ids that this user can read
            $perm_where = array();
            $perm_where_denied = array();
            $params_where = array();
            $where = array();
            // every condition here will require a join with the posts table
            $joins['posts'] = 'INNER JOIN {posts} ON {comments}.post_id={posts}.id';
            // Get the tokens that this user is granted or denied access to read
            $read_tokens = isset($paramset['read_tokens']) ? $paramset['read_tokens'] : ACL::user_tokens(User::identify(), 'read', true);
            $deny_tokens = isset($paramset['deny_tokens']) ? $paramset['deny_tokens'] : ACL::user_tokens(User::identify(), 'deny', true);
            // If a user can read his own posts, let him
            if (User::identify()->can('own_posts', 'read')) {
                $perm_where['own_posts_id'] = '{posts}.user_id = ?';
                $params_where[] = User::identify()->id;
            }
            // If a user can read any post type, let him
            if (User::identify()->can('post_any', 'read')) {
                $perm_where = array('post_any' => '(1=1)');
                $params_where = array();
            } else {
                // If a user can read specific post types, let him
                $permitted_post_types = array();
                foreach (Post::list_active_post_types() as $name => $posttype) {
                    if (User::identify()->can('post_' . Utils::slugify($name), 'read')) {
                        $permitted_post_types[] = $posttype;
                    }
                }
                if (count($permitted_post_types) > 0) {
                    $perm_where[] = '{posts}.content_type IN (' . implode(',', $permitted_post_types) . ')';
                }
                // If a user can read posts with specific tokens, let him see comments on those posts
                if (count($read_tokens) > 0) {
                    $joins['post_tokens__allowed'] = ' LEFT JOIN {post_tokens} pt_allowed ON {posts}.id= pt_allowed.post_id AND pt_allowed.token_id IN (' . implode(',', $read_tokens) . ')';
                    $perm_where['perms_join_null'] = 'pt_allowed.post_id IS NOT NULL';
                }
            }
            // If a user is denied access to all posts, do so
            if (User::identify()->cannot('post_any')) {
                $perm_where_denied = array('(0=1)');
            } else {
                // If a user is denied read access to specific post types, deny him
                $denied_post_types = array();
                foreach (Post::list_active_post_types() as $name => $posttype) {
                    if (User::identify()->cannot('post_' . Utils::slugify($name))) {
                        $denied_post_types[] = $posttype;
                    }
                }
                if (count($denied_post_types) > 0) {
                    $perm_where_denied[] = '{posts}.content_type NOT IN (' . implode(',', $denied_post_types) . ')';
                }
            }
            // If there are granted permissions to check, add them to the where clause
            if (count($perm_where) == 0 && !isset($joins['post_tokens__allowed'])) {
                // You have no grants.  You get no comments.
                $where['perms_granted'] = '(0=1)';
            } elseif (count($perm_where) > 0) {
                $where['perms_granted'] = '
					(' . implode(' OR ', $perm_where) . ')
				';
                $params = array_merge($params, $params_where);
            }
            if (count($deny_tokens) > 0) {
                $joins['post_tokens__denied'] = ' LEFT JOIN {post_tokens} pt_denied ON {posts}.id= pt_denied.post_id AND pt_denied.token_id IN (' . implode(',', $deny_tokens) . ')';
                $perm_where_denied['perms_join_null'] = 'pt_denied.post_id IS NULL';
            }
            // If there are denied permissions to check, add them to the where clause
            if (count($perm_where_denied) > 0) {
                $where['perms_denied'] = '
					(' . implode(' AND ', $perm_where_denied) . ')
				';
            }
            $master_perm_where = implode(' AND ', $where);
        }
        // Get any full-query parameters
        $possible = array('page', 'fetch_fn', 'count', 'month_cts', 'nolimit', 'limit', 'offset', 'orderby');
        foreach ($possible as $varname) {
            if (isset($paramarray[$varname])) {
                ${$varname} = $paramarray[$varname];
            }
        }
        if (isset($page) && is_numeric($page)) {
            $offset = (intval($page) - 1) * intval($limit);
        }
        if (isset($fetch_fn)) {
            if (!in_array($fetch_fn, $fns)) {
                $fetch_fn = $fns[0];
            }
        } else {
            $fetch_fn = $fns[0];
        }
        // is a count being request?
        if (isset($count)) {
            $select = "COUNT( 1 )";
            $fetch_fn = 'get_value';
            $orderby = '';
        }
        // is a count of comments by month being requested?
        $groupby = '';
        if (isset($month_cts)) {
            $select = 'MONTH(FROM_UNIXTIME(date)) AS month, YEAR(FROM_UNIXTIME(date)) AS year, COUNT({comments}.id) AS ct';
            $groupby = 'year, month';
            $orderby = 'year, month';
        }
        if (isset($limit)) {
            $limit = " LIMIT {$limit}";
            if (isset($offset)) {
                $limit .= " OFFSET {$offset}";
            }
        }
        if (isset($nolimit) || isset($month_cts)) {
            $limit = '';
        }
        // Build the final SQL statement
        $query = '
			SELECT DISTINCT ' . $select . ' FROM {comments} ' . implode(' ', $joins);
        if (count($wheres) > 0) {
            $query .= ' WHERE (' . implode(" \nOR\n ", $wheres) . ')';
            $query .= $master_perm_where == '' ? '' : ' AND (' . $master_perm_where . ')';
        } elseif ($master_perm_where != '') {
            $query .= ' WHERE (' . $master_perm_where . ')';
        }
        $query .= $groupby == '' ? '' : ' GROUP BY ' . $groupby;
        $query .= ($orderby == '' ? '' : ' ORDER BY ' . $orderby) . $limit;
        DB::set_fetch_mode(\PDO::FETCH_CLASS);
        DB::set_fetch_class('Comment');
        $results = DB::$fetch_fn($query, $params, 'Comment');
        if ('get_results' != $fetch_fn) {
            // return the results
            return $results;
        } elseif (is_array($results)) {
            $c = __CLASS__;
            $return_value = new $c($results);
            $return_value->get_param_cache = $paramarray;
            return $return_value;
        }
        return false;
    }
Example #10
0
 /**
  * Compare the current set of plugins with those we last checked for updates.
  * This is run by AdminHandler on every page load to make sure we always have fresh data on the dashboard.
  */
 public static function check_plugins()
 {
     // register the beacons
     self::register_beacons();
     // get the list we checked last time
     $checked_list = Options::get('updates_beacons');
     // if the lists are different
     if ($checked_list != self::instance()->beacons) {
         // remove any stored updates, just to avoid showing stale data
         Options::delete('updates_available');
         // schedule an update check the next time cron runs
         CronTab::add_single_cron('update_check_single', Method::create('\\Habari\\Update', 'cron'), DateTime::create()->int, _t('Perform a single check for plugin updates, the plugin set has changed.'));
     }
 }
Example #11
0
 /**
  * Magic property setter to set the cronjob properties.
  * Serializes the callback if needed.
  *
  * @see QueryRecord::__set()
  * @param string $name The name of the property to set.
  * @param mixed $value The value of the property to set.
  * @return mixed The new value of the property.
  */
 public function __set($name, $value)
 {
     switch ($name) {
         case 'callback':
             if (is_array($value) || is_object($value)) {
                 $value = serialize($value);
             }
             break;
         case 'next_run':
         case 'last_run':
         case 'start_time':
         case 'end_time':
             if (!$value instanceof DateTime && !is_null($value)) {
                 $value = DateTime::create($value);
             }
             break;
     }
     return parent::__set($name, $value);
 }
Example #12
0
 /**
  * Returns an array representing the difference between two times by interval.
  * 
  * <code>
  * 	print_r( DateTime::difference( 'now', 'January 1, 2010' ) );
  * 	// output (past): Array ( [invert] => [y] => 0 [m] => 9 [w] => 3 [d] => 5 [h] => 22 [i] => 33 [s] => 5 )
  * 	print_r( DateTime::difference( 'now', 'January 1, 2011' ) );
  * 	// output (future): Array ( [invert] => 1 [y] => 0 [m] => 2 [w] => 0 [d] => 3 [h] => 5 [i] => 33 [s] => 11 ) 
  * </code>
  * 
  *  If 'invert' is true, the time is in the future (ie: x from now). If it is false, the time is in the past (ie: x ago).
  *  
  *  For more information, see PHP's DateInterval class, which this and friendly() attempt to emulate for < PHP 5.3
  *  
  *  @todo Add total_days, total_years, etc. values?
  * 
  * @param mixed $start_date The start date, as a HDT object or any format accepted by DateTime::create().
  * @param mixed $end_date The end date, as a HDT object or any format accepted by DateTime::create().
  * @return array Array of each interval and whether the interval is inverted or not.
  */
 public static function difference($start_date, $end_date)
 {
     // if the dates aren't HDT objects, try to convert them to one. this lets you pass in just about any format
     if (!$start_date instanceof DateTime) {
         $start_date = DateTime::create($start_date);
     }
     if (!$end_date instanceof DateTime) {
         $end_date = DateTime::create($end_date);
     }
     $result = array();
     // calculate the difference, in seconds
     $difference = $end_date->int - $start_date->int;
     if ($difference < 0) {
         // if it's negative, time AGO
         $result['invert'] = false;
     } else {
         // if it's positive, time UNTIL
         $result['invert'] = true;
     }
     $difference = abs($difference);
     // we'll progressively subtract from the seconds left, so initialize it
     $seconds_left = $difference;
     $result['y'] = floor($seconds_left / self::YEAR);
     $seconds_left = $seconds_left - $result['y'] * self::YEAR;
     $result['m'] = floor($seconds_left / self::MONTH);
     $seconds_left = $seconds_left - $result['m'] * self::MONTH;
     $result['w'] = floor($seconds_left / self::WEEK);
     $seconds_left = $seconds_left - $result['w'] * self::WEEK;
     $result['d'] = floor($seconds_left / self::DAY);
     $seconds_left = $seconds_left - $result['d'] * self::DAY;
     $result['h'] = floor($seconds_left / self::HOUR);
     $seconds_left = $seconds_left - $result['h'] * self::HOUR;
     $result['i'] = floor($seconds_left / self::MINUTE);
     $seconds_left = $seconds_left - $result['i'] * self::MINUTE;
     $result['s'] = $seconds_left;
     return $result;
 }
Example #13
0
 /**
  * Return max validator
  *
  * @return DateTime
  */
 public function max()
 {
     return DateTime::create();
 }
Example #14
0
 /**
  * function update_scheduled_posts_cronjob
  *
  * Creates or recreates the cronjob to publish
  * scheduled posts. It is called whenever a post
  * is updated or created
  *
  */
 public static function update_scheduled_posts_cronjob()
 {
     $min_time = DB::get_value('SELECT MIN(pubdate) FROM {posts} WHERE status = ?', array(Post::status('scheduled')));
     CronTab::delete_cronjob('publish_scheduled_posts');
     if ($min_time) {
         CronTab::add_single_cron('publish_scheduled_posts', Method::create('\\Habari\\Posts', 'publish_scheduled_posts'), $min_time, 'Next run: ' . DateTime::create($min_time)->get('c'));
     }
 }
Example #15
0
 public static function trim()
 {
     // allow an option to be set to override the log retention - in days
     $retention_days = Options::get('log_retention', 14);
     // default to 14 days
     // make it into the string we'll use
     $retention = '-' . intval($retention_days) . ' days';
     // Trim the log table down
     $date = DateTime::create()->modify($retention);
     $result = DB::query('DELETE FROM {log} WHERE timestamp < ?', array($date->sql));
     if ($result) {
         EventLog::log(_t('Entries over %d days old were trimmed from the EventLog', array($retention_days)), 'info');
     } else {
         EventLog::log(_t('There was an error trimming old entries from the EventLog!'), 'err');
     }
     return $result;
 }
Example #16
0
}
?>
</p>
		</div>
		<?php 
if (!empty($updates)) {
    ?>
				
					<ul class="updates">
					
						<?php 
    foreach ($updates as $beacon_id => $beacon) {
        $u_strings = array();
        foreach ($beacon['updates'] as $u_version => $u) {
            if (!empty($u['date'])) {
                $u_title = _t('%1$s update released on %2$s: %3$s', array(MultiByte::ucfirst($u['severity']), DateTime::create($u['date'])->format('Y-m-d'), Utils::htmlspecialchars($u['text'])));
            } else {
                $u_title = _t('%1$s update: %3$s', array(MultiByte::ucfirst($u['severity']), $u['date'], Utils::htmlspecialchars($u['text'])));
            }
            if (!empty($u['url'])) {
                $u_string = sprintf('<a href="%1$s" title="%2$s" class="%3$s">%4$s</a>', $u['url'], $u_title, $u['severity'], $u['version']);
            } else {
                $u_string = sprintf('<span title="%1$s" class="%2$s">%3$s</span>', $u_title, $u['severity'], $u['version']);
            }
            // add it to the array of updates available for this plugin
            $u_strings[$u['version']] = $u_string;
        }
        $u_strings = Format::and_list($u_strings);
        ?>
								
									<li class="update">
Example #17
0
 /**
  * function nice_time
  * Formats a time using a date format string
  * @param DateTime $date A date as a DateTime object
  * @param string $dateformat A date format string
  * @returns string The time formatted as a string
  */
 public static function nice_time($date, $dateformat = 'H:i:s')
 {
     if (!$date instanceof DateTime) {
         $date = DateTime::create($date);
     }
     return $date->format($dateformat);
 }
Example #18
0
 /**
  * Overrides QueryRecord __set to implement custom object properties
  *
  * @param string $name name of property to return
  * @param mixed $value The requested field value
  * @return mixed The requested field value
  */
 public function __set($name, $value)
 {
     switch ($name) {
         case 'timestamp':
             if (!$value instanceof DateTime) {
                 $value = DateTime::create($value);
             }
             break;
     }
     return parent::__set($name, $value);
 }
Example #19
0
 /**
  * Handles GET requests for an individual comment.
  */
 public function get_comment($update = false)
 {
     if (isset($this->handler_vars['id']) && ($comment = Comment::get($this->handler_vars['id']))) {
         $this->theme->comment = $comment;
         // Convenience array to output actions twice
         $actions = array('deleted' => 'delete', 'spam' => 'spam', 'unapproved' => 'unapprove', 'approved' => 'approve', 'saved' => 'save');
         $form = $this->form_comment($comment, $actions);
         if ($update) {
             // Get the $_POSTed values
             $form->process();
             foreach ($actions as $key => $action) {
                 $id_one = $action . '_1';
                 $id_two = $action . '_2';
                 if ($form->{$id_one}->value != null || $form->{$id_two}->value != null) {
                     if ($action == 'delete') {
                         $comment->delete();
                         Utils::redirect(URL::get('display_comments'));
                     }
                     if ($action != 'save') {
                         foreach (Comment::list_comment_statuses() as $status) {
                             if ($status == $key) {
                                 $comment->status = Comment::status_name($status);
                                 $set_status = true;
                             }
                         }
                     }
                 }
             }
             $comment->content = $form->content->value;
             $comment->name = $form->author_name->value;
             $comment->url = $form->author_url->value;
             $comment->email = $form->author_email->value;
             $comment->ip = $form->author_ip->value;
             $comment->date = DateTime::create($form->comment_date->value);
             $comment->post_id = $form->comment_post->value;
             if (!isset($set_status)) {
                 $comment->status = $form->comment_status->value;
             }
             $comment->update();
             Plugins::act('comment_edit', $comment, $form);
             Utils::redirect();
         }
         $comment->content = $form;
         $this->theme->form = $form;
         $this->display('comment');
     } else {
         Utils::redirect(URL::get('display_comments'));
     }
 }
Example #20
0
 public function __construct()
 {
     $self = $this;
     FormUI::register('add_user', function (FormUI $form, $name) use($self) {
         $form->set_settings(array('use_session_errors' => true));
         $form->append(FormControlText::create('username')->set_properties(array('class' => 'columns three', 'placeholder' => _t('Username')))->add_validator('validate_username')->add_validator('validate_required'));
         $form->append(FormControlText::create('email')->set_properties(array('class' => 'columns four', 'placeholder' => _t('E-Mail')))->add_validator('validate_email')->add_validator('validate_required'));
         $password = FormControlPassword::create('password')->set_properties(array('class' => 'columns three', 'placeholder' => _t('Password')))->add_validator('validate_required');
         $form->append($password);
         $form->append(FormControlPassword::create('password_again')->set_properties(array('class' => 'columns three', 'placeholder' => _t('Password Again')))->add_validator('validate_same', $password));
         $form->append(FormControlSubmit::create('newuser')->set_caption('Add User'));
         $form->add_validator(array($self, 'validate_add_user'));
         $form->on_success(array($self, 'do_add_user'));
     });
     FormUI::register('delete_users', function (FormUI $form, $name) use($self) {
         $form->set_settings(array('use_session_errors' => true));
         $form->append(FormControlAggregate::create('deletion_queue')->set_selector('.select_user')->label('Select All'));
         $author_list = Users::get_all();
         $authors[0] = _t('nobody');
         foreach ($author_list as $author) {
             $authors[$author->id] = $author->displayname;
         }
         $form->append(FormControlSelect::create('reassign')->set_options($authors));
         $form->append(FormControlSubmit::create('delete_selected')->set_caption(_t('Delete Selected')));
         $form->add_validator(array($self, 'validate_delete_users'));
         $form->on_success(array($self, 'do_delete_users'));
     });
     FormUI::register('edit_user', function (FormUI $form, $name, $form_type, $data) use($self) {
         $form->set_settings(array('use_session_errors' => true));
         $edit_user = $data['edit_user'];
         $field_sections = array('user_info' => _t('User Information'), 'change_password' => _t('Change Password'), 'regional_settings' => _t('Regional Settings'), 'dashboard' => _t('Dashboard'));
         // Create a tracker for who we are dealing with
         $form->append(FormControlData::create('edit_user')->set_value($edit_user->id));
         // Generate sections
         foreach ($field_sections as $key => $name) {
             $fieldset = $form->append('wrapper', $key, $name);
             $fieldset->add_class('container main settings');
             $fieldset->append(FormControlStatic::create($key)->set_static('<h2 class="lead">' . htmlentities($name, ENT_COMPAT, 'UTF-8') . '</h2>'));
         }
         // User Info
         $displayname = FormControlText::create('displayname')->set_value($edit_user->displayname);
         $form->user_info->append(FormControlLabel::wrap(_t('Display Name'), $displayname));
         $username = FormControlText::create('username')->add_validator('validate_username', $edit_user->username)->set_value($edit_user->username);
         $form->user_info->append(FormControlLabel::wrap(_t('User Name'), $username));
         $email = FormControlText::create('email')->add_validator('validate_email')->set_value($edit_user->email);
         $form->user_info->append(FormControlLabel::wrap(_t('Email'), $email));
         $imageurl = FormControlText::create('imageurl')->set_value($edit_user->info->imageurl);
         $form->user_info->append(FormControlLabel::wrap(_t('Portrait URL'), $imageurl));
         // Change Password
         $password1 = FormControlPassword::create('password1', null, array('autocomplete' => 'off'))->set_value('');
         $form->change_password->append(FormControlLabel::wrap(_t('New Password'), $password1));
         $password2 = FormControlPassword::create('password2', null, array('autocomplete' => 'off'))->set_value('');
         $form->change_password->append(FormControlLabel::wrap(_t('New Password Again'), $password2));
         $delete = $self->handler_vars->filter_keys('delete');
         // don't validate password match if action is delete
         if (!isset($delete['delete'])) {
             $password2->add_validator('validate_same', $password1, _t('Passwords must match.'));
         }
         // Regional settings
         $timezones = \DateTimeZone::listIdentifiers();
         $timezones = array_merge(array_combine(array_values($timezones), array_values($timezones)));
         $locale_tz = FormControlSelect::create('locale_tz', null, array('multiple' => false))->set_options($timezones)->set_value($edit_user->info->locale_tz);
         $form->regional_settings->append(FormControlLabel::wrap(_t('Timezone'), $locale_tz));
         $locale_date_format = FormControlText::create('locale_date_format')->set_value($edit_user->info->locale_date_format);
         $form->regional_settings->append(FormControlLabel::wrap(_t('Date Format'), $locale_date_format));
         $edit_user_info = $edit_user->info;
         if (isset($edit_user_info->locale_date_format) && $edit_user_info->locale_date_format != '') {
             $current = DateTime::create()->get($edit_user_info->locale_date_format);
         } else {
             $current = DateTime::create()->date;
         }
         $locale_date_format->set_helptext(_t('See <a href="%s">php.net/date</a> for details. Current format: %s', array('http://php.net/date', $current)));
         $locale_time_format = FormControlText::create('locale_time_format')->set_value($edit_user_info->locale_time_format);
         $form->regional_settings->append(FormControlLabel::wrap(_t('Time Format'), $locale_time_format));
         if (isset($edit_user_info->locale_time_format) && $edit_user_info->locale_time_format != '') {
             $current = DateTime::create()->get($edit_user_info->locale_time_format);
         } else {
             $current = DateTime::create()->time;
         }
         $locale_time_format->set_helptext(_t('See <a href="%s">php.net/date</a> for details. Current format: %s', array('http://php.net/date', $current)));
         $locales = array_merge(array('' => _t('System default') . ' (' . Options::get('locale', 'en-us') . ')'), array_combine(Locale::list_all(), Locale::list_all()));
         $locale_lang = FormcontrolSelect::create('locale_lang', null, array('multiple' => false))->set_options($locales)->set_value($edit_user_info->locale_lang);
         $form->regional_settings->append(FormControlLabel::wrap(_t(' Language'), $locale_lang));
         $spam_count = FormControlCheckbox::create('dashboard_hide_spam_count')->set_helptext(_t('Hide the number of SPAM comments on your dashboard.'))->set_value($edit_user_info->dashboard_hide_spam_count);
         $form->dashboard->append(FormControlLabel::wrap(_t('Hide Spam Count'), $spam_count));
         // Groups
         if (User::identify()->can('manage_groups')) {
             $fieldset = $form->append(FormControlWrapper::create('groups'));
             $fieldset->add_class('container main settings');
             $fieldset->append(FormControlStatic::create('groups_title')->set_static('<h2 class="lead">' . htmlentities(_t('Groups'), ENT_COMPAT, 'UTF-8') . '</h2>'));
             $fieldset->append(FormControlCheckboxes::create('user_group_membership')->set_options(Utils::array_map_field(UserGroups::get_all(), 'name', 'id'))->set_value($edit_user->groups));
         }
         // Controls
         $controls = $form->append(FormControlWrapper::create('page_controls')->add_class('container controls transparent'));
         $apply = $controls->append(FormControlSubmit::create('apply')->set_caption(_t('Apply')));
         // Get author list
         $author_list = Users::get_all();
         $authors[0] = _t('nobody');
         foreach ($author_list as $author) {
             $authors[$author->id] = $author->displayname;
         }
         unset($authors[$edit_user->id]);
         // We can't reassign this user's posts to themselves if we're deleting them
         $reassign = FormControlSelect::create('reassign')->set_options($authors);
         $reassign_label = FormControlLabel::wrap(_t('Reassign posts to:'), $reassign)->set_settings(array('wrap' => '<span class="reassigntext">%s</span>'));
         $controls->append($reassign_label);
         $controls->append(FormControlStatic::create('conjunction')->set_static(_t('and'))->set_settings(array('wrap' => '<span class="conjunction">%s</span>')));
         $delete = $controls->append(FormControlSubmit::create('delete')->set_caption(_t('Delete'))->set_settings(array('wrap' => '<span>%s</span>'))->add_class('button'));
         $delete->on_success(array($self, 'edit_user_delete'));
         $delete->add_validator(array($self, 'validate_delete_user'));
         $apply->on_success(array($self, 'edit_user_apply'));
         $apply->add_validator(array($self, 'validate_edit_user'));
     });
     parent::__construct();
 }
Example #21
0
 /**
  * Sends HTTP headers that limit the cacheability of the page.
  *
  * @link http://php.net/session_cache_limiter
  * @param string $type The type of caching headers to send. One of: 'public', 'private_no_expire', 'private', 'nocache', or ''.
  * @return void
  */
 public static function cache_limiter($type = 'nocache')
 {
     $expires = DateTime::create('+' . session_cache_expire() . ' seconds')->format(DateTime::RFC1123);
     $last_modified = DateTime::create()->format(DateTime::RFC1123);
     switch ($type) {
         case 'public':
             header('Expires: ' . $expires, true);
             header('Cache-Control: public, max-age=' . $expires, true);
             header('Last-Modified: ' . $last_modified, true);
             break;
         case 'private_no_expire':
             header('Cache-Control: private, max-age=' . $expires . ', pre-check=' . $expires, true);
             header('Last-Modified: ' . $last_modified, true);
             break;
         case 'private':
             header('Expires: Thu, 19 Nov 1981 08:52:00 GMT', true);
             header('Cache-Control: private max-age=' . $expires . ', pre-check=' . $expires, true);
             header('Last-Modified: ' . $last_modified, true);
             break;
         case 'nocache':
             header('Expires: Thu, 19 Nov 1981 08:52:00 GMT', true);
             header('Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0', true);
             header('Pragma: no-cache', true);
             break;
         case '':
             return;
             break;
     }
 }
								<?php 
    }
    ?>
							</tr>
						</thead>
						<tbody>
						<?php 
    foreach ($post->versions as $v) {
        ?>
							<tr>
								<td><?php 
        echo $v->term_display;
        ?>
</td>
								<td><?php 
        echo DateTime::create($v->info->release)->format(Options::get("plugin_directory__date_format", "F j, Y"));
        ?>
</td>
								<td><a href="<?php 
        echo $v->download_url;
        ?>
">Download <?php 
        echo $v->info->version;
        ?>
</a></td>
								<?php 
        if (count($permitted_versions) > 0) {
            ?>
								<td>
								<?php 
            if (in_array($v->term, $permitted_versions)) {
 public static function handle_addon($info = array(), $versions = array())
 {
     // Allow plugins to modify a new addon before it is created.
     Plugins::act('handle_addon_before', $info, $versions);
     $main_fields = array('user_id' => 'user_id', 'name' => 'title', 'description' => 'content', 'tags' => 'tags');
     $post_fields = array('content_type' => Post::type('addon'), 'status' => Post::status('published'), 'pubdate' => DateTime::create());
     $post = self::get_addon(strtoupper($info['guid']));
     // strtoupper might not be necessary
     if (!$post) {
         /* There is no addon already with the guid. Create a new one. */
         foreach ($main_fields as $k => $v) {
             $post_fields[$v] = $info[$k];
         }
         unset($post);
         $post = Post::create($post_fields);
         $post->info->hoster = $info['hoster'];
         $post->update();
         EventLog::log(_t('Created post #%s - %s', array($post->id, $post->title)), 'info');
     } else {
         /* Update the existing addon. */
         $post->modify(array('title' => $info['name'], 'content' => $info['description'], 'slug' => Utils::slugify($info['name']), 'pubdate' => DateTime::date_create()));
         $post->update();
         EventLog::log(_t('Edited post #%s - %s', array($post->id, $post->title)), 'info');
         $info = array_diff_key($info, array('original_repo' => 'should be removed for updates'));
     }
     // remove the fields that should not become postinfo.
     $info_fields = array_diff_key($info, $main_fields);
     foreach ($info_fields as $k => $v) {
         switch ($k) {
             case 'guid':
                 $post->info->{$k} = strtoupper($v);
                 break;
             default:
                 $post->info->{$k} = $v;
                 break;
         }
     }
     $post->info->commit();
     self::save_versions($post, $versions);
     // Allow plugins to act after a new addon has been created.
     Plugins::act('handle_addon_after', $info, $versions);
 }
Example #24
0
 /**
  * Save a new user to the users table
  */
 public function insert()
 {
     $allow = true;
     $allow = Plugins::filter('user_insert_allow', $allow, $this);
     if (!$allow) {
         return;
     }
     Plugins::act('user_insert_before', $this);
     $this->exclude_fields('id');
     $result = parent::insertRecord(DB::table('users'));
     $this->fields['id'] = DB::last_insert_id();
     // Make sure the id is set in the user object to match the row id
     $this->info->set_key($this->id);
     /* If a new user is being created and inserted into the db, info is only safe to use _after_ this set_key call. */
     // $this->info->option_default = "saved";
     // Set the default timezone, date format, and time format
     $this->info->locale_tz = Options::get('timezone');
     $this->info->locale_date_format = Options::get('dateformat');
     $this->info->locale_time_format = Options::get('timeformat');
     $this->info->locale_lang = Options::get('locale', 'en-us');
     // Save when this user was created
     $this->info->creation_time = DateTime::create()->format('Y-m-d H:i:s');
     $this->info->commit();
     if ($result) {
         // Add the user to the default authenticated group if it exists
         if (UserGroup::exists('authenticated')) {
             $this->add_to_group('authenticated');
         }
     }
     EventLog::log(_t('New user created: %s', array($this->username)), 'info', 'default', 'habari');
     Plugins::act('user_insert_after', $this);
     return $result;
 }
Example #25
0
 /**
  * Overrides QueryRecord __set to implement custom object properties
  * @param string $name Name of property to set
  * @param mixed $value Value of the property
  * @return mixed The set field value
  */
 public function __set($name, $value)
 {
     switch ($name) {
         case 'status':
             $value = self::status($value);
             break;
         case 'date':
             if (!$value instanceof DateTime) {
                 $value = DateTime::create($value);
             }
             break;
         case 'post':
             if (is_int($value)) {
                 // a post ID was passed
                 $p = Post::get(array('id' => $value));
                 $this->post_id = $p->id;
                 $this->post_object = $p;
             } elseif (is_string($value)) {
                 // a post Slug was passed
                 $p = Post::get(array('slug' => $value));
                 $this->post_id = $p->id;
                 $this->post_object = $p;
             } elseif (is_object($value)) {
                 // a Post object was passed, so just use it directly
                 $this->post_id = $value->id;
                 $this->post_object = $value;
             }
             return $value;
     }
     return parent::__set($name, $value);
 }
Example #26
0
 /**
  * Add a comment to the site
  *
  * @param mixed $post A Post object instance or Post object id
  * @param string $name The commenter's name
  * @param string $email The commenter's email address
  * @param string $url The commenter's website URL
  * @param string $content The comment content
  * @param array $extra An associative array of extra values that should be considered
  */
 function add_comment($post, $name = null, $email = null, $url = null, $content = null, $extra = null)
 {
     if (is_numeric($post)) {
         $post = Post::get(array('id' => $post));
     }
     if (!$post instanceof Post) {
         // Not sure what you're trying to pull here, but that's no good
         header('HTTP/1.1 403 Forbidden', true, 403);
         die;
     }
     /* Sanitize data */
     foreach (array('name', 'url', 'email', 'content') as $k) {
         ${$k} = InputFilter::filter(${$k});
     }
     // there should never be any HTML in the name, so do some extra filtering on it
     $name = strip_tags(html_entity_decode($name, ENT_QUOTES, 'UTF-8'));
     /* Sanitize the URL */
     if (!empty($url)) {
         $parsed = InputFilter::parse_url($url);
         if ($parsed['is_relative']) {
             // guess if they meant to use an absolute link
             $parsed = InputFilter::parse_url('http://' . $url);
             if (!$parsed['is_error']) {
                 $url = InputFilter::glue_url($parsed);
             } else {
                 // disallow relative URLs
                 $url = '';
             }
         }
         if ($parsed['is_pseudo'] || $parsed['scheme'] !== 'http' && $parsed['scheme'] !== 'https') {
             // allow only http(s) URLs
             $url = '';
         } else {
             // reconstruct the URL from the error-tolerant parsing
             // http:moeffju.net/blog/ -> http://moeffju.net/blog/
             $url = InputFilter::glue_url($parsed);
         }
     }
     /* Create comment object*/
     $comment = new Comment(array('post_id' => $post->id, 'name' => $name, 'email' => $email, 'url' => $url, 'ip' => Utils::get_ip(), 'content' => $content, 'status' => Comment::status('approved'), 'date' => DateTime::create(), 'type' => Comment::type('comment')));
     // Should this really be here or in a default filter?
     // In any case, we should let plugins modify the status after we set it here.
     $user = User::identify();
     if ($user->loggedin && $comment->email == $user->email) {
         $comment->status = 'approved';
     }
     // Allow themes to work with comment hooks
     Themes::create();
     // Allow plugins to change comment data and add commentinfo based on plugin-added form fields
     Plugins::act('comment_accepted', $comment, $this->handler_vars, $extra);
     $spam_rating = 0;
     $spam_rating = Plugins::filter('spam_filter', $spam_rating, $comment, $this->handler_vars, $extra);
     if ($spam_rating >= Options::get('spam_percentage', 100)) {
         $comment->status = 'spam';
     }
     $comment->insert();
     $anchor = '';
     // If the comment was saved
     if ($comment->id && $comment->status != 'spam') {
         $anchor = '#comment-' . $comment->id;
         // store in the user's session that this comment is pending moderation
         if ($comment->status == 'unapproved') {
             Session::notice(_t('Your comment is pending moderation.'), 'comment_' . $comment->id);
         }
         // if no cookie exists, we should set one
         // but only if the user provided some details
         $cookie_name = 'comment_' . Options::get('public-GUID');
         // build the string we store for the cookie
         $cookie_content = implode('#', array($comment->name, $comment->email, $comment->url));
         // if the user is not logged in and there is no cookie OR the cookie differs from the current set
         if (User::identify()->loggedin == false && (!isset($_COOKIE[$cookie_name]) || $_COOKIE[$cookie_name] != $cookie_content)) {
             // update the cookie
             setcookie($cookie_name, $cookie_content, time() + DateTime::YEAR, Site::get_path('base', true));
         }
     }
     // Return the commenter to the original page.
     Utils::redirect($post->permalink . $anchor);
 }