/**
  * @param $uid
  * @param $parentUid
  */
 function validateParentUid($uid, $parentUid)
 {
     # Always validate for new forums.
     if ($uid == -1) {
         return;
     }
     $res = $this->databaseHandle->exec_SELECTquery('*', 'tx_mmforum_forums', 'parentID=' . intval($uid) . ' AND deleted=0 ' . $this->parent->getStoragePIDQuery());
     if ($this->databaseHandle->sql_num_rows($res) > 0 && $parentUid != 0) {
         $this->addErrorForField('parent', 'no-nested-forums', array($this->databaseHandle->sql_num_rows($res)));
     }
 }
Esempio n. 2
0
 function loadFromDB($pid = -1)
 {
     $andWhere = '';
     if ($pid + 1) {
         $andWhere = ' AND pid=' . $pid;
     }
     $res = $this->databaseHandle->exec_SELECTquery('*', $this->getTableName(), 'uid=' . $this->getUid() . ' AND deleted=0 ' . $andWhere);
     if ($this->databaseHandle->sql_num_rows($res) == 0) {
         $this->data = null;
         $this->origData = array();
     } else {
         $this->data = $this->origData = $this->databaseHandle->sql_fetch_assoc($res);
     }
     $this->loaded = true;
 }
 /**
  * Migrate dam references to fal references
  *
  * @param \mysqli_result $result
  * @param string $table
  * @param string $type
  * @param array $fieldnameMapping Re-map fieldnames e.g.
  *    tx_damnews_dam_images => tx_falttnews_fal_images
  *
  * @return void
  */
 protected function migrateDamReferencesToFalReferences($result, $table, $type, $fieldnameMapping = array())
 {
     $counter = 0;
     $total = $this->database->sql_num_rows($result);
     $this->controller->infoMessage('Found ' . $total . ' ' . $table . ' records with a dam ' . $type);
     while ($record = $this->database->sql_fetch_assoc($result)) {
         $identifier = $this->getFullFileName($record);
         try {
             $fileObject = $this->storageObject->getFile($identifier);
         } catch (\Exception $e) {
             // If file is not found
             // getFile will throw an invalidArgumentException if the file
             // does not exist. Create an empty file to avoid this. This is
             // usefull in a development environment that has the production
             // database but not all the physical files.
             try {
                 GeneralUtility::mkdir_deep(PATH_site . $this->storageBasePath . dirname($identifier));
             } catch (\Exception $e) {
                 $this->controller->errorMessage('Unable to create directory: ' . PATH_site . $this->storageBasePath . $identifier);
                 continue;
             }
             $config = $this->controller->getConfiguration();
             if (isset($config['createMissingFiles']) && (int) $config['createMissingFiles']) {
                 $this->controller->infoMessage('Creating empty missing file: ' . PATH_site . $this->storageBasePath . $identifier);
                 try {
                     GeneralUtility::writeFile(PATH_site . $this->storageBasePath . $identifier, '');
                 } catch (\Exception $e) {
                     $this->controller->errorMessage('Unable to create file: ' . PATH_site . $this->storageBasePath . $identifier);
                     continue;
                 }
             } else {
                 $this->controller->errorMessage('File not found: ' . PATH_site . $this->storageBasePath . $identifier);
                 continue;
             }
             $fileObject = $this->storageObject->getFile($identifier);
         }
         if ($fileObject instanceof \TYPO3\CMS\Core\Resource\File) {
             if ($fileObject->isMissing()) {
                 $this->controller->warningMessage('FAL did not find any file resource for DAM record. DAM uid: ' . $record['uid'] . ': "' . $identifier . '"');
                 continue;
             }
             $record['uid_local'] = $fileObject->getUid();
             foreach ($fieldnameMapping as $old => $new) {
                 if ($record['ident'] === $old) {
                     $record['ident'] = $new;
                 }
             }
             $progress = number_format(100 * ($counter++ / $total), 1) . '% of ' . $total;
             if (!$this->doesFileReferenceExist($record)) {
                 $insertData = array('tstamp' => time(), 'crdate' => time(), 'cruser_id' => $GLOBALS['BE_USER']->user['uid'], 'uid_local' => $record['uid_local'], 'uid_foreign' => (int) $record['uid_foreign'], 'sorting' => (int) $record['sorting'], 'sorting_foreign' => (int) $record['sorting_foreign'], 'tablenames' => (string) $record['tablenames'], 'fieldname' => (string) $record['ident'], 'table_local' => 'sys_file', 'pid' => $record['item_pid'], 'l10n_diffsource' => (string) $record['l18n_diffsource']);
                 $this->database->exec_INSERTquery('sys_file_reference', $insertData);
                 $this->amountOfMigratedRecords++;
                 $this->controller->message($progress . ' Migrating relation for ' . (string) $record['tablenames'] . ' uid: ' . $record['item_uid'] . ' dam uid: ' . $record['dam_uid'] . ' to fal uid: ' . $record['uid_local']);
             } else {
                 $this->controller->message($progress . ' Reference already exists for uid: ' . (int) $record['item_uid']);
             }
         }
     }
     $this->database->sql_free_result($result);
 }
