@author Vova Feldman (@svovaf)
@since  2.0.0

@param int $blog_id

@return FS_Admin_Notice_Manager
160677
private function get_site_notices( $blog_id = 0 ) {
            if ( 0 == $blog_id || $blog_id == $this->_blog_id ) {
                return $this->_notices;
            }

            return FS_Admin_Notice_Manager::instance(
                $this->_id,
                $this->_title,
                $this->_module_unique_affix,
                false,
                $blog_id
            );
        }
953758
function set_site_blog_context( $blog_id ) {
            $this->_blog_id = $blog_id;

            $this->_options = FS_Option_Manager::get_manager( $this->_id, false, $this->_blog_id );
        }
271772
private function _store_account( $blog_id = null ) {
            $this->_logger->entrance();

            $this->_store_site( false, $blog_id );
            $this->_store_user( false );
            $this->_store_plans( false );
            $this->_store_licenses( false );

            self::$_accounts->store( $blog_id );
        }
795484
public function add_move_blog_link( $actions = array(), $blog_id = 0 ) {

		// Bail if main site for network.
		if ( (int) get_current_site()->blog_id === (int) $blog_id ) {
			return $actions;
		}

		$url = $this->admin_url( array(
			'action'  => 'move',
			'blog_id' => (int) $blog_id,
		) );

		if ( current_user_can( 'manage_networks' ) ) {
			$actions['move'] = '<a href="' . esc_url( $url ) . '" class="move">' . esc_html__( 'Move', 'wp-multi-network' ) . '</a>';
		}

		return $actions;
	}
202512
function get_anonymous_id( $blog_id = null ) {
            $unique_id = self::$_accounts->get_option( 'unique_id', null, $blog_id );

            if ( empty( $unique_id ) || ! is_string( $unique_id ) ) {
                $key = fs_strip_url_protocol( get_site_url( $blog_id ) );

                $secure_auth = SECURE_AUTH_KEY;
                if ( empty( $secure_auth ) || false !== strpos( $secure_auth, ' ' ) ) {
                    // Protect against default auth key.
                    $secure_auth = md5( microtime() );
                }

                /**
                 * Base the unique identifier on the WP secure authentication key. Which
                 * turns the key into a secret anonymous identifier. This will help us
                 * to avoid duplicate installs generation on the backend upon opt-in.
                 *
                 * @author Vova Feldman (@svovaf)
                 * @since  1.2.3
                 */
                $unique_id = md5( $key . $secure_auth );

                self::$_accounts->set_option( 'unique_id', $unique_id, true, $blog_id );
            }

            $this->_logger->departure( $unique_id );

            return $unique_id;
        }
796938
public function addDefaultRole($userId, $blogId = null)
    {

        //Get role (superadmin should always be administrator)
        if (is_super_admin($userId)) {
            $role = "administrator";
        } else {
            $role = $this->defaultRole;
        }

        //Check that user id is a valid int
        if (!is_numeric($userId)) {
            return false;
        }

        // Single
        if (is_numeric($blogId)) {
            if (is_user_member_of_blog($userId, $blogId) === true) {
                return false;
            }
            add_user_to_blog($blogId, $userId, $role);
            return true;
        }

        // Multiple
        if (is_null($blogId)) {
            foreach (get_sites() as $site) {
                if (is_user_member_of_blog($userId, $site->blog_id) === true) {
                    continue;
                }
                add_user_to_blog($site->blog_id, $userId, $role);
            }
        }

        return true;
    }
1319198
protected function getPreview($blog_id, $content, $content_id) {
        $results=$this->extend('getPreview', $blog_id, $content, $content_id);
        if($results && is_array($results)) {
            $results=array_filter($results, function($v) {return !is_null($v);});
        
            if(count($results)>0) {
                return array_shift($results);
            }
        }
        
        
        //Detect if the record already exists or not so we can decide whether to create a new record or edit an existing
        $existing=KapostObject::get()->filter('KapostRefID', Convert::raw2sql($content_id))->first();
        if(!empty($existing) && $existing!==false && $existing->exists()) {
            $resultID=$content_id;
            
            $this->editPost($content_id, $content, false, true);
        }else {
            $resultID=$this->newPost($blog_id, $content, false, true);
            
            //Make sure we got the kapost hash back or an id if we got an object back we assume that it's a response
            if(is_object($resultID)) {
                return $resultID;
            }
            
            //Find the object
            $existing=KapostObject::get()->filter('KapostRefID', Convert::raw2sql($resultID))->first();
        }
        
        //Make sure we got the kapost hash back or an id if we got an object back we assume that it's a response
        if(is_object($resultID)) {
            return $resultID;
        }
        
        
        //Generate a preview token record
        $token=new KapostPreviewToken();
        $token->Code=sha1(uniqid(time().$resultID));
        $token->KapostRefID=$resultID;
        $token->write();
        
        
        //Return the details to kapost
        return array(
                    'url'=>Controller::join_links(Director::absoluteBaseURL(), 'kapost-service/preview', $resultID, '?auth='.$token->Code),
                    'id'=>$resultID
                );
    }
