Ejemplo n.º 1
0
 public function __construct(&$routeInfo, &$matches, &$queryString = '')
 {
     if (isset($matches['params']) and !empty($matches['params'])) {
         $paramString = strpos($matches['params'], '/') === 0 ? substr($matches['params'], 1) : $matches['params'];
         $params = explode('/', $paramString);
         if (count($params) >= 2) {
             $this->pagenum = $params[1];
             $this->folderid = $params[0];
         } else {
             if (!empty($params)) {
                 $this->pagenum = $params[1];
             }
         }
     }
     if (!empty($matches['pagenum']) and intval($matches['pagenum'])) {
         $this->pagenum = $matches['pagenum'];
     }
     if (!empty($matches['folderid']) and intval($matches['folderid'])) {
         $this->folderid = $matches['folderid'];
     }
     $routeInfo['arguments']['subtemplate'] = $this->subtemplate;
     $userid = vB::getCurrentSession()->get('userid');
     $pmquota = vB::getUserContext($userid)->getLimit('pmquota');
     $vboptions = vB::getDatastore($userid)->getValue('options');
     $canUsePmSystem = ($vboptions['enablepms'] and $pmquota);
     if (!$canUsePmSystem and !$this->overrideDisable) {
         throw new vB_Exception_NodePermission('privatemessage');
     }
 }
Ejemplo n.º 2
0
 /**
  * Create a blog channel.
  *
  * @param array $input
  * @param int $channelid
  * @param int $channelConvTemplateid
  * @param int $channelPgTemplateId
  * @param int $ownerSystemGroupId
  *
  * @return int The nodeid of the new blog channel
  */
 public function createChannel($input, $channelid, $channelConvTemplateid, $channelPgTemplateId, $ownerSystemGroupId)
 {
     $input['parentid'] = $channelid;
     $input['inlist'] = 1;
     // we don't want it to be shown in channel list, but we want to move them
     $input['protected'] = 0;
     if (empty($input['userid'])) {
         $input['userid'] = vB::getCurrentSession()->get('userid');
     }
     if (!isset($input['publishdate'])) {
         $input['publishdate'] = vB::getRequest()->getTimeNow();
     }
     $input['templates']['vB5_Route_Channel'] = $channelPgTemplateId;
     $input['templates']['vB5_Route_Conversation'] = $channelConvTemplateid;
     // add channel node
     $channelLib = vB_Library::instance('content_channel');
     $input['page_parentid'] = 0;
     $result = $channelLib->add($input, array('skipFloodCheck' => true, 'skipDupCheck' => true));
     //Make the current user the channel owner.
     $userApi = vB_Api::instanceInternal('user');
     $usergroup = vB::getDbAssertor()->getRow('usergroup', array('systemgroupid' => $ownerSystemGroupId));
     if (empty($usergroup) or !empty($usergroup['errors'])) {
         //This should never happen. It would mean an invalid parameter was passed
         throw new vB_Exception_Api('invalid_request');
     }
     vB_User::setGroupInTopic($input['userid'], $result['nodeid'], $usergroup['usergroupid']);
     vB_Cache::allCacheEvent(array('nodeChg_' . $this->blogChannel, "nodeChg_{$channelid}"));
     vB::getUserContext()->rebuildGroupAccess();
     vB_Channel::rebuildChannelTypes();
     // clear follow cache
     vB_Api::instanceInternal('follow')->clearFollowCache(array($input['userid']));
     return $result['nodeid'];
 }
Ejemplo n.º 3
0
 public function __call($method, $arguments)
 {
     try {
         $logger = vB::getLogger('api.' . $this->controller . '.' . $method);
         //check so that we don't var_export large variables when we don't have to
         if ($logger->isInfoEnabled()) {
             if (!($ip = vB::getRequest()->getAltIp())) {
                 $ip = vB::getRequest()->getIpAddress();
             }
             $message = str_repeat('=', 80) . "\ncalled {$method} on {$this->controller} from ip {$ip} \n\$arguments = " . var_export($arguments, true) . "\n" . str_repeat('=', 80) . "\n";
             $logger->info($message);
             $logger->info("time: " . microtime(true));
         }
         if ($logger->isTraceEnabled()) {
             $message = str_repeat('=', 80) . "\n " . $this->getTrace() . str_repeat('=', 80) . "\n";
             $logger->trace($message);
         }
         $c = $this->api;
         // This is a hack to prevent method parameter reference error. See VBV-5546
         $hackedarguments = array();
         foreach ($arguments as $k => &$arg) {
             $hackedarguments[$k] =& $arg;
         }
         $return = call_user_func_array(array(&$c, $method), $hackedarguments);
         //check so that we don't var_export large variables when we don't have to
         if ($logger->isDebugEnabled()) {
             $message = str_repeat('=', 80) . "\ncalled {$method} on {$this->controller}\n\$return = " . var_export($return, true) . "\n" . str_repeat('=', 80) . "\n";
             $logger->debug($message);
         }
         return $return;
     } catch (vB_Exception_Api $e) {
         $errors = $e->get_errors();
         $config = vB::getConfig();
         if (!empty($config['Misc']['debug'])) {
             $trace = '## ' . $e->getFile() . '(' . $e->getLine() . ") Exception Thrown \n" . $e->getTraceAsString();
             $errors[] = array("exception_trace", $trace);
         }
         return array('errors' => $errors);
     } catch (vB_Exception_Database $e) {
         $config = vB::getConfig();
         if (!empty($config['Misc']['debug']) or vB::getUserContext()->hasAdminPermission('cancontrolpanel')) {
             $errors = array('Error ' . $e->getMessage());
             $trace = '## ' . $e->getFile() . '(' . $e->getLine() . ") Exception Thrown \n" . $e->getTraceAsString();
             $errors[] = array("exception_trace", $trace);
             return array('errors' => $errors);
         } else {
             // This text is purposely hard-coded since we don't have
             // access to the database to get a phrase
             return array('errors' => array(array('There has been a database error, and the current page cannot be displayed. Site staff have been notified.')));
         }
     } catch (Exception $e) {
         $errors = array(array('unexpected_error', $e->getMessage()));
         $config = vB::getConfig();
         if (!empty($config['Misc']['debug'])) {
             $trace = '## ' . $e->getFile() . '(' . $e->getLine() . ") Exception Thrown \n" . $e->getTraceAsString();
             $errors[] = array("exception_trace", $trace);
         }
         return array('errors' => $errors);
     }
 }
Ejemplo n.º 4
0
 /**
  * Create an article category channel. This function works basically like the blog library's version
  *
  * @param array 	$input						data array, should have standard channel data like title, parentid, 
  * @param int 		$channelid					parentid that the new channel should fall under. 
  * @param int		$channelConvTemplateid		"Conversation" level pagetemplate to use. Typically vB_Page::getArticleConversPageTemplate()
  * @param int 		$channelPgTemplateId		"Channel" level pagetemplate to use. Typically  vB_Page::getArticleChannelPageTemplate()
  * @param int 		$ownerSystemGroupId
  *
  * @return int The nodeid of the new blog channel
  */
 public function createChannel($input, $channelid, $channelConvTemplateid, $channelPgTemplateId, $ownerSystemGroupId)
 {
     if (!isset($input['parentid']) or intval($input['parentid']) < 1) {
         $input['parentid'] = $channelid;
     }
     $input['inlist'] = 1;
     // we don't want it to be shown in channel list, but we want to move them
     $input['protected'] = 0;
     if (empty($input['userid'])) {
         $input['userid'] = vB::getCurrentSession()->get('userid');
     }
     if (!isset($input['publishdate'])) {
         $input['publishdate'] = vB::getRequest()->getTimeNow();
     }
     $input['templates']['vB5_Route_Channel'] = $channelPgTemplateId;
     $input['templates']['vB5_Route_Article'] = $channelConvTemplateid;
     $input['childroute'] = 'vB5_Route_Article';
     // add channel node
     $channelLib = vB_Library::instance('content_channel');
     $input['page_parentid'] = 0;
     $result = $channelLib->add($input, array('skipNotifications' => true, 'skipFloodCheck' => true, 'skipDupCheck' => true));
     //Make the current user the channel owner.
     $userApi = vB_Api::instanceInternal('user');
     $usergroup = vB::getDbAssertor()->getRow('usergroup', array('systemgroupid' => $ownerSystemGroupId));
     vB_Cache::allCacheEvent(array('nodeChg_' . $this->articleHomeChannel, "nodeChg_{$channelid}"));
     vB::getUserContext()->rebuildGroupAccess();
     vB_Channel::rebuildChannelTypes();
     // clear follow cache
     vB_Api::instanceInternal('follow')->clearFollowCache(array($input['userid']));
     return $result['nodeid'];
 }
