Example #1
0
 /**
  * read
  *
  * @param string $sid Session Id
  *
  * @return void
  */
 private function read($sid)
 {
     $row = $this->dbc->query("SELECT `session_data`\n            FROM " . SESSIONS . "\n            WHERE `session_id` = '" . $this->dbc->escapeValue($sid) . "'\n            LIMIT 1");
     if ($this->dbc->numRows($row) == 1) {
         $fields = $this->dbc->fetchAssoc($row);
         return $fields['session_data'];
     } else {
         return '';
     }
 }
Example #2
0
 function preload($ids, $aLEVEL = false)
 {
     parent::preload($ids, $aLEVEL);
     global $DB;
     $ids = array_diff($ids, array_keys(self::$PARENTS));
     if ($ids) {
         $r = $DB->menu->get(array('id' => $ids), 'id,parent,place');
         while (false !== ($data = Database::fetchAssoc($r))) {
             self::$PARENTS[$data['id']] = $data['parent'];
             self::$PLACES[$data['id']] = $data['place'];
         }
     }
 }
 function render($page = false)
 {
     global $DB, $Controller;
     if (!$page && isset($this)) {
         $page = $this;
     } elseif (!is_object($page)) {
         $page = $Controller->retrieve($page);
     }
     $r = $DB->formfields->get(array('id' => $page->ID, 'language' => $page->loadedLanguage), '*', false, 'sort');
     if (!Database::numRows($r)) {
         return '';
     }
     $uForm = new Form('uform');
     $form = array();
     while (false !== ($field = Database::fetchAssoc($r))) {
         $fieldName = 'uform[' . $field['field_id'] . ']';
         switch ($field['type']) {
             case 'Checkbox':
             case 'pCheckbox':
                 $Values = array_filter(array_map('trim', explode(',', $field['value'])));
                 $Names = array_map('idfy', $Values);
                 if (count($Values) > 1) {
                     $form[] = new checkset($field['label'], $fieldName, array_combine($Names, $Values), $field['type'] == 'pCheckbox');
                 } else {
                     $form[] = new Checkbox($field['label'], $fieldName, $field['type'] == 'pCheckbox');
                 }
                 break;
             case 'select':
             case 'mselect':
                 $Values = array_map('trim', explode(',', $field['value']));
                 $Names = array_map('idfy', $Values);
                 $form[] = new select($field['label'], $fieldName, array_combine($Names, $Values), false, $field['type'] == 'mselect');
                 break;
             case 'Radio':
                 $Values = array_map('trim', explode(',', $field['value']));
                 $Names = array_map('idfy', $Values);
                 $form[] = new Radioset($field['label'], $fieldName, array_combine($Names, $Values));
                 break;
             case 'input':
             case 'textarea':
             case 'htmlfield':
                 $form[] = new $field['type']($field['label'], $fieldName, $field['value']);
                 break;
         }
     }
     if (empty($form)) {
         return '';
     }
     return $uForm->set($form);
 }
 function run()
 {
     global $DB, $Templates;
     if (!$this->mayI(READ)) {
         errorPage(401);
     }
     $_REQUEST->setType('delsd', 'string');
     $_REQUEST->setType('editsd', 'string');
     $_POST->setType('sdname', 'string');
     $_POST->setType('sdassoc', 'string');
     if ($_POST['sdname']) {
         if ($_REQUEST['editsd']) {
             if ($DB->subdomains->update(array('subdomain' => $_POST['sdname'], 'assoc' => $_POST['sdassoc']), array('subdomain' => $_REQUEST['editsd']))) {
                 Flash::create(__('Subdomain updated'), 'confirmation');
             } else {
                 Flash::create(__('Subdomain in use'), 'warning');
             }
         } else {
             if ($DB->subdomains->insert(array('subdomain' => $_POST['sdname'], 'assoc' => $_POST['sdassoc']))) {
                 Flash::create(__('New subdomain inserted'), 'confirmation');
             } else {
                 Flash::create(__('Subdomain in use'), 'warning');
             }
         }
     } elseif ($_REQUEST['delsd'] && $this->mayI(EDIT)) {
         $DB->subdomains->delete(array('subdomain' => $_REQUEST['delsd']));
     }
     $r = $DB->subdomains->get(false, false, false, 'subdomain');
     $tablerows = array();
     while (false !== ($subdomain = Database::fetchAssoc($r))) {
         $tablerows[] = new Tablerow($subdomain['subdomain'], $subdomain['assoc'], icon('small/delete', __('Delete subdomain'), url(array('delsd' => $subdomain['subdomain']), 'id')) . icon('small/pencil', __('Edit subdomain'), url(array('editsd' => $subdomain['subdomain']), 'id')));
     }
     if ($_REQUEST['editsd']) {
         $sd = $DB->subdomains->getRow(array('subdomain' => $_REQUEST['editsd']));
         $form = new Form('editSubdomain');
     } else {
         $sd = false;
         $form = new Form('newSubdomain');
     }
     $this->setContent('main', (!empty($tablerows) ? new Table(new Tableheader(__('Subdomain'), __('Associated with..'), __('Actions')), $tablerows) : '') . $form->set($_REQUEST['editsd'] ? new Hidden('editsd', $_REQUEST['editsd']) : null, new input(__('Subdomain'), 'sdname', @$sd['subdomain']), new input(__('Associate with'), 'sdassoc', @$sd['assoc'], false, __('ID or alias to associate with the subdomain'))));
     $Templates->render();
 }
    function viewRevisions($page, $l, $sectionMap = false)
    {
        global $DB, $Controller;
        if (is_numeric($page)) {
            $page = $Controller->{(string) $page}(EDIT);
        }
        $lang = google::languages($l);
        $revisions = array();
        $_REQUEST->setType('rev1', 'numeric', true);
        $_REQUEST->setType('rev2', 'numeric', true);
        //FIXME: Move to CSS
        Head::add('ins {background: lightgreen;}
del {background: pink;}
.revlegend {text-align: right;display:inline;margin: 0 0 0 45px;}
.revlegend ins,.revlegend del {margin: 0 5px;}', 'css-raw');
        $r1 = false;
        $r2 = false;
        $r = $DB->content->get(array('id' => $this->that->ID, 'language' => $l), false, false, 'revision DESC');
        while ($rev = Database::fetchAssoc($r)) {
            $revisions[$rev['section']][$rev['revision']] = strftime('%c', $rev['revision']);
            if ($_REQUEST['rev1'][$rev['section']] === $rev['revision']) {
                $r1[$rev['section']] = $rev;
            }
            if ($_REQUEST['rev2'][$rev['section']] === $rev['revision']) {
                $r2[$rev['section']] = $rev;
            }
        }
        $revArray = array();
        if ($revisions) {
            foreach ($revisions as $sectionName => $sectContent) {
                $revArray[] = new Tab($sectionMap && isset($sectionMap[$sectionName]) ? $sectionMap[$sectionName] : $sectionName, new Li(new Select('View revision', 'rev1[' . $sectionName . ']', $sectContent, $_REQUEST['rev1'][$sectionName], false, __('None')), new Submit('Revert to this', 'revert1[' . $sectionName . ']')), new Li(new Select('Compare to', 'rev2[' . $sectionName . ']', $sectContent, $_REQUEST['rev2'][$sectionName], false, __('None')), new Submit('Revert to this', 'revert2[' . $sectionName . ']')), isset($r1[$sectionName]) ? '<div class="revlegend"><ins>' . strftime('%c', $r1[$sectionName]['revision']) . '</ins>' . (isset($r2[$sectionName]) ? '<del>' . strftime('%c', $r2[$sectionName]['revision']) . '</del></div>' . '<div id="revdiff">' . diff($r2[$sectionName]['content'], $r1[$sectionName]['content']) . '</div>' : '<div id="revdiff">' . strip_tags($r1[$sectionName]['content'], '<p><div>') . '</div>') : null);
            }
            $rForm = new Form('revisionsForm', url(null, array('id', 'edit', 'view', 'lang'), false));
            return '<div class="nav">' . Short::backn() . '</div>' . $rForm->collection(new Hidden('lang', $l), new Tabber('r' . $l, $revArray));
        } else {
            return '<div class="nav">' . Short::backn() . '</div>' . __('There are no saved revisions for this page and language');
        }
    }
    /**
     * Generates an overview over the permissions granted to a given user or group
     * @param integer $id ID of the user or group
     * @return string
     */
    private function overview($id)
    {
        global $Controller, $DB, $USER;
        $a = $Controller->{$id};
        if (is_a($a, 'User') || is_a($a, 'Group')) {
            if ($_REQUEST->valid('pdel')) {
                if ($Controller->{$_REQUEST['pdel']}->mayI(EDIT_PRIVILEGES)) {
                    if ($DB->privileges->delete(array('id' => $_REQUEST['pdel'], 'beneficiary' => $id))) {
                        Flash::create(__('Privilege deleted'), 'warning');
                    }
                }
            } elseif ($_POST['updatePrivileges'] && $_REQUEST['ovp']) {
                $priv = $DB->privileges->asList(array('benefittor' => $id), 'id');
                foreach ($priv as $pid) {
                    if ($o = $Controller->{(string) $pid}(EDIT_PRIVILEGES)) {
                        $privileges = @$_POST['privileges'][$pid];
                        $access = 0;
                        if (isset($privileges['read'])) {
                            $access |= READ;
                        }
                        if (isset($privileges['edit'])) {
                            $access |= EDIT;
                        }
                        if (isset($privileges['ep'])) {
                            $access |= EDIT_PRIVILEGES;
                        }
                        if (isset($privileges['del'])) {
                            $access |= DELETE;
                        }
                        if (isset($privileges['pub'])) {
                            $access |= PUBLISH;
                        }
                        $DB->privileges->update(array('privileges' => $access), array('id' => $pid, 'beneficiary' => $id));
                        Flash::create(__('Privileges updated'));
                    }
                }
            }
            $r = '<div class="nav"><a href="' . url(null, 'id') . '">' . icon('small/arrow_left') . __('Back to overview') . '</a>' . (is_a($a, 'Page') ? '<a href="' . url(array('id' => $a->ID)) . '">' . icon('small/arrow_left') . __('To page') . '</a>' : '') . '</div>';
            $r .= '<form action="' . url(null, array('id', 'view')) . '" method="post">' . '<fieldset><legend>' . __('Permissions for') . ' ' . $a . '</legend><input type="hidden" name="ovp" value="1" />' . '<table cellpadding="0" cellspacing="0" border="0" class="privilegeList">' . '<thead>' . '<tr>' . '<th width="10">' . __('Delete') . '</th>' . '<th width="*">' . __('Resource') . '</th>' . '<th width="20">' . icon('small/eye', __('Read')) . '</th>' . '<th width="20">' . icon('small/page_edit', __('Edit')) . '</th>' . '<th width="20">' . icon('small/thumb_up', __('Publish')) . '</th>' . '<th width="20">' . icon('small/key', __('Edit privileges')) . '</th>' . '<th width="20">' . icon('small/delete', __('Delete')) . '</th>' . '</tr>' . '</thead>' . '<tbody>';
            $m = $DB->privileges->get(array('beneficiary' => $id), 'id,privileges');
            while ($row = Database::fetchAssoc($m)) {
                if ($obj = $Controller->{$row['id']}) {
                    $r .= '		<tr>
                <td><a href="' . url(array('pdel' => $row['id']), array('id', 'edit', 'view')) . '">' . icon('small/delete') . '</a></td>
                <td>' . $obj . '</td>
                <td align="center"><input name="privileges[' . $row['id'] . '][read]" type="Checkbox" class="Checkbox"' . ($m['privileges'] & READ > 0 ? ' checked="checked"' : '') . ' /></td>
                <td align="center"><input name="privileges[' . $row['id'] . '][edit]" type="Checkbox" class="Checkbox"' . ($m['privileges'] & EDIT > 0 ? ' checked="checked"' : '') . ' /></td>
                <td align="center"><input name="privileges[' . $row['id'] . '][pub]" type="Checkbox" class="Checkbox"' . ($m['privileges'] & PUBLISH > 0 ? ' checked="checked"' : '') . ' /></td>
                <td align="center"><input name="privileges[' . $row['id'] . '][ep]" type="Checkbox" class="Checkbox"' . ($m['privileges'] & EDIT_PRIVILEGES > 0 ? ' checked="checked"' : '') . ' /></td>
                <td align="center"><input name="privileges[' . $row['id'] . '][del]" type="Checkbox" class="Checkbox"' . ($m['privileges'] & DELETE > 0 ? ' checked="checked"' : '') . ' /></td>
            </tr>';
                }
            }
            $r .= '
    </tbody>
    <tfoot>
        <tr>
            <td colspan="6"><input type="submit" name="updatePrivileges" value="' . __('Update') . '" /></td>
        </tr>
    </tfoot>
</table></fieldset>';
            $r .= '</form>';
            return $r;
        } else {
            return __('No permission overview available');
        }
    }
Example #7
0
 /**
  * Display the form for managing the comments
  * @param int|object $page Id of the page to manage, or the page itself
  * @param string $l What language to manage
  * @return string
  */
 function edit($page, $l)
 {
     global $DB, $Controller;
     if (is_object($page)) {
         $page = $page->ID;
     }
     $res = $DB->comments->get(array('id' => $page, 'language' => $l), false, false, 'created ASC');
     $c = 0;
     $r = '<ol class="comments">';
     while (false !== ($comment = Database::fetchAssoc($res))) {
         $u = false;
         if (is_numeric($comment['author'])) {
             $u = $Controller->{$comment['author']}(OVERRIDE, 'User');
         }
         $r .= '<li><span class="authsay' . ($comment['authd_by'] == 0 ? ' unauthorized' : '') . '"><div class="tools">' . ($comment['authd_by'] == 0 ? icon('small/tick', 'Approve', url(array('approve' => $comment['cid']), true)) : __('Approved by') . ': ' . $Controller->{$comment['authd_by']} . ' | ') . icon('small/cross', __('Remove'), url(array('remove' => $comment['cid']), true)) . '</div>' . '<span class="author">' . ($u ? $u : $comment['author']) . '</span> ' . __('says') . ': </span>' . $comment['comment'] . '</li>';
         $c++;
     }
     $r .= '</ol>';
     return $c ? $r : '';
 }
Example #8
0
 /**
  * Returns the ID of the user currently logged in. Also handles the logging in/out of the user
  * @return integer
  */
 private function currentUserID()
 {
     global $DB, $CONFIG;
     if (isset($_SESSION['uid']) && $_REQUEST['logout']) {
         $this->logout();
         return NOBODY;
     } elseif ($_POST['username'] && $_POST['password']) {
         $user = $DB->users->get(array('username' => $_POST['username']), false, 1);
         if (Database::numRows($user) == 1) {
             $row = Database::fetchAssoc($user);
             // LDAP-users har password hash satt till 'LDAP'
             if ($row['password'] == 'LDAP') {
                 $ldapconn = ldap_connect($CONFIG->LDAP->bindurl);
                 if ($ldapconn) {
                     // Bind (log in) to LDAP server
                     if (@ldap_bind($ldapconn, $CONFIG->LDAP->binddn, $CONFIG->LDAP->bindpw)) {
                         //echo "LDAP bind successful...<br />\n";
                         $unameattr = $CONFIG->LDAP->unameattr;
                         if (@empty($unameattr)) {
                             $unameattr = 'cn';
                         }
                         $filter = '(' . $unameattr . '=' . $_POST['username'] . ')';
                         $search = ldap_search($ldapconn, $CONFIG->LDAP->basedn, $filter, array('dn'), 0, 1);
                         // The last parameter is to limit search to 1 result returned
                         if ($search) {
                             // Found user
                             $entry = ldap_first_entry($ldapconn, $search);
                             // Get DN from search result
                             $dn = ldap_get_dn($ldapconn, $entry);
                             //echo 'Found ' . $dn . "\n";
                             // Don't unbind.
                             /* http://php.net/manual/en/function.ldap-unbind.php
                              *  kmenard at wpi dot edu
                              * 29-Nov-2001 07:47
                              * ldap_unbind kills the link descriptor.  So, if you want to rebind
                              * as another user, just bind again; don't unbind.
                              * Otherwise, you'll have to open up a new connection.
                              */
                             // Try to bind as the user account
                             // @ to not print a big error message if the user entered the wrong password
                             if (@ldap_bind($ldapconn, $dn, $_POST['password'])) {
                                 regenerateSession(true);
                                 //echo 'Login successful';
                                 $_SESSION['uid'] = $row['id'];
                                 $_SESSION['username'] = $row['username'];
                                 $_SESSION['upwd'] = 'LDAP';
                                 $_SESSION['loggedIn'] = time();
                                 $_SESSION['lastLogin'] = $row['last_active'];
                                 unset($_COOKIE['user_settings::language']);
                                 return $_SESSION['uid'];
                             } else {
                                 //echo 'Login failed';
                                 Flash::create(__('Wrong username or password'), 'warning');
                                 return NOBODY;
                             }
                         }
                     } else {
                         //echo "LDAP bind failed...";
                         return NOBODY;
                     }
                 } else {
                     // This will only happen if the ldap extension is broken
                     // because OpenLDAP-2.x.x doesn't connect until the ldap_bind() call
                     return NOBODY;
                 }
             } elseif ($this->passwordsEqual($_POST['password'], $row['password'])) {
                 regenerateSession(true);
                 $_SESSION['uid'] = $row['id'];
                 $_SESSION['username'] = $row['username'];
                 $_SESSION['upwd'] = pwdEncode($_POST['password'], $row['password']);
                 $_SESSION['loggedIn'] = time();
                 $_SESSION['lastLogin'] = $row['last_active'];
                 return $_SESSION['uid'];
             }
         } else {
             // User not found in solidbase
             // Try to search in ldap database
             $ldapuid = $this->tryImportLDAP($_POST['username'], $_POST['password']);
             if ($ldapuid !== false) {
                 // Successfully imported user
                 return $ldapuid;
             }
         }
         Flash::create(__('Wrong username or password'), 'warning');
         return NOBODY;
     } elseif (isset($_SESSION['uid']) && checkSession()) {
         $user = $DB->users->getRow(array('id' => $_SESSION['uid']), 'id, username, password, last_active');
         if ($user != false && ($CONFIG->security->loginTimeout < 1 || strtotime($user['last_active']) >= time() - 60 * $CONFIG->security->loginTimeout) && isset($_SESSION['upwd']) && $_SESSION['upwd'] == $user['password'] && isset($_SESSION['username']) && $user['username'] == $_SESSION['username']) {
             return $_SESSION['uid'];
         }
         return NOBODY;
     }
     return NOBODY;
 }
Example #9
0
 function listEmails($view = false)
 {
     global $USER, $Controller, $DB;
     if ($view == 'new') {
         $resource = $DB->massmail->get(array('approved' => '0', 'personal' => 'no'), false, false, 'written DESC');
     } elseif ($view == 'personal') {
         $resource = $DB->massmail->get(array('personal' => 'yes'), false, false, 'written DESC');
     } else {
         $resource = $DB->massmail->get(array('approved>' => '0', 'personal' => 'no', 'author' . ($this->mayI(EDIT) ? 'NO_SELECT' : '') => $USER->ID), false, false, 'written DESC');
     }
     $r = '';
     if (mysql_num_rows($resource)) {
         $table = new Table(new Tableheader(__('Author'), __('From'), __('Recipients'), __('Subject')));
         $i = 0;
         while ($email = Database::fetchAssoc($resource)) {
             $recipients = $Controller->get($email['recipients']);
             $recs = array();
             foreach ($recipients as $re) {
                 $recs[] = $re->link();
             }
             $table->append(new Tablerow($Controller->{$email['author']}->link(), $email['from'] ? $Controller->{$email['from']} : __('Default'), join(', ', $recs), '<a href="' . url(array('eedit' => $email['msg_id']), 'id') . '">' . $email['subject'] . '</a>', '<span class="tools">' . icon($email['sent'] ? 'small/eye' : 'small/email_edit', __($email['sent'] ? 'View' : 'Edit'), url(array('eedit' => $email['msg_id']), 'id')) . icon('small/delete', __('Delete'), url(array('edelete' => $email['msg_id']), 'id')) . ($email['sent'] ? icon('large/network-16', __('Sent')) : ($email['approved'] ? icon('small/tick', __('Approved')) : '')) . '</span>'));
         }
         $r .= $table;
         return $r;
     } else {
         return __('Empty');
     }
 }
Example #10
0
$db->openConnection();
$postdata = file_get_contents("php://input");
$jsonHandle = new jsonHandler();
$requestData = $jsonHandle->decode($postdata);
$data = array();
$page = $db->escapeString($requestData->page);
$innerPage = $db->escapeString($requestData->innerPage);
if ($page == "dashboard") {
    $query = $db->query("SELECT * FROM tbl_hashtag");
    /*Overview Page*/
    if ($innerPage == "overview") {
        /*Check whether it contains tha hashtag data or not*/
        if ($db->hasRows($query)) {
            $data['hashtagArray'] = array();
            $i = 0;
            while ($row = $db->fetchAssoc($query)) {
                $hashtagName = $row['hashtagName'];
                /*Total Tweet Count*/
                $totTweetsQuery = $db->query("SELECT COUNT(DISTINCT tweet_id) FROM tweet_tags WHERE tag = '{$hashtagName}'");
                $totalTweets = $db->fetchArray($totTweetsQuery);
                $data['hashtagArray'][$i]['hashtagName'] = $hashtagName;
                $data['hashtagArray'][$i]['tweets'] = array();
                //$tweetQuery = "SELECT * FROM tweet_tags LEFT JOIN"
                $data['hashtagArray'][$i]['totalTweets'] = $totalTweets[0];
                $data['hashtagArray'][$i]['totalImpressions'] = $i + 2000;
                $data['hashtagArray'][$i]['profileVisits'] = 3000;
                $data['hashtagArray'][$i]['totalMentions'] = 2000 - $i;
                $data['hashtagArray'][$i]['totalFollowers'] = 123121;
                $i++;
            }
            $data['destinationPage'] = "overview";
Example #11
0
 function loadDatabaseStructure()
 {
     if ($this->__loaded) {
         return;
     }
     $this->__loaded = true;
     $r = $this->database->query("SHOW COLUMNS FROM " . $this->name);
     while ($res = Database::fetchAssoc($r)) {
         $this->columns[] = $res['Field'];
     }
 }
Example #12
0
 static function get($id_set_type, $date = NULL)
 {
     $id_set_type = intval($id_set_type);
     // retrieve the distinct list of players who have played the asked set type
     $conditions = 'id_set_type = ' . $id_set_type . ($date !== NULL ? " AND creation_datetime < '" . $date . "'" : '');
     $ar_id_players = Database::fetchAll('SELECT DISTINCT id_player FROM (
       (SELECT DISTINCT id_player_1_win AS id_player FROM bad_set WHERE ' . $conditions . ')
       UNION
       (SELECT DISTINCT id_player_2_win AS id_player FROM bad_set WHERE ' . $conditions . ')
       UNION
       (SELECT DISTINCT id_player_1_lose AS id_player FROM bad_set WHERE ' . $conditions . ')
       UNION
       (SELECT DISTINCT id_player_2_lose AS id_player FROM bad_set WHERE ' . $conditions . ')
     ) AS t
     WHERE id_player IS NOT NULL');
     $count_id_players = count($ar_id_players);
     if ($count_id_players == 0) {
         // nobody played a set for the asked set type
         return array();
     }
     $ar_count_players = array();
     foreach ($ar_id_players as $row) {
         $ar_count_players[$row['id_player']] = NULL;
     }
     $count_scores_retrieved = 0;
     $resource = Database::query('SELECT * FROM bad_set WHERE ' . $conditions . ' ORDER BY creation_datetime DESC');
     while ($row = Database::fetchAssoc($resource)) {
         self::addScore($ar_count_players, $count_scores_retrieved, array('id_player' => $row['id_player_1_win'], 'score' => $row['new_score_player_1_win']));
         self::addScore($ar_count_players, $count_scores_retrieved, array('id_player' => $row['id_player_2_win'], 'score' => $row['new_score_player_2_win']));
         self::addScore($ar_count_players, $count_scores_retrieved, array('id_player' => $row['id_player_1_lose'], 'score' => $row['new_score_player_1_lose']));
         self::addScore($ar_count_players, $count_scores_retrieved, array('id_player' => $row['id_player_2_lose'], 'score' => $row['new_score_player_2_lose']));
     }
     // add player data
     $players = ModelPlayer::get();
     $players_indexed_by_id = array();
     foreach ($players as $player) {
         $players_indexed_by_id[$player['id']] = $player;
     }
     foreach ($ar_count_players as &$count_player) {
         $player = $players_indexed_by_id[$count_player['id']];
         $count_player['first_name'] = $player['first_name'];
         $count_player['last_name'] = $player['last_name'];
     }
     unset($count_player);
     // order $ar_count_players by score desc
     uasort($ar_count_players, array('self', 'sortByScoreDesc'));
     // compute ranks & "fair ranks" (same score = same rank)
     $rank = 1;
     $fair_rank = 1;
     $approved_rank = 1;
     $approved_fair_rank = 1;
     $previous_score = NULL;
     $previous_approved_score = NULL;
     foreach ($ar_count_players as &$player) {
         // basic ranking (allows to track ranking evolution)
         if ($previous_score != $player['score']) {
             $fair_rank = $rank;
         }
         $player['rank'] = $rank;
         $player['fair_rank'] = $fair_rank;
         $rank++;
         $previous_score = $player['score'];
         // 'approved' ranking
         if ($player['nb_sets'] >= MIN_SETS_FOR_BEING_RANKED) {
             if ($previous_approved_score != $player['score']) {
                 $approved_fair_rank = $approved_rank;
             }
             $player['approved_rank'] = $approved_fair_rank;
             $approved_rank++;
             $previous_approved_score = $player['score'];
         } else {
             $player['approved_rank'] = NULL;
         }
     }
     unset($player);
     // compute "fair rank diff" (helps to show how players ranking have evolved since previous training session)
     if ($date === NULL) {
         $now = new DateTime();
         $previous_rankings = self::get($id_set_type, $now->sub(new DateInterval(RANKINGS_COMPARISON_TIME_INTERVAL))->format('Y-m-d H:i:s'));
         foreach ($ar_count_players as &$player) {
             $player['fair_rank_diff'] = 0;
             foreach ($previous_rankings as $prev_player) {
                 if ($player['id'] == $prev_player['id']) {
                     $player['fair_rank_diff'] = $prev_player['fair_rank'] - $player['fair_rank'];
                     break;
                 }
             }
         }
         unset($player);
     }
     return $ar_count_players;
 }
Example #13
0
<?php

// Konfiguration:
error_reporting(E_ALL);
$i = 0;
chdir('..');
//FIXME: Korrigera sökväg efter flytt
include './lib/init.php';
$Messages_Resource = $DB->massmail->get(array('approved!' => 0, 'personal' => 'no', 'sent' => 0, '#!send<=' => 'UNIX_TIMESTAMP()'));
while (false !== ($Message = Database::fetchAssoc($Messages_Resource))) {
    try {
        $sent_to = array();
        $Message['message'] = str_replace(array('"?id=', '"/'), '"https://www.ysektionen.se/', $Message['message']);
        if (!is_array($Message['recipients'])) {
            continue;
        }
        foreach ($Message['recipients'] as $RecipientGroup) {
            $RecipientGroup = $Controller->get($RecipientGroup, OVERRIDE, false, false);
            switch (true) {
                case is_a($RecipientGroup, 'Group'):
                    $Recipients = $RecipientGroup->memberUsers(false, true);
                    break;
                case is_a($RecipientGroup, 'Page'):
                    $Recipients = $RecipientGroup->Form->getPosterIDs();
                    break;
                default:
                    continue 2;
            }
            $Recipients = array_unique($Recipients);
            foreach ($Recipients as $Recipient) {
                if (in_array($Recipient, $sent_to)) {
Example #14
0
 static function fetchOne($query)
 {
     $res = Database::query($query);
     return Database::fetchAssoc($res);
 }
Example #15
0
 function viewResult($echo = false, $no_stats = false)
 {
     $_REQUEST->setType('cout', '#^(email|sortedtable)$#');
     global $DB, $Controller, $USER;
     if ($USER->ID == NOBODY) {
         return false;
     }
     if ($_REQUEST['cout']) {
         $this->sendFile($_REQUEST['cout']);
     }
     $_REQUEST->setType('delpost', 'any');
     $myPosts = array();
     $where = array('id' => $this->ID);
     if (!$this->mayI(EDIT)) {
         $myPosts = $DB->formdata->asList(array('id' => $this->ID, 'field_id' => 'poster', 'value' => $USER->ID), 'post_id');
         if (!$this->_Public_Form) {
             if (!$myPosts) {
                 return '';
             }
             $where['post_id'] = $myPosts;
         }
         $no_stats = true;
     }
     if ($_REQUEST['delpost']) {
         if ($this->mayI(EDIT) || in_array($_REQUEST['delpost'], $myPosts)) {
             $DB->formdata->delete(array('id' => $this->ID, 'post_id' => $_REQUEST['delpost']), false);
             if (!is_null($this->_PostCount)) {
                 --$this->_PostCount;
             }
         }
     }
     $sort = array();
     $r = $DB->formfields->get(array('id' => $this->ID), false, false, 'sort');
     while (false !== ($field = Database::fetchAssoc($r))) {
         $sort[$field['field_id']] = $field['sort'];
         $fields[$field['field_id']] = $field;
         $labels[$field['field_id']] = self::fieldlabel($field['label'], $this->loadedLanguage);
     }
     asort($sort);
     $sort = array_flip(array_keys($sort));
     $r = $DB->formdata->get($where);
     $data = array();
     $postSort = array();
     $u = 0;
     $stats = array();
     while (false !== ($res = Database::fetchAssoc($r))) {
         if (in_array($res['field_id'], array('poster', 'posted', 'poster:ip', 'language'))) {
             $postMeta[$res['post_id']][$res['field_id']] = $res['value'];
             if ($res['field_id'] == 'posted') {
                 $postSort[$res['value']] = $res['post_id'];
             }
         } else {
             if ($this->_Public_Form < 2 && !$this->mayI(EDIT) && !in_array($res['post_id'], $myPosts)) {
                 continue;
             }
             if (@in_array($fields[$res['field_id']]['type'], array('Checkbox', 'pCheckbox')) && substr_count($fields[$res['field_id']]['value'], ',') == 0) {
                 if ($res['value']) {
                     $res['value'] = __('Yes');
                 } else {
                     $res['value'] = __('No');
                 }
             }
             if (!$no_stats) {
                 if (@(!in_array($fields[$res['field_id']]['type'], array('htmlfield', 'textarea', 'hidden', 'mselect')))) {
                     if (isset($stats[$res['field_id']][$res['value']])) {
                         $stats[$res['field_id']][$res['value']]++;
                     } else {
                         $stats[$res['field_id']][$res['value']] = 1;
                     }
                 } elseif ($fields[$res['field_id']]['type'] == 'mselect') {
                     if (!is_array($res['value'])) {
                         $res['value'] = array($res['value']);
                     }
                     foreach ($res['value'] as $sel) {
                         if (isset($stats[$res['field_id']][$sel])) {
                             $stats[$res['field_id']][$sel]++;
                         } else {
                             $stats[$res['field_id']][$sel] = 1;
                         }
                     }
                 }
             }
             $data[$res['post_id']][isset($sort[$res['field_id']]) ? $sort[$res['field_id']] : count($sort) + $u++] = new Tablerow(@$labels[$res['field_id']], $res['value']);
         }
     }
     if (empty($postSort)) {
         return '';
     }
     $sortData = array();
     ksort($postSort);
     foreach ($postSort as $post_id) {
         if (isset($data[$post_id])) {
             ksort($data[$post_id]);
             $sortedData[$post_id] = $data[$post_id];
         } else {
             $sortedData[$post_id] = null;
         }
     }
     $oa = array();
     foreach ($sortedData as $post_id => $rows) {
         $tbl = new Table(new Tableheader(__('Posted by') . ': ' . @$Controller->{$postMeta[$post_id]['poster']}, $this->mayI(EDIT) || in_array($post_id, $myPosts) ? icon('small/delete', __('Delete post'), url(array('delpost' => $post_id), true)) : ''), $rows);
         $tbl->class = 'form_posterdata';
         $oa[] = $tbl;
     }
     $output = listify($oa);
     $_REQUEST->setType('to', 'numeric');
     if ($this->mayI(EDIT)) {
         $output .= '<span class="forminfo">' . $this->PostCount . ' ' . __('posters') . ($this->_Limit ? ' (of ' . $this->_Limit . ')' : '') . '</span>' . '<span class="uform_posterdata"><a href="' . url(array('cout' => 'email'), 'id') . '">' . __('Contact data') . '</a>|<a href="' . url(array('cout' => 'sortedtable'), 'id') . '">' . __('Sorted table') . '</a>' . ($Controller->mailer ? '|<a href="' . url(array('id' => 'mailer', 'to' => $this->ID)) . '">' . __('Email posters') . '</a>' : '') . '</span>';
     }
     if (!$no_stats) {
         $s = new Table(new Tableheader(__('Field'), __('Data'), __('Occurrances')));
         $s->class = 'form_stats_table';
         foreach ($stats as $field_id => $values) {
             $st_rows = array();
             $i = 0;
             foreach ($values as $value => $count) {
                 $st_rows[] = new Tablerow(!$i++ ? @$labels[$field_id] : '', $value, $count);
             }
             $s->append($st_rows);
         }
         $output .= $s;
     }
     if ($echo) {
         echo $output;
     }
     return $output;
 }
Example #16
0
 /**
  * Returns at most $nr of objects
  * @param array|resource $source Array or MySQL resource with an 'id' field
  * @param integer $nr Maximum number of returned
  * @param integer $aLevel The accesslevel which all objects will be tried against.
  * @param User $u The user which the accesslevel will be tried for
  * @return object First object to match permissions
  * @return array Array of objects
  */
 function max($source, $nr, $aLevel = ANYTHING, $u = false, $keep = true)
 {
     $result = array();
     for ($i = 0; $i < $nr;) {
         if (is_resource($source)) {
             $currentID = Database::fetchAssoc($source);
             if ($currentID === false || !isset($currentID['id'])) {
                 return $result;
             }
             $currentID = $currentID['id'];
         } elseif (is_array($source)) {
             $currentID = next($source);
             if ($currentID === false) {
                 return $result;
             }
         } else {
             return false;
         }
         if ($current = $this->retrieve($currentID, $aLevel, $u, $keep)) {
             $result[$currentID] = $current;
             $i++;
         }
     }
     return $result;
 }
 /**
  * Display a given booking
  * @param $booking Booking id
  * @return string Page content
  */
 function viewBooking($booking)
 {
     global $DB, $Controller, $USER;
     $res = $DB->booking_bookings->get(array('b_id' => $booking));
     $booking = false;
     $booked_items = array();
     $nr = 0;
     while (false !== ($r = Database::fetchAssoc($res))) {
         $booking = $r;
         $nr++;
         if ($Controller->{$r['id']}) {
             $booked_items[] = array('obj' => $Controller->{$r['id']}, 'id' => $r['id'], 'parent' => $Controller->{$r['id']}->parentBookID());
         }
     }
     if (!$booking) {
         return __('An error occured. Cannot find booking');
     }
     $nav = '<div class="nav">';
     $nav .= ($_REQUEST['js'] ? '<a href="javascript:window.close();">' . icon('small/cancel') . __('Close') . '</a>' : '<a href="' . url(null, array('viewDate', 'id')) . '">' . icon('small/arrow_left') . __('Back') . '</a>') . ($this->mayI(EDIT) || $booking['booked_by'] == $USER->ID || $booking['booked_for'] && $Controller->{$booking['booked_for']}('Group') && $Controller->{$booking['booked_for']}->isMember($USER) ? '<a href="' . url(array('delbooking' => $booking['b_id']), array('viewDate', 'id', 'js')) . '">' . icon('small/delete') . __('Delete booking') . '</a>' . ($nr > 1 ? '<a href="' . url(array('rembooking' => $booking['b_id']), array('viewDate', 'id', 'js')) . '">' . icon('small/cross') . __('Remove from booking') . '</a>' : '') : '') . (!$booking['cleared_by'] && $this->mayI(EDIT) ? '<a href="' . url(array('confirm' => $booking['b_id']), true) . '">' . icon('small/tick') . __('Confirm') . '</a>' : '');
     $nav .= '</div>';
     return $nav . new Set($booked_items ? new FormText(__('What'), listify(inflate($booked_items), false, true, 'obj', 'children')) : null, $Controller->{$booking['booked_by']} ? new FormText(__('Booked by'), $Controller->{$booking['booked_by']}) : null, $booking['booked_for'] && $Controller->{$booking['booked_for']} ? new FormText(__('Booked for'), $Controller->{$booking['booked_for']}) : null, new FormText(__('Booked from'), date('Y-m-d, H:i', $booking['starttime'])), new FormText(__('Booked until'), date('Y-m-d, H:i', $booking['starttime'] + $booking['duration'])), $booking['comment'] ? new FormText(__('Comment'), $booking['comment']) : null);
 }
 /**
  * Display all options
  * @return void
  */
 function viewAll()
 {
     global $DB, $USER;
     $r = $DB->config->get(array('type!' => 'not_editable'), false, false, 'section,property');
     $form = new Form();
     $e = $this->may($USER, EDIT);
     $lastSectionName = false;
     $lastSection = false;
     $sections = array();
     while ($c = Database::fetchAssoc($r)) {
         if ($lastSectionName != $c['section']) {
             $lastSectionName = $c['section'];
             if ($lastSection != false && $lastSection->count() == 0) {
                 array_pop($sections);
             }
             $sections[] = $lastSection = new Fieldset(ucwords(str_replace('_', ' ', $c['section'])));
         }
         $mult = false;
         $a = false;
         switch ($c['type']) {
             case 'CSV':
                 if (is_array($c['value'])) {
                     $c['value'] = @join(',', $c['value']);
                 }
             case 'text':
                 if ($e) {
                     $a = new Input(ucwords(__(str_replace('_', ' ', $c['property']))), 'conf[' . $c['section'] . '][' . $c['property'] . ']', $c['value'], null, __($c['description']));
                 } else {
                     $a = '<span class="property">' . ucwords(__(str_replace('_', ' ', $c['property']))) . ':</span> <span class="value">' . $c['value'] . '</span><span class="description">' . __($c['description']) . '</span>';
                 }
                 break;
             case 'password':
                 if ($e) {
                     $a = new Password(ucwords(__(str_replace('_', ' ', $c['property']))), 'conf[' . $c['section'] . '][' . $c['property'] . ']', '********', null, __($c['description']));
                 } else {
                     $a = '<span class="property">' . ucwords(__(str_replace('_', ' ', $c['property']))) . ':</span> <span class="value">********</span><span class="description">' . __($c['description']) . '</span>';
                 }
                 break;
             case 'set':
                 $mult = true;
             case 'select':
                 if (is_array($c['set'])) {
                     if ($e) {
                         $a = new Select(ucwords(__(str_replace('_', ' ', $c['property']))), 'conf[' . $c['section'] . '][' . $c['property'] . ']', array_map('__', $c['set']), $c['value'], $mult, false, false, __($c['description']));
                     } else {
                         $a = '<span class="property">' . ucwords(__(str_replace('_', ' ', $c['property']))) . ':</span> <span class="value">' . @$c['set'][$c['value']] . '</span><span class="description">' . __($c['description']) . '</span>';
                     }
                 }
                 break;
             case 'check':
                 if ($e) {
                     $a = new Checkbox(ucwords(__(str_replace('_', ' ', $c['property']))), 'conf[' . $c['section'] . '][' . $c['property'] . ']', $c['value'], $c['value'], false, __($c['description']));
                 } else {
                     $a = '<span class="property">' . ucwords(__(str_replace('_', ' ', $c['property']))) . ':</span> <span class="value">' . $c['value'] . '</span><span class="description">' . __($c['description']) . '</span>';
                 }
                 break;
         }
         if ($a) {
             $lastSection->add($a);
         }
     }
     if ($lastSection != false && $lastSection->count() == 0) {
         array_pop($sections);
     }
     if ($e) {
         return $form->collection($sections);
     } else {
         return join('', $sections);
     }
 }
Example #19
0
 /**
  * Load the object's associated aliases from the database
  * @param $reload Force reload from database
  * @return void
  */
 function loadAliases($reload = false)
 {
     if (!$this->ID) {
         return false;
     }
     global $DB;
     if (!$reload && isset(self::$ALIASES[$this->ID])) {
         return;
     }
     global $Controller;
     $cloaded = $Controller->loadedIds(true);
     $load = array_diff($cloaded, self::$ALOADED);
     if ($reload) {
         $load += array($this->ID);
     }
     if ($load) {
         self::$ALOADED = array_merge($cloaded, $load);
         $r = $DB->aliases->get(array('id' => $load), 'id,alias');
         while (false !== ($row = Database::fetchAssoc($r))) {
             self::$ALIASES[$row['id']][$row['alias']] = $row['alias'];
         }
     }
 }
Example #20
0
 /**
  * This function returns the ID's of all menuitems on the same level, i.e. ignoring MenuSections in the hierarchy
  * @param int $id ID of the parent
  * @return array
  */
 private function singleVirtualDepth($id)
 {
     global $DB;
     $IDS = array();
     $r = $DB->{'menu,spine'}->get(array('menu.parent' => $id), 'spine.id,spine.class', false, 'place');
     while ($row = Database::fetchAssoc($r)) {
         if ($row['class'] == 'MenuSection') {
             $IDS = array_merge($IDS, $this->singleVirtualDepth($row['id']));
         } else {
             $IDS[] = $row['id'];
         }
     }
     return $IDS;
 }