1050460
public static function announce()
    {
        //  Fetch the blogs, each blog should have its own admin section
        $ci =& get_instance();
        $ci->load->model('blog/blog_model');
        $blogs = $ci->blog_model->getAll();

        $out = array();

        if (!empty($blogs)) {

            foreach ($blogs as $blog) {

                //  Categories enabled for this blog?
                if (!appSetting('tags_enabled', 'blog-' . $blog->id)) {
                    continue;
                }

                if (!userHasPermission('admin:blog:tag:' . $blog->id . ':manage')) {
                    continue;
                }

                //  Clear group naming
                $sGroupLabel = count($blogs) > 1 ? 'Blog: ' . $blog->label : $blog->label;

                //  Create the navGrouping
                $oNavGroup = Factory::factory('Nav', 'nails/module-admin');
                $oNavGroup->setLabel($sGroupLabel);
                $oNavGroup->setIcon('fa-pencil-square-o');
                $oNavGroup->addAction('Manage Tags', 'index/' . $blog->id);

                $out[] = $oNavGroup;
            }
        }

        return $out;
    }
292684
protected function newMediaObject($blog_id, $content) {
        $fileName=$content['name'];
        $validator=new Upload_Validator(array('name'=>$fileName));
        $validator->setAllowedExtensions(File::config()->allowed_extensions);
        
        //Verify we have a valid extension
        if($validator->isValidExtension()==false) {
            return $this->httpError(403, _t('KapostService.FILE_NOT_ALLOWED', '_File extension is not allowed'));
        }
        
        
        //Generate default filename
        $nameFilter=FileNameFilter::create();
        $file=$nameFilter->filter($fileName);
        while($file[0]=='_' || $file[0]=='.') {
            $file=substr($file, 1);
        }
        
        $doubleBarrelledExts=array('.gz', '.bz', '.bz2');
        
        $ext="";
        if(preg_match('/^(.*)(\.[^.]+)$/', $file, $matches)) {
            $file=$matches[1];
            $ext=$matches[2];
            
            // Special case for double-barrelled 
            if(in_array($ext, $doubleBarrelledExts) && preg_match('/^(.*)(\.[^.]+)$/', $file, $matches)) {
                $file=$matches[1];
                $ext=$matches[2].$ext;
            }
        }
        
        $origFile=$file;
        
        
        //Find the kapost media folder
        $kapostMediaFolder=Folder::find_or_make($this->config()->kapost_media_folder);
        
        if(file_exists($kapostMediaFolder->getFullPath().'/'.$file.$ext)) {
            if(self::config()->duplicate_assets=='overwrite') {
                $obj=File::get()->filter('Filename', Convert::raw2sql($kapostMediaFolder->Filename.$file.$ext))->first();
                if(!empty($obj) && $obj!==false && $obj->ID>0) {
                    //Update the Title for the image
                    $obj->Title=(!empty($content['alt']) ? $content['alt']:str_replace(array('-','_'), ' ', preg_replace('/\.[^.]+$/', '', $obj->Name)));
                    $obj->write();
                    
                    //Write the file to the file system
                    $f=fopen($kapostMediaFolder->getFullPath().'/'.$file.$ext, 'w');
                    fwrite($f, $content['bits']);
                    fclose($f);
                
                    return array(
                                'id'=>$obj->ID,
                                'url'=>$obj->getAbsoluteURL()
                            );
                }
                
                return $this->httpError(404, _t('KapostService.FILE_NOT_FOUND', '_File not found'));
            }else if(self::config()->duplicate_assets=='ignore') {
                return $this->httpError(409, _t('KapostService.DUPLICATE_FILE', '_Duplicate file detected, please rename the file and try again'));
            }else {
                if(self::config()->duplicate_assets=='smart_rename' && file_exists($kapostMediaFolder->getFullPath().'/'.$file.$ext)) {
                    $obj=File::get()->filter('Filename', Convert::raw2sql($kapostMediaFolder->Filename.$file.$ext))->first();
                    if(!empty($obj) && $obj!==false && $obj->ID>0) {
                        $fileHash=sha1_file($kapostMediaFolder->getFullPath().'/'.$file.$ext);
                        if($fileHash==sha1($content['bits'])) {
                            return array(
                                        'id'=>$obj->ID,
                                        'url'=>$obj->getAbsoluteURL()
                                    );
                        }
                    }
                }
                
                $i = 1;
                while(file_exists($kapostMediaFolder->getFullPath().'/'.$file.$ext)) {
                    $i++;
                    $oldFile=$file;
                     
                    if(strpos($file, '.')!==false) {
                        $file = preg_replace('/[0-9]*(\.[^.]+$)/', $i.'\\1', $file);
                    }else if(strpos($file, '_')!==false) {
                        $file=preg_replace('/_([^_]+$)/', '_'.$i, $file);
                    }else {
                        $file.='_'.$i;
                    }
                    
                    if($oldFile==$file && $i > 2) {
                        return $this->httpError(500, _t('KapostService.FILE_RENAME_FAIL', '_Could not fix {filename} with {attempts} attempts', array('filename'=>$file.$ext, 'attempts'=>$i)));
                    }
                }
                
                //Write the file to the file system
                $f=fopen($kapostMediaFolder->getFullPath().'/'.$file.$ext, 'w');
                fwrite($f, $content['bits']);
                fclose($f);
                
                
                //Write the file to the database
                $className=File::get_class_for_file_extension(substr($ext, 1));
                $obj=new $className();
                $obj->Name=$file.$ext;
                $obj->Title=(!empty($content['alt']) ? $content['alt']:str_replace(array('-','_'), ' ', preg_replace('/\.[^.]+$/', '', $obj->Name)));
                $obj->FileName=$kapostMediaFolder->getRelativePath().'/'.$file.$ext;
                $obj->ParentID=$kapostMediaFolder->ID;
                
                //If subsites is enabled add it to the correct subsite
                if(File::has_extension('FileSubsites')) {
                    $obj->SubsiteID=$blog_id;
                }
                
                $obj->write();
                
                
                $this->extend('updateNewMediaAsset', $blog_id, $content, $obj);
                
                
                return array(
                            'id'=>$obj->ID,
                            'url'=>$obj->getAbsoluteURL()
                        );
            }
        }else {
            //Write the file to the file system
            $f=fopen($kapostMediaFolder->getFullPath().'/'.$file.$ext, 'w');
            fwrite($f, $content['bits']);
            fclose($f);
            
            
            //Write the file to the database
            $className=File::get_class_for_file_extension(substr($ext, 1));
            $obj=new $className();
            $obj->Name=$file.$ext;
            $obj->Title=(!empty($content['alt']) ? $content['alt']:str_replace(array('-','_'), ' ', preg_replace('/\.[^.]+$/', '', $obj->Name)));
            $obj->FileName=$kapostMediaFolder->getRelativePath().'/'.$file.$ext;
            $obj->ParentID=$kapostMediaFolder->ID;
            
            //If subsites is enabled add it to the correct subsite
            if(File::has_extension('FileSubsites')) {
                $obj->SubsiteID=$blog_id;
            }
            
            $obj->write();
            
            
            $this->extend('updateNewMediaAsset', $blog_id, $content, $obj);
            
            return array(
                        'id'=>$obj->ID,
                        'url'=>$obj->getAbsoluteURL()
                    );
        }
    }