Ejemplo n.º 5
0
 protected function checkRoutePermissions()
 {
     $currentUser = vB::getUserContext();
     if (!$currentUser->hasPermission('genericpermissions', 'canviewmembers') and $this->arguments['userid'] != vB::getCurrentSession()->get('userid')) {
         throw new vB_Exception_NodePermission('profile');
     }
 }
Ejemplo n.º 6
0
 /**
  * Fetches announcements by channel ID
  *
  * @param  int              $channelid (optional) Channel ID
  * @param  int              $announcementid (optional) Announcement ID
  *
  * @throws vB_Exception_Api no_permission if the user doesn't have permission to view the announcements
  *
  * @return array            Announcements, each element is an array containing all the fields
  *                          in the announcement table and username, avatarurl, and the individual
  *                          options from the announcementoptions bitfield-- dohtml, donl2br,
  *                          dobbcode, dobbimagecode, dosmilies.
  */
 public function fetch($channelid = 0, $announcementid = 0)
 {
     $usercontext = vB::getUserContext();
     $userapi = vB_Api::instanceInternal('user');
     $channelapi = vB_Api::instanceInternal('content_channel');
     $parentids = array();
     // Check channel permission
     if ($channelid) {
         // This is to verify $channelid
         $channelapi->fetchChannelById($channelid);
         if (!$usercontext->getChannelPermission('forumpermissions', 'canview', $channelid)) {
             throw new vB_Exception_Api('no_permission');
         }
         $parents = vB_Library::instance('node')->getParents($channelid);
         foreach ($parents as $parent) {
             if ($parent['nodeid'] != 1) {
                 $parentids[] = $parent['nodeid'];
             }
         }
     }
     $data = array(vB_dB_Query::TYPE_KEY => vB_dB_Query::QUERY_SELECT, vB_dB_Query::CONDITIONS_KEY => array(array('field' => 'startdate', 'value' => vB::getRequest()->getTimeNow(), 'operator' => vB_dB_Query::OPERATOR_LTE), array('field' => 'enddate', 'value' => vB::getRequest()->getTimeNow(), 'operator' => vB_dB_Query::OPERATOR_GTE)));
     if ($parentids) {
         $parentids[] = -1;
         // We should always include -1 for global announcements
         $data[vB_dB_Query::CONDITIONS_KEY][] = array('field' => 'nodeid', 'value' => $parentids);
     } elseif ($channelid) {
         $channelid = array($channelid, -1);
         // We should always include -1 for global announcements
         $data[vB_dB_Query::CONDITIONS_KEY][] = array('field' => 'nodeid', 'value' => $channelid);
     } else {
         $data[vB_dB_Query::CONDITIONS_KEY][] = array('field' => 'nodeid', 'value' => '-1');
     }
     $announcements = $this->assertor->getRows('vBForum:announcement', $data, array('field' => array('startdate', 'announcementid'), 'direction' => array(vB_dB_Query::SORT_DESC, vB_dB_Query::SORT_DESC)));
     if (!$announcements) {
         return array();
     } else {
         $results = array();
         $bf_misc_announcementoptions = vB::getDatastore()->getValue('bf_misc_announcementoptions');
         foreach ($announcements as $k => $post) {
             $userinfo = $userapi->fetchUserinfo($post['userid'], array(vB_Api_User::USERINFO_AVATAR, vB_Api_User::USERINFO_SIGNPIC));
             $announcements[$k]['username'] = $userinfo['username'];
             $announcements[$k]['avatarurl'] = $userapi->fetchAvatar($post['userid']);
             $announcements[$k]['dohtml'] = $post['announcementoptions'] & $bf_misc_announcementoptions['allowhtml'];
             if ($announcements[$k]['dohtml']) {
                 $announcements[$k]['donl2br'] = false;
             } else {
                 $announcements[$k]['donl2br'] = true;
             }
             $announcements[$k]['dobbcode'] = $post['announcementoptions'] & $bf_misc_announcementoptions['allowbbcode'];
             $announcements[$k]['dobbimagecode'] = $post['announcementoptions'] & $bf_misc_announcementoptions['allowbbcode'];
             $announcements[$k]['dosmilies'] = $post['announcementoptions'] & $bf_misc_announcementoptions['allowsmilies'];
             if ($announcements[$k]['dobbcode'] and $post['announcementoptions'] & $bf_misc_announcementoptions['parseurl']) {
                 require_once DIR . '/includes/functions_newpost.php';
                 $announcements[$k]['pagetext'] = convert_url_to_bbcode($post['pagetext']);
             }
         }
         return $announcements;
     }
 }
Ejemplo n.º 7
0
 /**
  * Checks if user can delete a given link
  *
  * @param 	int		User Id
  *
  * @param	int		Link Id
  *
  * @return boolean value to indicate whether user can or not delete link
  */
 protected function canDeleteLink($userId, $nodeid, $fileDataRecord)
 {
     /** moderators can delete links */
     if (vB::getUserContext()->getChannelPermission("moderatorpermissions", "canmoderateattachments", $nodeid)) {
         return true;
     }
     return false;
 }
Ejemplo n.º 8
0
 public function call($forumid, $perpage = 20, $pagenumber = 1)
 {
     $contenttype = vB_Api::instance('contenttype')->fetchContentTypeIdFromClass('Channel');
     $forum = vB_Api::instance('node')->getNodeFullContent($forumid);
     if (empty($forum) or isset($forum['errors'])) {
         return array("response" => array("errormessage" => array("invalidid")));
     }
     $forum = $forum[$forumid];
     $modPerms = vB::getUserContext()->getModeratorPerms($forum);
     $foruminfo = array('forumid' => $forum['nodeid'], 'title' => vB_String::unHtmlSpecialChars($forum['title']), 'description' => $forum['description'], 'title_clean' => $forum['htmltitle'], 'description_clean' => strip_tags($forum['description']), 'prefixrequired' => 0);
     $nodes = vB_Api::instance('node')->fetchChannelNodeTree($forumid, 3);
     $channels = array();
     if (!empty($nodes) and empty($nodes['errors']) and isset($nodes['channels']) and !empty($nodes['channels'])) {
         foreach ($nodes['channels'] as $node) {
             $channels[] = vB_Library::instance('vb4_functions')->parseForum($node);
         }
     }
     $forumbits = $channels;
     $topics = array();
     $topics_sticky = array();
     $page_nav = vB_Library::instance('vb4_functions')->pageNav(1, $perpage, 1);
     $search = array("channel" => $forumid);
     $search['view'] = vB_Api_Search::FILTER_VIEW_TOPIC;
     $search['depth'] = 1;
     $search['include_sticky'] = true;
     $search['sort']['lastcontent'] = 'desc';
     $search['nolimit'] = 1;
     $topic_search = vB_Api::instanceInternal('search')->getInitialResults($search, $perpage, $pagenumber, true);
     if (!isset($topic_search['errors']) and !empty($topic_search['results'])) {
         $topic_search['results'] = vB_Api::instance('node')->mergeNodeviewsForTopics($topic_search['results']);
         foreach ($topic_search['results'] as $key => $node) {
             if ($node['content']['contenttypeclass'] == 'Channel' or $node['content']['starter'] != $node['content']['nodeid']) {
                 unset($topic_search['results'][$key]);
             } else {
                 $topic = vB_Library::instance('vb4_functions')->parseThread($node);
                 if ($topic['thread']['sticky']) {
                     $topics_sticky[] = $topic;
                 } else {
                     $topics[] = $topic;
                 }
             }
         }
         $page_nav = vB_Library::instance('vb4_functions')->pageNav($topic_search['pagenumber'], $perpage, $topic_search['totalRecords']);
     }
     $inlinemod = $forum['canmoderate'] ? 1 : 0;
     $subscribed = vB_Api::instance('follow')->isFollowingContent($forum['nodeid']);
     $subscribed = $subscribed ? 1 : 0;
     $forumsearch = vB::getUserContext()->hasPermission('forumpermissions', 'cansearch');
     $response = array();
     $response['response']['forumbits'] = $forumbits;
     $response['response']['foruminfo'] = $foruminfo;
     $response['response']['threadbits'] = $topics;
     $response['response']['threadbits_sticky'] = $topics_sticky;
     $response['response']['pagenav'] = $page_nav;
     $response['response']['pagenumber'] = intval($pagenumber);
     $response['show'] = array('subscribed_to_forum' => $subscribed, 'inlinemod' => $inlinemod, 'spamctrls' => $modPerms['candeleteposts'] > 0 ? 1 : 0, 'openthread' => $modPerms['canopenclose'] > 0 ? 1 : 0, 'approvethread' => $modPerms['canmoderateposts'] > 0 ? 1 : 0, 'movethread' => $modPerms['canmassmove'] > 0 ? 1 : 0, 'forumsearch' => $forumsearch, 'stickies' => count($topics_sticky) > 0 ? 1 : 0);
     return $response;
 }