Esempio n. 4
0
 /**
  * @test
  */
 public function importingExtension()
 {
     $this->importExtensions(array('extbase'));
     /** @var mysqli_result|resource $res */
     $res = $this->db->sql_query('show tables');
     $rows = $this->db->sql_num_rows($res);
     self::assertNotSame(0, $rows);
 }
 /**
  * Determines the user's rank by his/her post count.
  *
  * @author  Martin Helmich <*****@*****.**>
  * @version 2007-06-06
  * @param   int   $post_count The user's post count.
  * @return  array             The regarding user rank as associative array.
  */
 function getRankByPostCount($post_count)
 {
     $res = $this->databaseHandle->exec_SELECTquery('*', 'tx_mmforum_ranks', 'minPosts <= ' . $post_count . ' AND deleted=0 AND hidden=0 AND special=0', '', 'minPosts DESC');
     if ($this->databaseHandle->sql_num_rows($res) == 0) {
         return 'error';
     } else {
         return $this->databaseHandle->sql_fetch_assoc($res);
     }
 }
 /**
  *
  * Retrievs a topic's forum UID.
  *
  * @author  Martin Helmich <*****@*****.**>
  * @version 2007-07-21
  * @param   int $topic_uid The topic's UID
  * @return  int            The forum's UID
  */
 function getForumUIDByTopic($topic_uid)
 {
     $topic_uid = intval($topic_uid);
     $res = $this->databaseHandle->exec_SELECTquery('forum_id', 'tx_mmforum_topics', 'uid=' . $topic_uid . ' AND deleted=0');
     if ($this->databaseHandle->sql_num_rows($res) > 0) {
         list($forum_uid) = $this->databaseHandle->sql_fetch_row($res);
         return $forum_uid;
     } else {
         return false;
     }
 }
    /**
     *
     * Moves a forum downwards.
     *
     * @access private
     * @param  Integer $forumUid The UID of the forum that is to be moved.
     * @return void|bool
     */
    function moveForumDown($forumUid)
    {
        $forumData = $this->p->getBoardData($forumUid);
        if (!$this->checkActionAllowance($forumData['parentID'] == 0 ? 'category' : 'forum', 'order')) {
            $this->flashmessage = $this->l('access-error');
            return FALSE;
        }
        $res = $this->databaseHandle->exec_SELECTquery('uid, sorting', 'tx_mmforum_forums', 'deleted=0 AND parentID=' . $forumData['parentID'] . '
					                            AND sorting > ' . $forumData['sorting'], '', 'sorting ASC', 1);
        if ($this->databaseHandle->sql_num_rows($res) == 0) {
            return;
        }
        list($lowerUid, $lowerSorting) = $this->databaseHandle->sql_fetch_row($res);
        $this->databaseHandle->exec_UPDATEquery('tx_mmforum_forums', 'uid=' . $forumData['uid'], array('sorting' => $lowerSorting, 'tstamp' => $GLOBALS['EXEC_TIME']));
        $this->databaseHandle->exec_UPDATEquery('tx_mmforum_forums', 'uid=' . $lowerUid, array('sorting' => $forumData['sorting'], 'tstamp' => $GLOBALS['EXEC_TIME']));
    }
 /**
  * Converts CHC Forum groups into ordinary fe_groups.
  * This function converts a list of CHC forum groups into a list of the
  * fe_groups contained in this forum group. This is necessary since the
  * mm_forum extension - unlike the CHC Forum - works with the fe_groups
  * table directly.
  * There will be a slight data loss regarding specific users that are
  * members of a CHC group. These users will not be included in the result,
  * since in the mm_forum access rights are handled using fe_groups ONLY.
  *
  * @author  Martin Helmich <*****@*****.**>
  * @version 2007-10-08
  * @param   string $groups A commaseperated list of CHC forum group UIDs.
  * @return  string         The UIDs of the fe_groups contained in the CHC
  *                         forum groups submitted as parameter as commaseperated
  *                         list.
  */
 function convertGroups($groups)
 {
     $groupArray = GeneralUtility::intExplode(',', $groups);
     $resultFeGroups = array();
     foreach ($groupArray as $group) {
         $res = $this->dbObj->exec_SELECTquery('forumgroup_groups', 'tx_chcforum_forumgroup', 'uid=' . $group . ' AND deleted=0');
         if (!$res || !$this->dbObj->sql_num_rows($res)) {
             continue;
         }
         list($feGroups) = $GLOBALS['TYPO3_DB']->sql_fetch_row($res);
         $feGroupArray = GeneralUtility::intExplode(',', $feGroups);
         foreach ($feGroupArray as $feGroup) {
             $resultFeGroups[] = $feGroup;
         }
     }
     return implode(',', $resultFeGroups);
 }
 /**
  * Adds a topic to a (logged in) user's list of email subscriptions.
  *
  * @param  \tx_mmforum_base $forumObj The plugin object
  * @param  string $topicId The topic identifier
  * @param $feUserId
  * @return bool             Whether it worked or not
  */
 function addSubscription(\tx_mmforum_base $forumObj, $topicId, $feUserId)
 {
     $feUserId = intval($feUserId);
     $topicId = intval($topicId);
     if ($feUserId && $topicId) {
         // Executing database operations
         $res = $this->databaseHandle->exec_SELECTquery('uid', 'tx_mmforum_topicmail', 'user_id = ' . $feUserId . ' AND topic_id = ' . $topicId . $forumObj->getStoragePIDQuery());
         if ($this->databaseHandle->sql_num_rows($res) < 1) {
             $insertData = array('pid' => $forumObj->getStoragePID(), 'tstamp' => $GLOBALS['EXEC_TIME'], 'crdate' => $GLOBALS['EXEC_TIME'], 'topic_id' => $topicId, 'user_id' => $feUserId);
             return $this->databaseHandle->exec_INSERTquery('tx_mmforum_topicmail', $insertData);
         } else {
             // it's already added, so "it worked"
             return true;
         }
     }
     // invalid parameters
     return false;
 }
 /**
  * Inserts a new word into the search index table and returns it's UID.
  * If the word already exists in the search index, just the UID is returned.
  * @param string $word The word to be inserted
  * @return int         The word's UID
  */
 function wordAdd($word)
 {
     // Attempt to load word from database
     $res = $this->databaseHandle->exec_SELECTquery('uid', 'tx_mmforum_wordlist', "word=" . $this->databaseHandle->fullQuoteStr($word, 'tx_mmforum_wordlist') . " " . $this->getPidQuery($this->conf));
     if (!$res) {
         echo $this->databaseHandle->sql_error() . '<hr>';
     }
     // If words already exists, just return the UID
     if ($this->databaseHandle->sql_num_rows($res) > 0) {
         list($uid) = $this->databaseHandle->sql_fetch_row($res);
     } else {
         // Compost insert query
         $insertArray = array('pid' => $this->getFirstPid($this->conf), 'word' => $word, 'metaphone' => metaphone($word));
         // Execute insert query
         $this->databaseHandle->exec_INSERTquery('tx_mmforum_wordlist', $insertArray);
         $uid = $this->databaseHandle->sql_insert_id();
     }
     return $uid;
 }
 function get($data)
 {
     if (is_int($data)) {
         /* Load record from database */
         $res = $this->databaseHandle->exec_SELECTquery('*', 'tx_mmforum_userfields', 'uid=' . intval($data));
         if ($this->databaseHandle->sql_num_rows($res) == 0) {
             return null;
         }
         $arr = $this->databaseHandle->sql_fetch_assoc($res);
     } else {
         $arr = $data;
     }
     /* Unserialize array with meta information */
     $arr['meta'] = unserialize($arr['meta']);
     /* Parse configuration TypoScript */
     $parser =& $this->userLib->getTSParser();
     $parser->setup = array();
     $parser->parse($arr['config']);
     $arr['config_parsed'] = $parser->setup;
     /* Do some corrections for backwards compatibility */
     if (!$arr['meta']['label']['default']) {
         $arr['meta']['label']['default'] = $arr['label'];
     }
     if (!$arr['meta']['type']) {
         $arr['meta']['type'] = 'custom';
     }
     if (!$arr['meta']['link'] && $arr['config_parsed']['datasource']) {
         $arr['meta']['link'] = $arr['config_parsed']['datasource'];
     }
     if (!isset($arr['meta']['required']) && isset($arr['config_parsed']['required'])) {
         $arr['meta']['required'] = $arr['config_parsed']['required'] ? true : false;
     }
     if (!$arr['meta']['text']['validate']) {
         $arr['meta']['text']['validate'] = 'none';
     }
     if (!$arr['meta']['text']['length']) {
         $arr['meta']['text']['length'] = '-1';
     }
     $this->data = $arr;
     $this->meta =& $arr['meta'];
     $this->conf =& $arr['config_parsed'];
 }
 /**
  * Loads the record of an user field.
  * This function load the entire record of a custom user field. The
  * field's typoscript configuration is automatically parsed and the
  * array of metadata that is stored in the database is automatically
  * unserialized.
  *
  * @param  mixed $value Some data the record is to be initialized with.
  *                     This may be either the record's UID or the entire
  *                     record itself as array.
  * @return array       The record of the user field.
  *
  * @author  Martin Helmich <*****@*****.**>
  * @version 2009-02-16
  */
 function getUserFieldData($value)
 {
     if (is_array($value)) {
         $data = $value;
     } else {
         if (MathUtility::canBeInterpretedAsInteger($value) || intval($value) != 0) {
             $res = $this->databaseHandle->exec_SELECTquery('*', 'tx_mmforum_userfields', 'uid=' . intval($value));
             if ($this->databaseHandle->sql_num_rows($res) == 0) {
                 return null;
             }
             $data = $this->databaseHandle->sql_fetch_assoc($res);
         }
     }
     /* Parse configuration TypoScript */
     $parser = $this->getTSParser();
     $parser->parse($data['config']);
     $data['config_parsed'] = $parser->setup;
     $parser->setup = array();
     $this->initializeOldMetaArray($data);
     return $data;
 }
Esempio n. 13
0
 /**
  * Returns the number of tuples matching the query.
  *
  * @throws \TYPO3\CMS\Extbase\Persistence\Generic\Storage\Exception\BadConstraintException
  * @return int The number of matching tuples
  */
 public function countResult()
 {
     $parameters = array();
     $statementParts = $this->parseQuery($this->query, $parameters);
     $statementParts = $this->processStatementStructureForRecursiveMMRelation($statementParts);
     // Mmm... check if that is the right way of doing that.
     // Reset $statementParts for valid table return
     reset($statementParts);
     // if limit is set, we need to count the rows "manually" as COUNT(*) ignores LIMIT constraints
     if (!empty($statementParts['limit'])) {
         $statement = $this->buildQuery($statementParts);
         $this->replacePlaceholders($statement, $parameters, current($statementParts['tables']));
         #print $statement; exit(); // @debug
         $result = $this->databaseHandle->sql_query($statement);
         $this->checkSqlErrors($statement);
         $count = $this->databaseHandle->sql_num_rows($result);
     } else {
         $statementParts['fields'] = array('COUNT(*)');
         // having orderings without grouping is not compatible with non-MySQL DBMS
         $statementParts['orderings'] = array();
         if (isset($statementParts['keywords']['distinct'])) {
             unset($statementParts['keywords']['distinct']);
             $distinctField = $this->query->getDistinct() ? $this->query->getDistinct() : 'uid';
             $statementParts['fields'] = array('COUNT(DISTINCT ' . reset($statementParts['tables']) . '.' . $distinctField . ')');
         }
         $statement = $this->buildQuery($statementParts);
         $this->replacePlaceholders($statement, $parameters, current($statementParts['tables']));
         #print $statement; exit(); // @debug
         $result = $this->databaseHandle->sql_query($statement);
         $this->checkSqlErrors($statement);
         $count = 0;
         if ($result) {
             $row = $this->databaseHandle->sql_fetch_assoc($result);
             $count = current($row);
         }
     }
     $this->databaseHandle->sql_free_result($result);
     return (int) $count;
 }
Esempio n. 14
0
 /**
  * Determines if the user that is currently logged in is an moderator.
  *
  * @param int $forum
  * @return boolean  TRUE, if the user that is currently logged in is an moderator.
  */
 function getIsMod($forum = 0)
 {
     if ($GLOBALS['TSFE']->fe_user->user['username'] == '') {
         return false;
     }
     $userId = $this->getUserID();
     $cacheRes = $this->cache->restore("userIsMod_{$userId}_{$forum}");
     if ($cacheRes !== null) {
         return $cacheRes;
     }
     $res = $this->databaseHandle->exec_SELECTquery('c.grouprights_mod as category_auth, f.grouprights_mod as forum_auth', 'tx_mmforum_forums f LEFT JOIN tx_mmforum_forums c ON f.parentID=c.uid', 'f.uid=' . intval($forum) . ' AND f.deleted=0');
     if (!$res || $this->databaseHandle->sql_num_rows($res) == 0) {
         return false;
     }
     list($category_auth, $forum_auth) = $this->databaseHandle->sql_fetch_row($res);
     $category_auth = GeneralUtility::intExplode(',', $category_auth);
     $forum_auth = GeneralUtility::intExplode(',', $forum_auth);
     $auth = array_merge($category_auth, $forum_auth);
     $auth = array_unique($auth);
     $intersect = array_intersect($GLOBALS['TSFE']->fe_user->groupData['uid'], $auth);
     $isMod = count($intersect) > 0;
     $this->cache->store("userIsMod_{$userId}_{$forum}", $isMod);
     return $isMod;
 }
 /**
  * @param string $tableName
  * @return bool
  */
 protected function tableExists($tableName)
 {
     $res = $this->databaseConnection->sql_query(sprintf('SHOW TABLES LIKE \'%s\'', $tableName));
     return (bool) $this->databaseConnection->sql_num_rows($res);
 }
 /**
  * @test
  *
  * @return void
  */
 public function sqlNumRowsReturnsFalse()
 {
     $res = $this->subject->admin_query("SELECT * FROM {$this->testTable} WHERE test='baz'");
     $numRows = $this->subject->sql_num_rows($res);
     $this->assertFalse($numRows);
 }
    /**
     * Displays the form for editing an already existing category.
     *
     * @author  Martin Helmich <*****@*****.**>
     * @version 2008-05-16
     * @return  string The form content
     *
     * @todo    Combine all form creation functions into a single method?
     */
    function display_editCategory()
    {
        if ($this->param['ctg']) {
            if ($this->param['ctg']['save']) {
                $errors = $this->save_editCategory();
            } elseif ($this->param['ctg']['back']) {
                unset($this->param);
                return;
            } elseif ($this->param['ctg']['delete']) {
                $this->delete_category();
                return;
            }
        }
        $res = $this->databaseHandle->exec_SELECTquery('*', 'tx_mmforum_forums', 'uid=' . intval($this->param['cid']) . ' AND deleted=0');
        if ($this->databaseHandle->sql_num_rows($res) == 0) {
            return $this->display_tree();
        } else {
            $ctg = $this->databaseHandle->sql_fetch_assoc($res);
        }
        $orderOptions = $this->getForumOrderField($ctg, 0);
        $input_authRead = $this->getUserGroupAccess_field('[ctg][authRead]', $ctg['grouprights_read']);
        $input_authWrite = $this->getUserGroupAccess_field('[ctg][authWrite]', $ctg['grouprights_write']);
        $input_authMod = $this->getUserGroupAccess_field('[ctg][authMod]', $ctg['grouprights_mod']);
        /*$content = '<fieldset>
          <legend>'.$this->getLL('category.edit').'</legend>
          <table cellspacing="0" cellpadding="2" style="width:100%">*/
        $content = '<table class="mm_forum-list" width="100%" cellpadding="2" cellspacing="0">
	    <tr>
	        <td class="mm_forum-listrow_header" colspan="2" valign="top"><img src="img/forum-edit.png" style="vertical-align: middle; margin-right:8px;" />' . $this->getLL('category.edit') . '</td>
	    </tr>
        <tr>
            <td>' . $this->getLL('category.title') . '</td>
            <td><input type="text" name="tx_mmforum_fadm[ctg][title]" value="' . htmlspecialchars($ctg['forum_name']) . '" style="width:100%;" />' . $errors['title'] . '</td>
        </tr>
        <tr>
            <td>' . $this->getLL('category.hidden') . '</td>
            <td>
                <input type="hidden" name="tx_mmforum_fadm[ctg][hidden]" value="0" />
                <input type="checkbox" name="tx_mmforum_fadm[ctg][hidden]" value="1" ' . ($ctg['hidden'] ? 'checked="checked"' : '') . ' />
            </td>
        </tr>
        <tr>
            <td>' . $this->getLL('category.order') . '</td>
            <td>
                <select name="tx_mmforum_fadm[ctg][order]">' . $orderOptions . '</select>
            </td>
        </tr>
        <tr>
            <td>' . $this->getLL('category.authRead') . '</td>
            <td>
                ' . $input_authRead . '
                ' . $this->getLL('category.readAuth_note') . '<br /><br />
                ' . $this->getLL('category.updateIndex') . '
            </td>
        </tr>
        <tr>
            <td>' . $this->getLL('category.authWrite') . '</td>
            <td>
                ' . $input_authWrite . '
                ' . $this->getLL('category.writeAuth_note') . '
            </td>
        </tr>
        <tr>
            <td>' . $this->getLL('category.authMod') . '</td>
            <td>
                ' . $input_authMod . '
                ' . $this->getLL('category.modAuth_note') . '
            </td>
        </tr>
    </table>
    <div style="float:right;">' . $this->p->getItemFromRecord('tx_mmforum_forums', $ctg) . '</div>
    <input type="hidden" value="' . $ctg['uid'] . '" name="tx_mmforum_fadm[cid]" />
    <input type="hidden" value="' . $ctg['parentID'] . '" name="tx_mmforum_fadm[ctg][parentID]" />
    <input type="submit" value="' . $this->getLL('save') . '" name="tx_mmforum_fadm[ctg][save]" />
    <input type="submit" value="' . $this->getLL('back') . '" name="tx_mmforum_fadm[ctg][back]" />
    <input type="submit" value="' . $this->getLL('delete') . '" name="tx_mmforum_fadm[ctg][delete]" onclick="return confirm(\'' . $this->getLL('category.confirmDelete') . '\');" />
</fieldset>
';
        return $content;
    }
 /**
  * Loads a cache variable from database.
  *
  * @author  Martin Helmich <*****@*****.**>
  * @version 2008-06-22
  * @param   string $key The key of the cache variable.
  * @return  mixed       The cache variable. Since the cache value is
  *                      stored in serialized form, this value can be of
  *                      any type. If the value was not found in the
  *                      cache table, this function will return NULL.
  */
 function getCacheValue($key)
 {
     $res = $this->databaseHandle->exec_SELECTquery('cache_value', 'tx_mmforum_cache', 'cache_key=' . $this->databaseHandle->fullQuoteStr($key, 'tx_mmforum_cache'));
     if ($this->databaseHandle->sql_num_rows($res)) {
         list($value) = $this->databaseHandle->sql_fetch_row($res);
         return unserialize($value);
     }
     return null;
 }
Esempio n. 19
0
 /**
  * Return record count
  *
  * @return integer
  */
 public function count()
 {
     return $this->connection->sql_num_rows($this->resource);
 }
Esempio n. 20
0
 /**
  * Returning sorting number for tables with a "sortby" column
  * Using when new records are created and existing records are moved around.
  *
  * @param string $table Table name
  * @param int $uid Uid of record to find sorting number for. May be zero in case of new.
  * @param int $pid Positioning PID, either >=0 (pointing to page in which case we find sorting number for first record in page) or <0 (pointing to record in which case to find next sorting number after this record)
  * @return int|array|bool|NULL Returns integer if PID is >=0, otherwise an array with PID and sorting number. Possibly FALSE in case of error.
  */
 public function getSortNumber($table, $uid, $pid)
 {
     if ($GLOBALS['TCA'][$table] && $GLOBALS['TCA'][$table]['ctrl']['sortby']) {
         $sortRow = $GLOBALS['TCA'][$table]['ctrl']['sortby'];
         // Sorting number is in the top
         if ($pid >= 0) {
             // Fetches the first record under this pid
             $res = $this->databaseConnection->exec_SELECTquery($sortRow . ',pid,uid', $table, 'pid=' . (int) $pid . $this->deleteClause($table), '', $sortRow . ' ASC', '1');
             // There was an element
             if ($row = $this->databaseConnection->sql_fetch_assoc($res)) {
                 // The top record was the record it self, so we return its current sortnumber
                 if ($row['uid'] == $uid) {
                     return $row[$sortRow];
                 }
                 // If the pages sortingnumber < 1 we must resort the records under this pid
                 if ($row[$sortRow] < 1) {
                     $this->resorting($table, $pid, $sortRow, 0);
                     // First sorting number after resorting
                     return $this->sortIntervals;
                 } else {
                     // Sorting number between current top element and zero
                     return floor($row[$sortRow] / 2);
                 }
             } else {
                 // No pages, so we choose the default value as sorting-number
                 // First sorting number if no elements.
                 return $this->sortIntervals;
             }
         } else {
             // Sorting number is inside the list
             // Fetches the record which is supposed to be the prev record
             $res = $this->databaseConnection->exec_SELECTquery($sortRow . ',pid,uid', $table, 'uid=' . abs($pid) . $this->deleteClause($table));
             // There was a record
             if ($row = $this->databaseConnection->sql_fetch_assoc($res)) {
                 // Look, if the record UID happens to be an offline record. If so, find its live version. Offline uids will be used when a page is versionized as "branch" so this is when we must correct - otherwise a pid of "-1" and a wrong sort-row number is returned which we don't want.
                 if ($lookForLiveVersion = BackendUtility::getLiveVersionOfRecord($table, $row['uid'], $sortRow . ',pid,uid')) {
                     $row = $lookForLiveVersion;
                 }
                 // Fetch move placeholder, since it might point to a new page in the current workspace
                 if ($movePlaceholder = BackendUtility::getMovePlaceholder($table, $row['uid'], 'uid,pid,' . $sortRow)) {
                     $row = $movePlaceholder;
                 }
                 // If the record should be inserted after itself, keep the current sorting information:
                 if ($row['uid'] == $uid) {
                     $sortNumber = $row[$sortRow];
                 } else {
                     $subres = $this->databaseConnection->exec_SELECTquery($sortRow . ',pid,uid', $table, 'pid=' . (int) $row['pid'] . ' AND ' . $sortRow . '>=' . (int) $row[$sortRow] . $this->deleteClause($table), '', $sortRow . ' ASC', '2');
                     // Fetches the next record in order to calculate the in-between sortNumber
                     // There was a record afterwards
                     if ($this->databaseConnection->sql_num_rows($subres) == 2) {
                         // Forward to the second result...
                         $this->databaseConnection->sql_fetch_assoc($subres);
                         // There was a record afterwards
                         $subrow = $this->databaseConnection->sql_fetch_assoc($subres);
                         // The sortNumber is found in between these values
                         $sortNumber = $row[$sortRow] + floor(($subrow[$sortRow] - $row[$sortRow]) / 2);
                         // The sortNumber happened NOT to be between the two surrounding numbers, so we'll have to resort the list
                         if ($sortNumber <= $row[$sortRow] || $sortNumber >= $subrow[$sortRow]) {
                             // By this special param, resorting reserves and returns the sortnumber after the uid
                             $sortNumber = $this->resorting($table, $row['pid'], $sortRow, $row['uid']);
                         }
                     } else {
                         // If after the last record in the list, we just add the sortInterval to the last sortvalue
                         $sortNumber = $row[$sortRow] + $this->sortIntervals;
                     }
                     $this->databaseConnection->sql_free_result($subres);
                 }
                 return array('pid' => $row['pid'], 'sortNumber' => $sortNumber);
             } else {
                 if ($this->enableLogging) {
                     $propArr = $this->getRecordProperties($table, $uid);
                     // OK, don't insert $propArr['event_pid'] here...
                     $this->log($table, $uid, 4, 0, 1, 'Attempt to move record \'%s\' (%s) to after a non-existing record (uid=%s)', 1, array($propArr['header'], $table . ':' . $uid, abs($pid)), $propArr['pid']);
                 }
                 // There MUST be a page or else this cannot work
                 return false;
             }
         }
     }
     return null;
 }
Esempio n. 21
0
 /**
  * Determines if the user that is currently logged in is allowed to vote in a poll.
  * This function determines if the user that is currently logged in
  * is allowed to participate in a poll. This will not be the case if the
  * poll is already expired, if there is no user logged in or if the user
  * has already participated in this poll.
  *
  * @return boolean TRUE, if the current user may vote, otherwise false.
  */
 function getMayVote()
 {
     if ($this->data['endtime'] > 0 && $this->data['endtime'] < $GLOBALS['EXEC_TIME']) {
         return false;
     }
     if (!$GLOBALS['TSFE']->fe_user->user['uid']) {
         return false;
     }
     $res = $this->databaseHandle->exec_SELECTquery('*', 'tx_mmforum_polls_votes', 'poll_id=' . intval($this->data['uid']) . ' AND user_id=' . $GLOBALS['TSFE']->fe_user->user['uid'] . ' AND deleted=0');
     return $this->databaseHandle->sql_num_rows($res) == 0;
 }
 /**
  * Parses BBCode in a string.
  * This function parses all BBCodes in a string. Most of the BBCodes and
  * their substitution patterns are loaded from database.
  *
  * @author  Björn Detert <*****@*****.**>
  * @author  Martin Helmich <*****@*****.**>
  * @version 2008-12-08
  * @param   string $text   The text to be parsed
  * @param   tx_mmforum_base $parent The calling object (regulary of type tx_mmforum_pi1), so this
  *                         object inherits all configuration and language options from the
  *                         calling object.
  * @param   array  $conf   The calling plugin's configuration vars
  * @return  string         The parsed string
  */
 function bbcode2html($text, $parent, $conf)
 {
     /* Parse special characters */
     $text = $parent->validator->specialChars($text);
     /* SET Buffer markers for Syntax Highlithing Boxes */
     /* ======================== */
     /* getting all activated syntaxhl languages out of the database ... */
     $res = $this->databaseHandle->exec_SELECTquery('lang_title,lang_pattern,lang_code', 'tx_mmforum_syntaxhl', 'deleted=0 AND hidden=0');
     if ($this->databaseHandle->sql_num_rows($res) == 0) {
         $buffer = array();
     } else {
         $buffer = array();
         while ($data = $this->databaseHandle->sql_fetch_assoc($res)) {
             preg_match_all($data['lang_pattern'], $text, $buffer[$data['lang_title']]);
             $text = preg_replace($data['lang_pattern'], '###' . $data['lang_title'] . '_BUFFER_MARKER_MMCMS###', $text);
         }
     }
     $text = $this->links($text, $conf);
     $text = $this->linkgenerator($text, $conf, 'cryptmail', $parent);
     $text = $this->typolinks($text, $parent);
     $res = $this->databaseHandle->exec_SELECTquery('pattern,replacement', 'tx_mmforum_postparser', 'deleted=0');
     if ($this->databaseHandle->sql_num_rows($res) > 0) {
         while ($data = $this->databaseHandle->sql_fetch_assoc($res)) {
             $text = preg_replace($data['pattern'], $data['replacement'], $text);
         }
     }
     /* FILLING the Markers by TYPOScript Vars */
     $text = str_replace('###TARGET###', $conf['postparser.']['bb_code_linktarget'], $text);
     /* Different CSS classes for internal and external links */
     if ($conf['postparser.']['bb_code_parser_differlinkclass'] == 1) {
         $hostname = str_replace('www.', '', $_SERVER['SERVER_NAME']);
         $temptext = '';
         foreach (explode('<a ', $text) as $value) {
             if (strpos($value, 'href=') > -1) {
                 $temptext .= '<a ';
             }
             if (strpos($value, $hostname) === FALSE) {
                 $temptext .= str_replace('###CSS_CLASS###', $conf['postparser.']['bb_code_linkclass'], $value);
             } else {
                 $temptext .= str_replace('###CSS_CLASS###', $conf['postparser.']['bb_code_linkclassinternal'], $value);
             }
         }
         $text = $temptext;
         unset($temptext);
         unset($value);
     } else {
         $text = str_replace('###CSS_CLASS###', $conf['postparser.']['bb_code_linkclass'], $text);
     }
     /* remove unneeded HTML-code */
     $text = str_replace('target=""', '', $text);
     $text = str_replace('class=""', '', $text);
     /* the list bb code */
     $patterns = array("/\\[list\\](.*?)\\[\\/list\\]/isS", "/\\[list:[a-z0-9]{10}\\](.*?)\\[\\/list:[a-z0-9]{10}\\]/isS", "/\\[list=[a-z0-9]{1}:[a-z0-9]{10}\\](.*?)\\[\\/list:[a-z0-9]{1}:[a-z0-9]{10}\\]/isS");
     while (list($k, $v) = each($patterns)) {
         #$text  = preg_replace_callback($v,create_function('$treffer',' return "<ul>".str_replace("[*]","</li><li>",$treffer[1])."</ul>";'),$text);
         $text = preg_replace_callback($v, array('tx_mmforum_postparser', 'processList'), $text);
     }
     $text = str_replace('<li></li>', '', $text);
     while (list($k, $v) = each($buffer)) {
         foreach ($v[0] as $code_item) {
             $text = preg_replace('/###' . $k . '_BUFFER_MARKER_MMCMS###/', "{$code_item}", $text, 1);
         }
     }
     return $text;
 }
Esempio n. 23
0
 /**
  * get the content for a news item NOT displayed as single item (List & Latest)
  *
  * @param	array		$itemparts : parts of the html template
  * @param	array		$selectConf : quety parameters in an array
  * @param	string		$prefix_display : the part of the TS-setup
  * @return	string		$itemsOut: itemlist as htmlcode
  */
 function getListContent($itemparts, $selectConf, $prefix_display)
 {
     if ($this->debugTimes) {
         $this->hObj->getParsetime(__METHOD__);
     }
     $limit = $this->config['limit'];
     $lConf = $this->conf[$prefix_display . '.'];
     $res = $this->exec_getQuery('tt_news', $selectConf);
     //get query for list contents
     //				debug($selectConf, $this->theCode.' final $selectConf (' . __CLASS__ . '::' . __FUNCTION__ . ')', __LINE__, __FILE__, 3);
     // make some final config manipulations
     // overwrite image sizes from TS with the values from content-element if they exist.
     if ($this->config['FFimgH'] || $this->config['FFimgW']) {
         $lConf['image.']['file.']['maxW'] = $this->config['FFimgW'];
         $lConf['image.']['file.']['maxH'] = $this->config['FFimgH'];
     }
     if ($this->config['croppingLenght']) {
         $lConf['subheader_stdWrap.']['crop'] = $this->config['croppingLenght'];
     }
     $this->splitLConf = array();
     $cropSuffix = FALSE;
     if ($this->conf['enableOptionSplit']) {
         if ($this->config['croppingLenghtOptionSplit']) {
             $crop = $lConf['subheader_stdWrap.']['crop'];
             if ($this->config['croppingLenght']) {
                 $crop = $this->config['croppingLenght'];
             }
             $cparts = explode('|', $crop);
             if (is_array($cparts)) {
                 $cropSuffix = '|' . $cparts[1] . ($cparts[2] ? '|' . $cparts[2] : '');
             }
             $lConf['subheader_stdWrap.']['crop'] = $this->config['croppingLenghtOptionSplit'];
         }
         $resCount = $this->db->sql_num_rows($res);
         $this->splitLConf = $this->processOptionSplit($lConf, $limit, $resCount);
     }
     $itemsOut = '';
     $itempartsCount = count($itemparts);
     $pTmp = $this->tsfe->ATagParams;
     $cc = 0;
     $piVarsArray = array('backPid' => $this->conf['dontUseBackPid'] ? null : $this->config['backPid'], 'year' => $this->conf['dontUseBackPid'] ? null : ($this->piVars['year'] ? $this->piVars['year'] : null), 'month' => $this->conf['dontUseBackPid'] ? null : ($this->piVars['month'] ? $this->piVars['month'] : null));
     // needed for external renderer
     $this->listData = array();
     // Getting elements
     while ($row = $this->db->sql_fetch_assoc($res)) {
         // gets the option splitted config for this record
         if ($this->conf['enableOptionSplit'] && !empty($this->splitLConf[$cc])) {
             $lConf = $this->splitLConf[$cc];
             $lConf['subheader_stdWrap.']['crop'] .= $cropSuffix;
         }
         $wrappedSubpartArray = array();
         $titleField = $lConf['linkTitleField'] ? $lConf['linkTitleField'] : '';
         // First get workspace/version overlay:
         if ($this->versioningEnabled) {
             $this->tsfe->sys_page->versionOL('tt_news', $row);
         }
         // Then get localization of record:
         if ($this->tsfe->sys_language_content) {
             // prevent link targets from being changed in localized records
             $tmpPage = $row['page'];
             $tmpExtURL = $row['ext_url'];
             $row = $this->tsfe->sys_page->getRecordOverlay('tt_news', $row, $this->tsfe->sys_language_content, $this->tsfe->sys_language_contentOL, '');
             $row['page'] = $tmpPage;
             $row['ext_url'] = $tmpExtURL;
         }
         // Register displayed news item globally:
         $GLOBALS['T3_VAR']['displayedNews'][] = $row['uid'];
         $this->tsfe->ATagParams = $pTmp . ' title="' . $this->local_cObj->stdWrap(trim(htmlspecialchars($row[$titleField])), $lConf['linkTitleField.']) . '"';
         if ($this->conf[$prefix_display . '.']['catOrderBy']) {
             $this->config['catOrderBy'] = $this->conf[$prefix_display . '.']['catOrderBy'];
         }
         //			if ($this->isRenderMarker('###NEWS_CATEGORY_ROOTLINE###')) {
         $this->categories = array();
         $this->categories[$row['uid']] = $this->getCategories($row['uid']);
         //			}
         $catSPid = FALSE;
         if ($row['type'] == 1 || $row['type'] == 2) {
             // News type article or external url
             $this->local_cObj->setCurrentVal($row['type'] == 1 ? $row['page'] : $row['ext_url']);
             $wrappedSubpartArray['###LINK_ITEM###'] = $this->local_cObj->typolinkWrap($this->conf['pageTypoLink.']);
             // fill the link string in a register to access it from TS
             $this->local_cObj->LOAD_REGISTER(array('newsMoreLink' => $this->local_cObj->typolink($this->pi_getLL('more'), $this->conf['pageTypoLink.'])), '');
         } else {
             //  Overwrite the singlePid from config-array with a singlePid given from the first entry in $this->categories
             if ($this->conf['useSPidFromCategory'] && is_array($this->categories)) {
                 $tmpcats = $this->categories;
                 if (is_array($tmpcats[$row['uid']])) {
                     $catSPid = array_shift($tmpcats[$row['uid']]);
                 }
             }
             $singlePid = $catSPid['single_pid'] ? $catSPid['single_pid'] : $this->config['singlePid'];
             $wrappedSubpartArray['###LINK_ITEM###'] = $this->getSingleViewLink($singlePid, $row, $piVarsArray);
         }
         // reset ATagParams
         $this->tsfe->ATagParams = $pTmp;
         $markerArray = $this->getItemMarkerArray($row, $lConf, $prefix_display);
         // XML
         if ($this->theCode == 'XML') {
             if ($row['type'] == 2) {
                 // external URL
                 $exturl = trim(strpos($row['ext_url'], 'http://') !== FALSE ? $row['ext_url'] : 'http://' . $row['ext_url']);
                 $exturl = strpos($exturl, ' ') ? substr($exturl, 0, strpos($exturl, ' ')) : $exturl;
                 $rssUrl = $exturl;
             } elseif ($row['type'] == 1) {
                 // internal URL
                 $rssUrl = $this->pi_getPageLink($row['page'], '');
                 if (strpos($rssUrl, '://') === FALSE) {
                     $rssUrl = $this->config['siteUrl'] . $rssUrl;
                 }
             } else {
                 // News detail link
                 $link = $this->getSingleViewLink($singlePid, $row, $piVarsArray, true);
                 $rssUrl = trim(strpos($link, '://') === FALSE ? $this->config['siteUrl'] : '') . $link;
             }
             // replace square brackets [] in links with their URLcodes and replace the &-sign with its ASCII code
             $rssUrl = preg_replace(array('/\\[/', '/\\]/', '/&/'), array('%5B', '%5D', '&#38;'), $rssUrl);
             $markerArray['###NEWS_LINK###'] = $rssUrl;
             if ($this->conf['displayXML.']['xmlFormat'] == 'rdf') {
                 $this->rdfToc .= "\t\t\t\t" . '<rdf:li resource="' . $rssUrl . '" />' . "\n";
             }
         }
         $layoutNum = $itempartsCount == 0 ? 0 : $cc % $itempartsCount;
         if (!$this->useUpstreamRenderer) {
             // Store the result of template parsing in the Var $itemsOut, use the alternating layouts
             $itemsOut .= $this->cObj->substituteMarkerArrayCached($itemparts[$layoutNum], $markerArray, array(), $wrappedSubpartArray);
         }
         $this->listData[] = array('row' => $row, 'markerArray' => $markerArray, 'categories' => $this->categories);
         $cc++;
         if ($cc == $limit) {
             break;
         }
     }
     $this->db->sql_free_result($res);
     if ($this->debugTimes) {
         $this->hObj->getParsetime(__METHOD__);
     }
     return $itemsOut;
 }