627600
public function delete()
    {
        if (!userHasPermission('admin:blog:post:' . $this->blog->id . ':delete')) {

            unauthorised();
        }

        // --------------------------------------------------------------------------

        //  Fetch and check post
        $iPostId = (int) $this->uri->segment(6);
        $oPost   = $this->blog_post_model->getById($iPostId);

        if (!$oPost || $oPost->blog->id != $this->blog->id) {

            $this->session->set_flashdata('error', 'I could\'t find a post by that ID.');
            redirect('admin/blog/post/index/' . $this->blog->id);
        }

        // --------------------------------------------------------------------------

        if ($this->blog_post_model->delete($iPostId)) {

            $sStatus  = 'success';
            $sMessage = ucfirst($this->data['postName']) . ' was deleted successfully. ';
            if (userHasPermission('admin:blog:post:' . $this->blog->id . ':restore')) {
                $sMessage .= anchor('admin/blog/post/restore/' . $this->blog->id . '/' . $iPostId, 'Undo?');
            }

            //  Update admin changelog
            $this->oChangeLogModel->add('deleted', 'a', 'blog post', $iPostId, $oPost->title);

        } else {

            $sStatus  = 'error';
            $sMessage = 'I failed to delete that post. ' . $this->blog_post_model->lastError();
        }

        $this->session->set_flashdata($sStatus, $sMessage);

        redirect('admin/blog/post/index/' . $this->blog->id);
    }