Ejemplo n.º 9
0
 /**
  * Adds a new node.
  *
  * @param  mixed   Array of field => value pairs which define the record.
  * @param  array   Array of options for the content being created.
  *                 Understands skipTransaction, skipFloodCheck, floodchecktime, skipDupCheck, skipNotification, nl2br, autoparselinks.
  *                 - nl2br: if TRUE, all \n will be converted to <br /> so that it's not removed by the html parser (e.g. comments).
  *                 - wysiwyg: if true convert html to bbcode.  Defaults to true if not given.
  *
  * @return integer the new nodeid
  */
 public function add($data, $options = array())
 {
     vB_Api::instanceInternal('hv')->verifyToken($data['hvinput'], 'post');
     if (vB_Api::instanceInternal('node')->fetchAlbumChannel() == $data['parentid'] and !vB::getUserContext()->hasPermission('albumpermissions', 'picturefollowforummoderation')) {
         $data['approved'] = 0;
         $data['showapproved'] = 0;
     }
     return parent::add($data, $options);
 }
Ejemplo n.º 10
0
 /**
  * Return current user's notifications from DB.
  *
  * @param	Array	$data	@see vB_Library_Notification::fetchNotificationsForCurrentUser()
  *
  * @return	Array	@see vB_Library_Notification::fetchNotificationsForCurrentUser()
  *
  * @throws vB_Exception_Api('not_logged_no_permission')		If user is not logged in
  */
 public function fetchNotificationsForCurrentUser($data = array())
 {
     $userid = vB::getCurrentSession()->get('userid');
     if (!intval($userid)) {
         throw new vB_Exception_Api('not_logged_no_permission');
     }
     $data['showdetail'] = vB::getUserContext()->hasPermission('genericpermissions', 'canseewholiked');
     $notifications = vB_Library::instance('notification')->fetchNotificationsForCurrentUser($data);
     return $notifications;
 }
Ejemplo n.º 11
0
 public function __construct(&$routeInfo, &$matches, &$queryString = '')
 {
     $userid = vB::getCurrentSession()->get('userid');
     $pmquota = vB::getUserContext($userid)->getLimit('pmquota');
     $vboptions = vB::getDatastore($userid)->getValue('options');
     $canUsePmSystem = ($vboptions['enablepms'] and $pmquota);
     if (!$canUsePmSystem) {
         throw new vB_Exception_NodePermission('privatemessage');
     }
     parent::__construct($routeInfo, $matches, $queryString);
 }
Ejemplo n.º 12
0
 /**
  * Check if the external data provider type is available and it actually produces a valid output for given channels.
  *
  * @param 	Array 	List of channel ids to check external status from.
  * @param 	String 	External type.
  *					Supported: vB_Api_External::TYPE_JS, vB_Api_External::TYPE_XML, 
  *					vB_Api_External::TYPE_RSS, vB_Api_External::TYPE_RSS1, vB_Api_External::TYPE_RSS2
  * 
  * @return 	Array 	Associative array with external status information for each given channel.
  *					Status will be added to each array element as '$type_enabled' key.
  */
 public function checkExternalForChannels($channelids, $type)
 {
     $check = $this->validateExternalType($type);
     $enabled = true;
     if ($check['valid'] === false) {
         $enabled = false;
     }
     $result = array();
     $gcontext = vB::getUserContext(0);
     foreach ($channelids as $channel) {
         $result[$channel][$type . '_enabled'] = ($enabled and $gcontext->getChannelPermission('forumpermissions', 'canview', $channel)) ? 1 : 0;
     }
     return $result;
 }
Ejemplo n.º 13
0
 /** sends a batch of emails
  *
  *	@param	mixed	array of recipients, or a semicolon-delimited string
  * 	@param	string	subject of the message
  * 	@param	string	content of message
  *
  * 	@return	mixed	either success => true, or array of sent, failed, errors, and message- the last is suitable for display to user.
  */
 public function send($to, $subject, $message)
 {
     //This should only be used by admins
     if (!vB::getUserContext()->hasAdminPermission('canadminusers')) {
         throw new vB_Exception_Api('no_permission');
     }
     if (!is_array($to)) {
         if (strpos($to, ';')) {
             $to = explode(';', $to);
         } else {
             $to = array($to);
         }
     }
     $errors = '';
     $sent = array();
     $failed = array();
     foreach ($to as $toemail) {
         //The next function returns either true, false or an error string.
         $result = vB_Mail::vbmail($toemail, $subject, $message, false, '', '', '', true);
         if (is_string($result)) {
             $errors .= $result;
         } else {
             if ($result) {
                 $sent[] = $toemail;
             } else {
                 $failed[] = $toemail;
             }
         }
     }
     if (empty($failed) and empty($errors)) {
         return array('success' => true);
     }
     $message = '';
     if (!empty($errors)) {
         $message = vB_Phrase::fetchSinglePhrase('error_x', $errors) . '. ';
     }
     if (!empty($sent)) {
         $message .= vB_Phrase::fetchSinglePhrase('sent_to_x', implode(',', $sent));
     }
     if (!empty($failed)) {
         $message .= vB_Phrase::fetchSinglePhrase('send_failed_to_x', implode(',', $failed));
     }
     return array('sent' => $sent, 'failed' => $failed, 'errors' => $errors, 'message' => $message);
 }
Ejemplo n.º 14
0
 public function isViglinkEnabled($prev, $feature = self::VIGLINK_FEATURE_ALL)
 {
     $utils = new Viglink_Utils();
     $is_enabled = (bool) vB::getDatastore()->getOption('viglink_enabled');
     $has_key = (bool) vB_Api::instance('site')->getViglinkKey();
     $args = func_get_args();
     $enabled = $is_enabled && $has_key;
     switch ($feature) {
         case self::VIGLINK_FEATURE_ALL:
             return $enabled;
         case self::VIGLINK_FEATURE_LII:
             // disabled for one of this user's groups?
             $disabled_group_ids = json_decode($utils->getOption('lii_excluded_usergroups', '[]'));
             $user_disabled_group_ids = array_intersect($disabled_group_ids, vB::getUserContext()->fetchUserGroups());
             $lii_enabled_for_groups = empty($user_disabled_group_ids);
             $lii_enabled = $lii_enabled_for_groups;
             return $enabled && $lii_enabled;
     }
 }
Ejemplo n.º 15
0
 public function __construct($routeInfo, $matches, $queryString = '', $anchor = '')
 {
     parent::__construct($routeInfo, $matches, $queryString);
     if (isset($this->arguments['channelid'])) {
         if (!vB::getUserContext()->getChannelPermission('forumpermissions', 'canview', $this->arguments['channelid'])) {
             throw new vB_Exception_NodePermission($this->arguments['channelid']);
         }
         // check if we need to force a styleid
         $channel = vB_Library::instance('Content_Channel')->getBareContent($this->arguments['channelid']);
         if (is_array($channel)) {
             $channel = array_pop($channel);
         }
         if (!empty($channel['styleid'])) {
             $forumOptions = vB::getDatastore()->getValue('bf_misc_forumoptions');
             if ($channel['options']['styleoverride']) {
                 // the channel must force the style
                 $this->arguments['forceStyleId'] = $channel['styleid'];
             } else {
                 // the channel suggests to use this style
                 $this->arguments['routeStyleId'] = $channel['styleid'];
             }
         }
         if (!empty($this->queryParameters)) {
             $this->arguments['noindex'] = 1;
         }
         if (!empty($channel['description'])) {
             $this->arguments['nodedescription'] = $channel['description'];
         }
         // rss info
         $this->arguments['rss_enabled'] = $channel['rss_enabled'];
         $this->arguments['rss_route'] = $channel['rss_route'];
         $this->arguments['rss_title'] = $channel['title'];
         // because conversation routes also add their parent channel's rss info into the arguments,
         // this flag helps us tell channels apart from conversations when we're adding the RSS icon next to the page title
         $this->arguments['rss_show_icon_on_pagetitle'] = $channel['rss_enabled'];
         // styleid for channels are not final at this point, so let's not include them in the key
         $this->setPageKey('pageid', 'channelid');
         // set user action
         $this->setUserAction('viewing_forum_x', $channel['title'], $this->getFullUrl('fullurl'));
         // remove link from last crumb
         $this->breadcrumbs[count($this->breadcrumbs) - 1]['url'] = '';
     }
 }
Ejemplo n.º 16
0
 public function newthread($forumid)
 {
     $cleaner = vB::getCleaner();
     $forumid = $cleaner->clean($forumid, vB_Cleaner::TYPE_UINT);
     $forum = vB_Api::instance('node')->getFullContentforNodes(array($forumid));
     if (empty($forum)) {
         return array("response" => array("errormessage" => array("invalidid")));
     }
     $forum = $forum[0];
     $foruminfo = vB_Library::instance('vb4_functions')->parseForumInfo($forum);
     $prefixes = vB_Library::instance('vb4_functions')->getPrefixes($forumid);
     $options = vB::getDatastore()->getValue('options');
     $postattachment = $forum['content']['createpermissions']['vbforum_attach'];
     $postattachment = empty($postattachment) ? 0 : intval($postattachment);
     $usercontext = vB::getUserContext($this->currentUserId);
     $maxtags = $usercontext->getChannelLimits($forumid, 'maxstartertags');
     $out = array('show' => array('tag_option' => 1), 'vboptions' => array('postminchars' => $options['postminchars'], 'titlemaxchars' => $options['titlemaxchars'], 'maxtags' => $maxtags), 'response' => array('forumrules' => array('can' => array('postattachment' => $postattachment)), 'prefix_options' => $prefixes, 'foruminfo' => $foruminfo, 'poststarttime' => vB::getRequest()->getTimeNow(), 'posthash' => vB_Library::instance('vb4_posthash')->getNewPosthash()));
     return $out;
 }
Ejemplo n.º 17
0
 public function newreply($threadid, $disablesmilies = false)
 {
     $cleaner = vB::getCleaner();
     $threadid = $cleaner->clean($threadid, vB_Cleaner::TYPE_UINT);
     $thread = vB_Api::instance('node')->getFullContentforNodes(array($threadid));
     if (empty($thread)) {
         return array("response" => array("errormessage" => array("invalidid")));
     }
     $thread = $thread[0];
     $prefixes = vB_Library::instance('vb4_functions')->getPrefixes($threadid);
     $options = vB::getDatastore()->getValue('options');
     $postattachment = $thread['content']['createpermissions']['vbforum_attach'];
     $postattachment = empty($postattachment) ? 0 : intval($postattachment);
     /*
     			additional options' checked checkboxes array...
     */
     $checked = array('parseurl' => 1, 'signature' => "", "subscribe" => $thread['content']['subscribed']);
     // 	SIGNATURE
     $userContext = vB::getUserContext();
     $currentUserId = $userContext->fetchUserId();
     $signature = vB_Api::instanceInternal('user')->fetchSignature($currentUserId);
     if (!empty($signature)) {
         $checked['signature'] = 1;
     }
     // 	DISABLESMILIES
     // getDataForParse converts channel.options into bbcodeoptions, and this is used by the
     // frontend nodetext / bbcode parsers
     $textDataArray = vB_Api::instanceInternal('content_text')->getDataForParse(array($threadid));
     $channelAllowsSmilies = $textDataArray[$threadid]['bbcodeoptions']['allowsmilies'];
     if ($channelAllowsSmilies) {
         if (!empty($disablesmilies)) {
             $checked['disablesmilies'] = 1;
         } else {
             $checked['disablesmilies'] = "";
         }
         $show['smiliebox'] = 1;
     } else {
         $show['smiliebox'] = 0;
     }
     $out = array('show' => array('tag_option' => 1, 'smiliebox' => $show['smiliebox']), 'vboptions' => array('postminchars' => $options['postminchars'], 'titlemaxchars' => $options['titlemaxchars']), 'response' => array('title' => '', 'forumrules' => array('can' => array('postattachment' => $postattachment)), 'prefix_options' => $prefixes, 'poststarttime' => 0, 'posthash' => vB_Library::instance('vb4_posthash')->getNewPosthash()), 'checked' => $checked);
     return $out;
 }
Ejemplo n.º 18
0
 public function __construct(&$routeInfo, &$matches, &$queryString = '')
 {
     $cleaner = vB::getCleaner();
     if (isset($matches['params']) and !empty($matches['params'])) {
         $paramString = strpos($matches['params'], '/') === 0 ? substr($matches['params'], 1) : $matches['params'];
         list($this->userid) = explode('/', $paramString);
     } else {
         if (isset($matches['userid'])) {
             $this->userid = $matches['userid'];
         }
     }
     $this->userid = $cleaner->clean($this->userid, vB_Cleaner::TYPE_INT);
     $routeInfo['arguments']['subtemplate'] = $this->subtemplate;
     $userid = vB::getCurrentSession()->get('userid');
     $pmquota = vB::getUserContext($userid)->getLimit('pmquota');
     $vboptions = vB::getDatastore($userid)->getValue('options');
     $canUsePmSystem = ($vboptions['enablepms'] and $pmquota);
     if (!$canUsePmSystem) {
         throw new vB_Exception_NodePermission('privatemessage');
     }
 }
Ejemplo n.º 19
0
 /**
  * Vote on a Poll (for the current user)
  *
  * @param  int|array Int or an array of poll option IDs to be "voted"
  *
  * @return int       The node ID of the poll that was voted on.
  */
 public function vote($polloptionids)
 {
     $usercontext =& vB::getUserContext();
     if (is_numeric($polloptionids)) {
         $polloptionids = array($polloptionids);
     } elseif (!is_array($polloptionids)) {
         throw new vB_Exception_Api('invalidparameter');
     }
     $options = array();
     $nodeid = 0;
     foreach ($polloptionids as $polloptionid) {
         $option = $this->assertor->getRow('vBForum:polloption', array(vB_dB_Query::TYPE_KEY => vB_dB_Query::QUERY_SELECT, 'polloptionid' => intval($polloptionid)));
         if (!$option or $nodeid and $nodeid != $option['nodeid']) {
             throw new vB_Exception_Api('invalidvote');
         }
         if (!$usercontext->getChannelPermission('forumpermissions', 'canvote', $option['nodeid'])) {
             throw new vB_Exception_Api('no_permission');
         }
         $options[] = $option;
         $nodeid = $option['nodeid'];
     }
     unset($option);
     $polls = $this->getContent($nodeid);
     if (empty($polls) or empty($polls[$nodeid])) {
         return false;
     }
     // Check if the poll is timeout
     if ($polls[$nodeid]['timeout'] and $polls[$nodeid]['timeout'] < vB::getRequest()->getTimeNow()) {
         return false;
     }
     // Check if the user has voted the poll
     if ($this->checkVoted($nodeid)) {
         return false;
     }
     $nodeid = $this->library->vote($options);
     // All options should be in a same poll
     $this->updatePollCache($nodeid, true);
     return $nodeid;
 }