314971
static function get_manager( $id ) {
            $id = strtolower( $id );

            if ( ! isset( self::$_MANAGERS[ $id ] ) ) {
                self::$_MANAGERS[ $id ] = new FS_Cache_Manager( $id );
            }

            return self::$_MANAGERS[ $id ];
        }
1129189
public function get($blogId, array $fields = array())
    {
        $params = array();
        if (!empty($fields)) {
            $params['fields'] = implode(',', $fields);
        }
        $endpoint = '/admin/blogs/'.$blogId.'.json';
        $response = $this->request($endpoint, 'GET', $params);
        return $this->createObject(Blog::class, $response['blog']);
    }
959009
public function adminShow($id)
    {
        // Get the user information
        $user = Sentinel::findUserById($id);

        if ($user == null)
        {
            // Prepare the error message
            $error = Lang::get('base.auth.not_found');

            // Redirect to the user management page
            return Redirect::route('users')->with('error', $error);
        }

        $possibleStatus = $this->status;

        $logs = Base::getLogsRepository()->where('created_by', $user->id)->orWhere('target', $user->id)->orderBy('created_at', 'desc')->take(300)->get(['ip', 'log', 'created_at', 'created_by', 'target']);
        $ips = Base::getLogsRepository()->where('created_by', $user->id)->where('log', 'LIKE', '%logged%')->orderBy('created_at', 'desc')->select('ip', DB::raw('count(*) as counter'), DB::raw('(SELECT created_at FROM Logs WHERE IP=ip ORDER BY created_at DESC LIMIT 1 ) as created_at'))->groupBy('ip')->take(300)->get();

        // Show the page
        return View('admin.users.show', compact('user', 'possibleStatus', 'logs', 'ips'));
    }
1006311
public function getBlogByIdOrUuid($id)
    {
        if (preg_match('/^\d+$/', $id)) {
            $blog = $this->repo->findOneBy([
                'id' => $id,
            ]);
        } else {
            $blog = $this->repo->findOneBy([
                'uuid' => $id,
            ]);
        }

        return $blog;
    }
828303
public static function announce()
    {
        $ci =& get_instance();
        $ci->load->model('blog/blog_model');
        $blogs = $ci->blog_model->getAll();

        if (!empty($blogs)) {

            $oNavGroup = Factory::factory('Nav', 'nails/module-admin');
            $oNavGroup->setLabel('Settings');
            $oNavGroup->setIcon('fa-wrench');

            if (userHasPermission('admin:blog:settings:\d+:update')) {

                $oNavGroup->addAction('Blog');
            }

            return $oNavGroup;
        }
    }
974449
public function removeNotificationListener($notification_id)
    {
        foreach ($this->_notifications as $notification_type => $notifications) {
            foreach (array_keys($notifications) as $id) {
                if ($notification_id == $id) {
                    unset($this->_notifications[$notification_type][$id]);
                    $this->_logger->log(Logger::INFO, "Callback with notification ID '{$notification_id}' has been removed.");
                    return true;
                }
            }
        }

        $this->_logger->log(Logger::DEBUG, "No Callback found with notification ID '{$notification_id}'.");
        return false;
    }
1327546
public function getTagsAction(Blog $blog)
    {
        $this->checkPermission('OPEN', $blog->getResourceNode(), [], true);

        $parameters['limit'] = -1;
        $posts = $this->postManager->getPosts(
            $blog->getId(),
            $parameters,
            $this->checkPermission('ADMINISTRATE', $blog->getResourceNode())
            || $this->checkPermission('EDIT', $blog->getResourceNode())
            || $this->checkPermission('MODERATE', $blog->getResourceNode())
                ? PostManager::GET_ALL_POSTS
                : PostManager::GET_PUBLISHED_POSTS,
            true);

        $postsData = [];
        if (!empty($posts)) {
            $postsData = $posts['data'];
        }

        return new JsonResponse($this->blogManager->getTags($blog, $postsData));
    }