Ejemplo n.º 20
0
 public function importAdminCP($parsedXML, $startat = 0, $perpage = 1, $overwrite = false, $styleid = -1, $anyversion = false, $extra = array())
 {
     /*
      *	Since this function allows passing in a string rather than pulling a file from the filesystem, we should
      *	be more careful about who can call it
      *	This check is based on the admincp/template.php script @ if ($_REQUEST['do'] == 'upload'). We should keep them in line.
      */
     if (!vB::getUserContext()->hasAdminPermission('canadmintemplates') or !vB::getUserContext()->hasAdminPermission('canadminstyles')) {
         require_once DIR . '/includes/adminfunctions.php';
         print_cp_no_permission();
     }
     if (empty($parsedXML['guid'])) {
         // todo: some error handling here if basic xml file validation isn't okay.
     }
     $this->parsedXML['theme'] = $parsedXML;
     // make sure we have the theme parent, as any imported themes will be its children
     if (empty(self::$themeParent['guid'])) {
         $this->getDefaultParentTheme();
     }
     /*
      *	drop any unexpected extra variables.
      *	Let's also clean them, since there might be someway a user w/ the right permissions
      *	hits this function directly. So here we have an issue. If coming through the adminCP page,
      *	things will already be cleaned, so STRINGS will already be escaped. However, I don't think
      *	the title should contain any special HTML characters, so I think we don't have to worry about
      *	double escaping here. If we do end up having to worry about double escaping, we need to remove
      *	the cleaning here, and just rely on the adminCP page's cleaning, then make sure NOTHING HERE
      *	GOES STRAIGHT TO DB without going through the assertor in adminfunctions_template.php
      */
     $unclean = $extra;
     $extra = array();
     $cleanMap = array('title' => vB_Cleaner::TYPE_STR, 'parentid' => vB_Cleaner::TYPE_INT, 'displayorder' => vB_Cleaner::TYPE_INT, 'userselect' => vB_Cleaner::TYPE_BOOL);
     foreach ($unclean as $key => $value) {
         if (isset($cleanMap[$key])) {
             $extra[$key] = vB::getCleaner()->clean($value, $cleanMap[$key]);
         }
     }
     return $this->import($startat, $perpage, $overwrite, $styleid, $anyversion, $extra);
 }
Ejemplo n.º 21
0
 /** this deletes an existing permission
  *
  * 	@return	mixed		either permissionid(single or array), or nodeid and usergroupid. A single Nodeid is required and usergroup is optional and may be an array
  ***/
 public function deletePerms($params)
 {
     if (!empty($params['permissionid'])) {
         //We don't allow deleting permissions from page 1.
         $existing = vB::getDbAssertor()->getRow('vBForum:permission', array('permissionid' => $params['permissionid']));
         if (empty($existing) or !empty($existing['errors']) or $existing['nodeid'] == 1) {
             return false;
         }
         $qryParams['permissionid'] = $params['permissionid'];
     } else {
         if (!empty($params['nodeid']) and intval($params['nodeid'])) {
             $qryParams['nodeid'] = intval($params['nodeid']);
             if (!empty($params['groupid'])) {
                 $qryParams['groupid'] = $params['groupid'];
             }
         } else {
             return false;
         }
     }
     $qryParams[vB_dB_Query::TYPE_KEY] = vB_dB_Query::QUERY_DELETE;
     $result = vB::getDbAssertor()->assertQuery('vBForum:permission', $qryParams);
     vB_Cache::instance()->event('perms_changed');
     //force reloading the group access cache
     vB::getUserContext()->rebuildGroupAccess();
     return $result;
 }
Ejemplo n.º 22
0
 /**
  * Determines if the logged-in user can view admin notes
  *
  * @return bool The current user can view admin notes (or not)
  */
 public function canViewAdminNote()
 {
     // To view the admin note, you must have permission to give or to reverse infractions
     // (not merely permission to view the infraction)
     return vB::getUserContext()->hasPermission('genericpermissions', 'cangiveinfraction') or vB::getUserContext()->hasPermission('genericpermissions', 'canreverseinfraction');
 }
Ejemplo n.º 23
0
                }
            }
            break;
        case 'deny':
            $usergroupcache =& vB::getDatastore()->getValue('usergroupcache');
            foreach ($usergroupcache as $group) {
                /*insert query*/
                vB::getDbAssertor()->assertQuery('replacePermissions', array(vB_dB_Query::TYPE_KEY => vB_dB_Query::QUERY_STORED, 'nodeid' => $vbulletin->GPC['nodeid'], 'usergroupid' => $group['usergroupid'], 'forumpermissions' => 0, 'moderatorpermissions' => 0, 'createpermissions' => 0, 'forumpermissions2' => 0, 'edit_time' => 2, 'require_moderate' => 1, 'maxtags' => 0, 'maxstartertags' => 0, 'maxothertags' => 0, 'maxattachments' => 0, 'maxchannels' => 0, 'channeliconmaxsize' => 0));
            }
            break;
        default:
            print_stop_message2('invalid_quick_set_action');
    }
    build_channel_permissions();
    vB_Cache::instance()->event('perms_changed');
    vB::getUserContext()->rebuildGroupAccess();
    print_stop_message2('saved_channel_permissions_successfully', 'forumpermission', array('do' => 'modify', 'n' => $vbulletin->GPC['nodeid']));
}
// ###################### Start fpgetstyle #######################
function fetch_forumpermission_style($permissions)
{
    global $vbulletin;
    if (!($permissions & $vbulletin->bf_ugp_forumpermissions['canview'])) {
        return " style=\"list-style-type:circle;\"";
    } else {
        return '';
    }
}
// ###################### Start modify #######################
if ($_REQUEST['do'] == 'modify') {
    print_form_header('', '');
Ejemplo n.º 24
0
 /**
  * Prepares data for generating the navbar display, decides which navbar tab to
  * highlight. The passed $data array is modified.
  *
  * @param	array	Array of navigation items, for the header or the footer
  * @param	string	The current URL
  * @param	bool	True if editing the page, false if not
  * @param	int	Channel Node ID
  *
  * @return	bool	Whether the current navbar item was found or not
  */
 protected function prepareNavbarData(array &$data, $url = false, $edit = false, $channelId = 0)
 {
     $baseurl_short = vB_String::parseUrl(vB::getDatastore()->getOption('frontendurl'), PHP_URL_PATH);
     $found_current = false;
     $found_sub_parent = false;
     $possibleCurrentItems = array();
     $removed_element = false;
     $userinfo = vB_Api::instanceInternal('user')->fetchCurrentUserInfo();
     $phraseApi = vB_Api::instance('phrase');
     foreach ($data as $k => &$item) {
         if (is_array($item) and isset($item['url'])) {
             $item['phrase'] = $item['title'];
             $this->requiredPhrases[] = $item['title'];
             $additionalGrp = false;
             if ($userinfo['membergroupids'] and !empty($item['usergroups'])) {
                 $memberGroups = explode(',', $userinfo['membergroupids']);
                 foreach ($memberGroups as $memberGroup) {
                     if (in_array($memberGroup, $item['usergroups'])) {
                         $additionalGrp = true;
                         break;
                     }
                 }
             }
             if ((!$edit or !vB::getUserContext()->hasAdminPermission('canusesitebuilder')) and (!empty($item['usergroups']) and (!in_array($userinfo['usergroupid'], $item['usergroups']) and !$additionalGrp))) {
                 unset($data[$k]);
                 $removed_element = true;
                 continue;
             }
             $item['isAbsoluteUrl'] = (bool) preg_match('#^https?://#i', $item['url']);
             $item['normalizedUrl'] = ltrim($item['url'], '/');
             $item['newWindow'] = $item['newWindow'] ? 1 : 0;
             if (!empty($item['subnav']) and is_array($item['subnav'])) {
                 $found_sub = $this->prepareNavbarData($item['subnav'], $url, $edit, $channelId);
                 if (!$found_current and $found_sub) {
                     $found_sub_parent =& $item;
                     $item['current_sub'] = true;
                 }
             }
             if (!$found_current and !empty($url)) {
                 if ($item['isAbsoluteUrl']) {
                     $itemUrl = vB_String::parseUrl($item['normalizedUrl'], PHP_URL_PATH);
                 } else {
                     $itemUrl = $baseurl_short . '/' . $item['normalizedUrl'];
                 }
                 if (strtolower($url) == strtolower($itemUrl) || strlen($url) > strlen($itemUrl) && strtolower(substr($url, 0, -(strlen($url) - strlen($itemUrl)))) == strtolower($itemUrl)) {
                     // found an item that might be the current item
                     $possibleCurrentItems[] = array('length' => strlen($itemUrl), 'item' => &$item);
                 }
             }
         }
     }
     // Reset the keys of the array, because in js it will be considered as an object
     if ($removed_element) {
         $data = array_values($data);
     }
     // test some special cases where we have non-conforming routes (routes
     // which don't begin with the same text as the navbar tab they are
     // supposed to be in.
     // @TODO consider renaming the /blogadmin route to /blogs/admin
     // and the /sgadmin route to /social-groups/admin
     if (!$found_current) {
         $setCurrentTab = '';
         // special case: the create content pages
         $channelId = (int) $channelId;
         if (strpos($url, $baseurl_short . '/new-content') === 0 and $channelId > 0) {
             switch ($this->getChannelType($channelId)) {
                 case 'blog':
                     $setCurrentTab = 'blogs';
                     break;
                 case 'group':
                     $setCurrentTab = 'social-groups';
                     break;
                 case 'article':
                     $setCurrentTab = 'articles';
                     break;
                 default:
                     break;
             }
         } else {
             if (strpos($url, $baseurl_short . '/blogadmin') === 0) {
                 $setCurrentTab = 'blogs';
             } else {
                 if (strpos($url, $baseurl_short . '/sgadmin') === 0) {
                     $setCurrentTab = 'social-groups';
                 } else {
                     if ($channelId > 0) {
                         // special case: social groups, categories & topics
                         // social group routes do not maintain the 'social-groups' bit in the URL
                         if ($this->getChannelType($channelId) == 'group') {
                             $setCurrentTab = 'social-groups';
                         }
                     }
                 }
             }
         }
         // set the special-cased tab to current
         if ($setCurrentTab) {
             foreach ($data as $k => $v) {
                 if ($v['normalizedUrl'] == $setCurrentTab) {
                     $data[$k]['current'] = true;
                     $found_current = true;
                     break;
                 }
             }
         }
     }
     // test the possible current items-- the longest URL is the best match
     if (!$found_current and !empty($possibleCurrentItems)) {
         $longestKey = 0;
         foreach ($possibleCurrentItems as $k => $possibleCurrentItem) {
             if ($possibleCurrentItem['length'] > $possibleCurrentItems[$longestKey]['length']) {
                 $longestKey = $k;
             }
         }
         $possibleCurrentItems[$longestKey]['item']['current'] = true;
         $found_current = true;
     }
     unset($possibleCurrentItems);
     if (!$found_current and !empty($found_sub_parent)) {
         $found_sub_parent['current'] = true;
     }
     return $found_current;
 }
Ejemplo n.º 25
0
 /**
  * Saves an uploaded file into the filedata system.
  *
  * @param	int		$userid				Id of user uploading the image. This user's permissions will be checked when necessary
  * @param	array	$filearray			Array of data describing the uploaded file with data-types & keys:
  *											string	'name'			Filename
  *											int		'size'			Filesize
  *											string	'type'			Filetype
  *											string	'tmp_name'		Filepath to the temporary file created on the server
  *											int		'parentid'		Optional. Node/Channelid this file will be uploaded under. If provided
  *																	permissions will be checked under this node.
  *											bool	'is_sigpic'		Optional. If this is not empty, the saved filedata will replace
  *																	the user's sigpicnew record (or inserted for the user if none exists),
  *																	and the filedata record will have refcount incremented & publicview
  *																	set to 1.
  * @param	string	$fileContents		String(?) containing file content BLOB
  * @param	int		$filesize			File size
  * @param	string	$extension			File extension
  * @param	bool	$imageOnly			If true, this function will throw an exception if the file is not an image
  * @param	bool	$skipUploadPermissionCheck		Optional boolean to skip permission checks. Only used internally when the system
  *													saves a theme icon. Do not use for normal calls to this function.
  *
  * @return	array	Array of saved filedata info with data-types & keys:
  *						int 		'filedataid'
  *						int 		'filesize'
  *						int			'thumbsize'		file size of the thumbnail of the saved filedata
  *						string		'extension'
  *						string		'filename'
  *						string[]	'headers'		array containing the content-type http header of the saved filedata
  *						boolean		'isimage'
  *
  * @throws	vB_Exception_Api('invalid_attachment_storage')	If 'attachfile' ("Save attachments as File") is enabled and the path specified
  *															by 'attachpath' option is not writable for some reason
  * @throws	vB_Exception_Api('dangerous_image_rejected')	If image verification failed for $fileContents or $filearray['tmp_name']
  * @throws	vB_Exception_Api('upload_attachfull_total')		If attachment quota specified by 'attachtotalspace' option is exceeded
  * @throws	vB_Exception_Api('cannot_create_file')			If the user fails the permission checks
  * @throws	vB_Exception_Api('upload_invalid_image')		If $imageOnly is true and the uploaded file is not an image
  * @throws	vB_Exception_Api('unable_to_add_filedata')		If adding the filedata record failed
  * @throws	vB_Exception_Api('attachpathfailed')			If 'attachfile' ("Save attachments as File") is enabled and creating or fetching
  *															the path to the attachment directory for the user failed
  * @throws	vB_Exception_Api('upload_file_system_is_not_writable_path')		If 'attachfile' ("Save attachments as File") is enabled and the
  *															path retrieved for the user is not writable.
  *
  * @access	public
  */
 public function saveUpload($userid, $filearray, $fileContents, $filesize, $extension, $imageOnly = false, $skipUploadPermissionCheck = false)
 {
     $assertor = vB::getDbAssertor();
     $datastore = vB::getDatastore();
     $options = $datastore->getValue('options');
     $config = vB::getConfig();
     $usercontext = vB::getUserContext($userid);
     //make sure there's a place to put attachments.
     if ($options['attachfile'] and (empty($options['attachpath']) or !file_exists($options['attachpath']) or !is_writable($options['attachpath']) or !is_dir($options['attachpath']))) {
         throw new vB_Exception_Api('invalid_attachment_storage');
     }
     //make sure the file is good.
     if (!$this->imageHandler->verifyImageFile($fileContents, $filearray['tmp_name'])) {
         @unlink($filearray['tmp_name']);
         throw new vB_Exception_Api('dangerous_image_rejected');
     }
     // Check if this is an image extension we're dealing with for displaying later.
     // exif_imagetype() will check the validity of image
     $isImageExtension = $isImage = $this->imageHandler->isImage($extension);
     if ($isImage and function_exists('exif_imagetype')) {
         $imageType = @exif_imagetype($filearray['tmp_name']);
         $isImage = (bool) $imageType;
     } else {
         if ($isImage and function_exists('finfo_open') and function_exists('finfo_file')) {
             /*
              * TODO: When pdf thumbnail support is fixed, this check might have to be updated.
              */
             // Just in case exif_imagetype is not there. finfo extension should be installed
             // by default (except windows), and is an alternative way to detect
             // if this is an image.
             // In the future, perhaps we can just use below to set the mimetype in the database,
             // and have the fetchImage functions return the mimetype as well rather than
             // trying to set it based on the filedata.extension (which may not be correct).
             $finfo = finfo_open(FILEINFO_MIME_TYPE);
             $mimetype = finfo_file($finfo, $filearray['tmp_name']);
             if ($mimetype) {
                 $mimetype = explode('/', $mimetype);
                 $toplevel = $mimetype[0];
                 if ($toplevel != 'image') {
                     $isImage = false;
                 }
             } else {
                 $isImage = false;
             }
         }
     }
     /*
      *	Note, this is for identification only, NOT for security!
      *	If we're going to depend on the extension to determine if it's an image,
      *	let's at least check that it's an image.
      */
     if ($isImageExtension and !$isImage) {
         // Do not allow a non-image to use an image extension.
         throw new vB_Exception_Api('image_extension_but_wrong_type');
     }
     // Thumbnails are a different story altogether. Something like a PDF
     // might have a thumbnail.
     $canHaveThumbnail = $this->imageHandler->imageThumbnailSupported($extension);
     /*
      * TODO: We might want to check that the extension matches the mimetype.
      *
      */
     //We check to see if this file already exists.
     $filehash = md5($fileContents);
     $fileCheck = $assertor->getRow('vBForum:getFiledataWithThumb', array('filehash' => $filehash, 'filesize' => $filesize));
     // Does filedata already exist?
     if (empty($fileCheck) or $fileCheck['userid'] != $userid) {
         // Check if we are not exceeding the quota
         if ($options['attachtotalspace'] > 0) {
             $usedSpace = $assertor->getField('vBForum:getUserFiledataFilesizeSum', array('userid' => $userid));
             $overage = $usedSpace + $filesize - $options['attachtotalspace'];
             if ($overage > 0) {
                 $overage = vb_number_format($overage, 1, true);
                 $userinfo = vB::getCurrentSession()->fetch_userinfo();
                 $maildata = vB_Api::instanceInternal('phrase')->fetchEmailPhrases('attachfull', array($userinfo['username'], $options['attachtotalspace'], $options['bburl'], 'admincp'), array($options['bbtitle']), 0);
                 vB_Mail::vbmail($options['webmasteremail'], $maildata['subject'], $maildata['message']);
                 throw new vB_Exception_Api('upload_attachfull_total', $overage);
             }
         }
         // Can we move this permission check out of this library function?
         if (!$usercontext->canUpload($filesize, $extension, !empty($filearray['parentid']) ? $filearray['parentid'] : false) and !$skipUploadPermissionCheck) {
             @unlink($filearray['tmp_name']);
             throw new vB_Exception_Api('cannot_create_file');
         }
         if ($imageOnly and !$isImage) {
             throw new vB_Exception_Api('upload_invalid_image');
         }
         $timenow = vB::getRequest()->getTimeNow();
         if ($canHaveThumbnail) {
             //Get the image size information.
             $imageInfo = $this->imageHandler->fetchImageInfo($filearray['tmp_name']);
             $sizes = @unserialize($options['attachresizes']);
             if (!isset($sizes['thumb']) or empty($sizes['thumb'])) {
                 $sizes['thumb'] = 100;
             }
             $thumbnail = $this->imageHandler->fetchThumbnail($filearray['name'], $filearray['tmp_name'], $sizes['thumb'], $sizes['thumb'], $options['thumbquality']);
         } else {
             $thumbnail = array('filesize' => 0, 'width' => 0, 'height' => 0, 'filedata' => null);
         }
         $thumbnail_data = array(vB_dB_Query::TYPE_KEY => vB_dB_Query::QUERY_INSERT, 'resize_type' => 'thumb', 'resize_dateline' => $timenow, 'resize_filesize' => $thumbnail['filesize'], 'resize_width' => $thumbnail['width'], 'resize_height' => $thumbnail['height']);
         // Note, unless this is a sigpic (defined as !empty($filearray['is_sigpic'])), below will set
         // the refcount of the new filedata record to 0.
         // So the caller MUST increment the refcount if this image should not be removed by the cron.
         $data = array(vB_dB_Query::TYPE_KEY => vB_dB_Query::QUERY_INSERT, 'userid' => $userid, 'dateline' => $timenow, 'filesize' => $filesize, 'filehash' => $filehash, 'extension' => $extension, 'refcount' => 0);
         if (!empty($imageInfo)) {
             $data['width'] = $imageInfo[0];
             $data['height'] = $imageInfo[1];
         }
         //Looks like we're ready to store. But do we put it in the database or the filesystem?
         if ($options['attachfile']) {
             //We name the files based on the filedata record, but we don't have that until we create the record. So we need
             // to do an insert, then create/move the files.
             $filedataid = $assertor->assertQuery('filedata', $data);
             if (is_array($filedataid)) {
                 $filedataid = $filedataid[0];
             }
             if (!intval($filedataid)) {
                 throw new vB_Exception_Api('unable_to_add_filedata');
             }
             $path = $this->verifyAttachmentPath($userid);
             if (!$path) {
                 throw new vB_Exception_Api('attachpathfailed');
             }
             if (!is_writable($path)) {
                 throw new vB_Exception_Api('upload_file_system_is_not_writable_path', array(htmlspecialchars($path)));
             }
             if (!empty($thumbnail['filedata'])) {
                 file_put_contents($path . $filedataid . '.thumb', $thumbnail['filedata']);
             }
             rename($filearray['tmp_name'], $path . $filedataid . '.attach');
         } else {
             //We put the file contents into the data record.
             $data['filedata'] = $fileContents;
             $filedataid = $assertor->assertQuery('filedata', $data);
             if (is_array($filedataid)) {
                 $filedataid = $filedataid[0];
             }
             $thumbnail_data['resize_filedata'] = $thumbnail['filedata'];
         }
         $thumbnail_data['filedataid'] = $filedataid;
         if ($canHaveThumbnail) {
             $assertor->assertQuery('vBForum:filedataresize', $thumbnail_data);
         }
         if (!empty($filearray['name'])) {
             $filename = $filearray['name'];
         } else {
             $filename = '';
         }
         $result = array('filedataid' => $filedataid, 'filesize' => $filesize, 'thumbsize' => $thumbnail['filesize'], 'extension' => $extension, 'filename' => $filename, 'headers' => $this->getAttachmentHeaders(strtolower($extension)), 'isimage' => $isImage);
         if (!empty($filearray['is_sigpic'])) {
             $assertor->assertQuery('replaceSigpic', array('userid' => $userid, 'filedataid' => $filedataid));
             $assertor->assertQuery('incrementFiledataRefcountAndMakePublic', array('filedataid' => $filedataid));
         }
     } else {
         // file already exists so we are not going to insert a new one
         $filedataid = $fileCheck['filedataid'];
         if (!empty($filearray['is_sigpic'])) {
             // Get old signature picture data and decrease refcount
             $oldfiledata = vB::getDbAssertor()->getRow('vBForum:sigpicnew', array('userid' => $userid));
             if ($oldfiledata) {
                 vB::getDbAssertor()->assertQuery('decrementFiledataRefcount', array('filedataid' => $oldfiledata['filedataid']));
             }
             $assertor->assertQuery('replaceSigpic', array('userid' => $fileCheck['userid'], 'filedataid' => $filedataid));
             $assertor->assertQuery('incrementFiledataRefcountAndMakePublic', array('filedataid' => $filedataid));
         }
         $result = array('filedataid' => $filedataid, 'filesize' => $fileCheck['filesize'], 'thumbsize' => $fileCheck['resize_filesize'], 'extension' => $extension, 'filename' => $filearray['name'], 'headers' => $this->getAttachmentHeaders(strtolower($extension)), 'isimage' => $isImage);
     }
     return $result;
 }
Ejemplo n.º 26
0
 /**
  * Attempt to resize file if the filesize is too large after an initial resize to max dimensions or the file is already within max dimensions but the filesize is too large
  *
  * @param	bool	Has the image already been resized once?
  * @param	bool	Attempt a resize
  */
 function bestResize($width, $height)
 {
     // Linear Regression
     $maxuploadsize = vB::getUserContext()->getLimit('avatarmaxsize');
     switch (vB::getDatastore()->getOption('thumbquality')) {
         case 65:
             // No Sharpen
             // $magicnumber = round(379.421 + .00348171 * $this->maxuploadsize);
             // Sharpen
             $magicnumber = round(277.652 + 0.00428902 * $maxuploadsize);
             break;
         case 85:
             // No Sharpen
             // $magicnumber = round(292.53 + .0027378 * $maxuploadsize);
             // Sharpen
             $magicnumber = round(189.939 + 0.00352439 * $maxuploadsize);
             break;
         case 95:
             // No Sharpen
             // $magicnumber = round(188.11 + .0022561 * $maxuploadsize);
             // Sharpen
             $magicnumber = round(159.146 + 0.00234146 * $maxuploadsize);
             break;
         default:
             //75
             // No Sharpen
             // $magicnumber = round(328.415 + .00323415 * $maxuploadsize);
             // Sharpen
             $magicnumber = round(228.201 + 0.00396951 * $maxuploadsize);
     }
     $xratio = $width > $magicnumber ? $magicnumber / $width : 1;
     $yratio = $height > $magicnumber ? $magicnumber / $height : 1;
     if ($xratio > $yratio and $xratio != 1) {
         $new_width = round($width * $xratio);
         $new_height = round($height * $xratio);
     } else {
         $new_width = round($width * $yratio);
         $new_height = round($height * $yratio);
     }
     if ($new_width == $width and $new_height == $height) {
         // subtract one pixel so that requested size isn't the same as the image size
         $new_width--;
     }
     return array('width' => $new_width, 'height' => $new_height);
 }
Ejemplo n.º 27
0
 /** Tells whether the current user can create a blog entry. That can be their own permissions or GIT.
  *
  * 	@return
  */
 public function canCreateBlogEntry($nodeid = 0)
 {
     //This is called from the templates, so we return 0/1.  Templates have problems with true/false.
     if (empty($nodeid) and vB::getUserContext()->hasPermission('forumpermissions', 'cancreateblog')) {
         return 1;
     }
     if (empty($nodeid)) {
         $nodeid = vB_Library::instance('blog')->getBlogChannel();
     }
     $canStart = $this->getGitCanStart($nodeid);
     if (!empty($canStart)) {
         return 1;
     }
     return 0;
 }
Ejemplo n.º 28
0
 /**
  * Return all the subscribers from a given nodeid.
  *
  * @param	int		Nodeid we are fetching subscribers from
  * @param	mixed	Array of options to the node subscribers such as page, perpage,
  *
  * @return	mixed	Array of the subscribers with their information. Such as userid, username, avatar
  */
 public function getNodeSubscribers($nodeid, $options = array())
 {
     if (!is_numeric($nodeid) or $nodeid < 1) {
         throw new vB_Exception_Api('invalid_data');
     }
     if (!vB::getUserContext()->getChannelPermission('moderatorpermissions', 'canaddowners', $nodeid)) {
         throw new vB_Exception_Api('no_permission');
     }
     $data = array('nodeid' => $nodeid);
     $data[vB_dB_Query::PARAM_LIMIT] = (isset($options['perpage']) and is_numeric($options['perpage']) and $options['perpage'] > 0) ? $options['perpage'] : 20;
     $data[vB_dB_Query::PARAM_LIMITPAGE] = (isset($options['page']) and is_numeric($options['page']) and $options['page'] > 0) ? $options['page'] : 1;
     $data['sort'] = array('username' => 'ASC');
     $subscribers = vB::getDbAssertor()->getRows('vBForum:fetchNodeSubscribers', $data);
     $total = vB::getDbAssertor()->getRow('vBForum:getNodeSubscribersTotalCount');
     $result = array('subscribers' => array(), 'totalcount' => $total['total']);
     $ids = array();
     if (!empty($subscribers)) {
         foreach ($subscribers as $subscriber) {
             $result['subscribers'][$subscriber['userid']] = array('userid' => $subscriber['userid'], 'username' => $subscriber['username']);
             $ids[] = $subscriber['userid'];
         }
         $avatars = vB_Api::instanceInternal('user')->fetchAvatars($ids);
         foreach ($avatars as $uid => $avatar) {
             $result['subscribers'][$uid]['avatarpath'] = $avatar['avatarpath'];
         }
     }
     // paginationinfo
     $pages = ceil($total['total'] / $data[vB_dB_Query::PARAM_LIMIT]);
     $result['pageinfo'] = array('page' => $data[vB_dB_Query::PARAM_LIMITPAGE], 'pages' => $pages, 'nextpage' => $data[vB_dB_Query::PARAM_LIMITPAGE] < $pages ? $data[vB_dB_Query::PARAM_LIMITPAGE] + 1 : 0, 'prevpage' => $data[vB_dB_Query::PARAM_LIMITPAGE] > 1 ? $data[vB_dB_Query::PARAM_LIMITPAGE] - 1 : 0);
     return $result;
 }
Ejemplo n.º 29
0
 /**
  * Halts execution of the entire system and displays an error message
  *
  * @param	string	Text of the error message. Leave blank to use $this->sql as error text.
  *
  * @return	integer
  */
 function halt($errortext = '')
 {
     static $called = false;
     /*		if ($this->inTransaction)
     	{
     			$this->rollbackTransaction();
     		}
     */
     if ($called) {
         if (!empty($errortext)) {
             $this->error = $errortext;
         }
         return $this->error;
     } else {
         $called = true;
     }
     if ($this->connection_recent) {
         $this->error = $this->error($this->connection_recent);
         $this->errno = $this->errno($this->connection_recent);
     }
     if ($this->errno == -1) {
         throw new exception('no_vb5_database');
     }
     if ($this->reporterror) {
         if ($errortext == '') {
             $this->sql = "Invalid SQL:\r\n" . chop($this->sql) . ';';
             $errortext =& $this->sql;
             if (strlen($errortext) > 2048) {
                 $truncated_errortext = "\r\n[Showing truncated query, original length: " . strlen($this->sql) . "]\r\n[First 500 chars]\r\n" . substr($errortext, 0, 500) . "\r\n[Last 500 chars]\r\n" . substr($errortext, -500);
                 $errortext = $truncated_errortext;
                 unset($truncated_errortext);
             }
         }
         $session = vB::getCurrentSession();
         if ($session) {
             $userinfo = $session->fetch_userinfo();
         }
         //TODO -- need to clean up VB_AREA stuff
         if (defined('VB_AREA') and (VB_AREA == 'Upgrade' or VB_AREA == 'Install')) {
             $display_db_error = true;
         } else {
             $userContext = vB::getUserContext();
             $display_db_error = $userContext ? $userContext->isAdministrator() : false;
         }
         // Hide the MySQL Version if its going in the source
         if (!$display_db_error) {
             $mysqlversion = '';
         } else {
             if ($this->connection_recent) {
                 $this->hide_errors();
                 list($mysqlversion) = $this->query_first("SELECT VERSION() AS version", self::DBARRAY_NUM);
                 $this->show_errors();
             }
         }
         $vb5_config = vB::getConfig();
         $request = vB::getRequest();
         if ($request) {
             $timeNow = $request->getTimeNow();
             $scriptpath = 'unknown';
             $ipAddress = 'unknown';
             $scriptpath = $request->getScriptPath();
             $ipAddress = $request->getIpAddress();
             $referer = $request->getReferrer();
         } else {
             $timeNow = time();
             $scriptpath = '';
             $ipAddress = '';
             $referer = '';
         }
         $vboptions = vB::getDatastore()->getValue('options');
         $technicalemail =& $vb5_config['Database']['technicalemail'];
         $data = array();
         $data['error'] = $this->error;
         $data['errno'] = $this->errno;
         $data['requestdate'] = date('l, F jS Y @ h:i:s A', $timeNow);
         $data['date'] = date('l, F jS Y @ h:i:s A');
         $data['host'] = "";
         //todo figure this out for non http requests
         $data['scriptpath'] = str_replace('&amp;', '&', $scriptpath);
         $data['referer'] = $referer;
         $data['ipaddress'] = $ipAddress;
         $data['username'] = isset($userinfo['username']) ? $userinfo['username'] : "";
         $data['classname'] = get_class($this);
         $data['mysqlversion'] = $mysqlversion;
         $data['technicalemail'] = $technicalemail;
         $data['appname'] = $this->appname;
         $data['templateversion'] = $vboptions['templateversion'];
         if ($vb5_config['Misc']['debug']) {
             $data['trace'] = debug_backtrace();
         }
         $dbexception = new vB_Exception_Database($errortext, $data);
         //log message
         require_once DIR . '/includes/functions_log_error.php';
         if (function_exists('log_vbulletin_error')) {
             log_vbulletin_error($dbexception->getMessage(), 'database');
         }
         if ($this->reporterror) {
             throw $dbexception;
         }
     } else {
         if (!empty($errortext)) {
             $this->error = $errortext;
         }
     }
 }
Ejemplo n.º 30
0
</div>
</form>
<?php 
    echo '<p align="center" class="smallfont">';
    if (vB::getUserContext()->hasAdminPermission('canadminstyles')) {
        echo construct_link_code($vbphrase['add_new_style'], "template.php?" . vB::getCurrentSession()->get('sessionurl') . "do=addstyle");
    }
    if ($vb5_config['Misc']['debug'] and vB::getUserContext()->hasAdminPermission('canadmintemplates')) {
        echo construct_link_code($vbphrase['rebuild_all_styles'], "template.php?" . vB::getCurrentSession()->get('sessionurl') . "do=rebuild&amp;goto=template.php?" . vB::getCurrentSession()->get('sessionurl'));
    }
    echo "</p>\n";
}
// #############################################################################
// rebuilds all parent lists and id cache lists
if ($_REQUEST['do'] == 'rebuild') {
    if (!vB::getUserContext()->hasAdminPermission('canadmintemplates')) {
        print_cp_no_permission();
    }
    $vbulletin->input->clean_array_gpc('r', array('renumber' => vB_Cleaner::TYPE_INT, 'install' => vB_Cleaner::TYPE_INT, 'goto' => vB_Cleaner::TYPE_STR));
    echo "<p>&nbsp;</p>";
    vB_Library::instance('style')->buildAllStyles($vbulletin->GPC['renumber'], $vbulletin->GPC['install']);
    $execurl = vB_String::parseUrl($vbulletin->GPC['goto']);
    $pathinfo = pathinfo($execurl['path']);
    $file = $pathinfo['basename'];
    parse_str($execurl['query'], $args);
    print_cp_redirect2($file, $args);
}
// #############################################################################
// hex convertor
if ($_REQUEST['do'] == 'colorconverter') {
    $vbulletin->input->clean_array_gpc('r', array('hex' => vB_Cleaner::TYPE_NOHTML, 'rgb' => vB_Cleaner::TYPE_NOHTML, 'hexdec' => vB_Cleaner::TYPE_STR, 'dechex' => vB_Cleaner::TYPE_STR));