Banner management screen.

@since 2.0.0
@access public
484393
public function Banner() {
      $this->Permission('Garden.Settings.Manage');
      $this->AddSideMenu('dashboard/settings/banner');
      $this->Title(T('Banner'));
      
      $Validation = new Gdn_Validation();
      $ConfigurationModel = new Gdn_ConfigurationModel($Validation);
      $ConfigurationModel->SetField(array(
         'Garden.HomepageTitle' => C('Garden.Title'),
         'Garden.Title',
         'Garden.Description'
         ));
      
      // Set the model on the form.
      $this->Form->SetModel($ConfigurationModel);

      // Get the current logo.
      $Logo = C('Garden.Logo');
      if ($Logo) {
         $Logo = ltrim($Logo, '/');
         // Fix the logo path.
         if (StringBeginsWith($Logo, 'uploads/'))
            $Logo = substr($Logo, strlen('uploads/'));
         $this->SetData('Logo', $Logo);
      }
      
      // Get the current favicon.
      $Favicon = C('Garden.FavIcon');
      $this->SetData('Favicon', $Favicon);
      
      $ShareImage = C('Garden.ShareImage');
      $this->SetData('ShareImage', $ShareImage);
      
      // If seeing the form for the first time...
      if (!$this->Form->AuthenticatedPostBack()) {
         // Apply the config settings to the form.
         $this->Form->SetData($ConfigurationModel->Data);
      } else {
         $SaveData = array();
         if ($this->Form->Save() !== FALSE) {
            $Upload = new Gdn_Upload();
            try {
               // Validate the upload
               $TmpImage = $Upload->ValidateUpload('Logo', FALSE);
               if ($TmpImage) {
                  // Generate the target image name
                  $TargetImage = $Upload->GenerateTargetName(PATH_UPLOADS);
                  $ImageBaseName = pathinfo($TargetImage, PATHINFO_BASENAME);
                  
                  // Delete any previously uploaded images.
                  if ($Logo)
                     $Upload->Delete($Logo);
                  
                  // Save the uploaded image
                  $Parts = $Upload->SaveAs(
                     $TmpImage,
                     $ImageBaseName
                  );
                  $ImageBaseName = $Parts['SaveName'];
                  $SaveData['Garden.Logo'] = $ImageBaseName;
                  $this->SetData('Logo', $ImageBaseName);
               }
               
               $ImgUpload = new Gdn_UploadImage();
               $TmpFavicon = $ImgUpload->ValidateUpload('Favicon', FALSE);
               if ($TmpFavicon) {
                  $ICOName = 'favicon_'.substr(md5(microtime()), 16).'.ico';

                  if ($Favicon)
                     $Upload->Delete($Favicon);

                  // Resize the to a png.
                  $Parts = $ImgUpload->SaveImageAs($TmpFavicon, $ICOName, 16, 16, array('OutputType' => 'ico', 'Crop' => TRUE));
                  $SaveData['Garden.FavIcon'] = $Parts['SaveName'];
                  $this->SetData('Favicon', $Parts['SaveName']);
               }
               
               $TmpShareImage = $Upload->ValidateUpload('ShareImage', FALSE);
               if ($TmpShareImage) {
                  $TargetImage = $Upload->GenerateTargetName(PATH_UPLOADS, FALSE);
                  $ImageBaseName = pathinfo($TargetImage, PATHINFO_BASENAME);
                  
                  if ($ShareImage)
                     $Upload->Delete($ShareImage);
                  
                  $Parts = $Upload->SaveAs($TmpShareImage, $ImageBaseName);
                  $SaveData['Garden.ShareImage'] = $Parts['SaveName'];
                  $this->SetData('ShareImage', $Parts['SaveName']);
                  
               }
            } catch (Exception $ex) {
               $this->Form->AddError($ex);
            }
            // If there were no errors, save the path to the logo in the config
            if ($this->Form->ErrorCount() == 0) {
               SaveToConfig($SaveData);
               
            }
            
            $this->InformMessage(T("Your settings have been saved."));
         }
      }
      
      $this->Render();      
   }
835822
protected function visitorScreenSetResolutions()
	{
	    $this->_SCREEN = array( "scrw"  => (int)\Input::get('scrw'),
                                "scrh"  => (int)\Input::get('scrh'),
                                "scriw" => (int)\Input::get('scriw'),
                                "scrih" => (int)\Input::get('scrih')
                                );
	    if ((int)\Input::get('scrw')  == 0 ||
	        (int)\Input::get('scrh')  == 0 ||
	        (int)\Input::get('scriw') == 0 ||
	        (int)\Input::get('scrih') == 0
	    )
	    {
	        ModuleVisitorLog::writeLog(__METHOD__ ,
                            	        __LINE__ ,
                            	        'ERR: '.print_r(array( "scrw"  => \Input::get('scrw'),
                                                    	       "scrh"  => \Input::get('scrh'),
                                                    	       "scriw" => \Input::get('scriw'),
                                                    	       "scrih" => \Input::get('scrih')
                                                	        ), true)
                        	        );
	        $this->_SCREEN = false;
	    }
	}
1102932
protected function bannerHelperInit()
	{
	    //Fix the planet
	    $this->statusRandomBlocker           = false;
	    $this->statusFirstViewBlocker        = false;
	    $this->statusBannerFirstView         = false;
	    $this->statusBannerFrontendGroupView = true;
	    $this->statusAllBannersBasic         = true;
	    $this->arrCategoryValues             = array();
	    $this->arrAllBannersBasic            = array();
		
		//set $arrCategoryValues over tl_banner_category
		if ($this->getSetCategoryValues() === false) { return false; }
		
		//check for protected user groups
		//set $statusBannerFrontendGroupView
		$this->checkSetUserFrontendLogin();
		
		//get basic banner infos (id,weighting) in $this->arrAllBannersBasic
		if ($this->getSetAllBannerForCategory() === false) 
		{
			$this->statusAllBannersBasic = false;
		}
		
		//ModuleBannerTag->outputFormat
		if ($this->outputFormat == 'html5')
		{
		    $this->strFormat = 'html5';
		}
		//DEBUG log_message('bannerHelperInit this->outputFormat:'.$this->outputFormat,'Banner.log');
		 
		if (!isset($GLOBALS['objPage'])) 
		{
			$objPage = new \stdClass();
			$objPage->templateGroup = $this->templatepfad;
			$objPage->outputFormat = $this->outputFormat;
			$GLOBALS['objPage'] = $objPage;
		}
		
	}
918197
public function adminRender()
	{
		$this->root = 'data/';

		$this->panels['l'] = (arg('lf')?preg_replace('!^/|/$!','',arg('lf')).'/':'');
		$this->panels['l'] = preg_replace('~(/\.\.|^\.\./)~', '', $this->panels['l']);
		$this->panels['l'] = preg_replace('!^/!', '', $this->panels['l']);
		while (!empty($this->panels['l'])
			&& !is_dir(Eresus_CMS::getLegacyKernel()->froot.$this->root.$this->panels['l']))
		{
			$this->panels['l'] = preg_replace('![^/]+/$!', '', $this->panels['l']);
		}
		$this->panels['r'] = (arg('rf')?preg_replace('!^/|/$!','',arg('rf')).'/':'');
		$this->panels['r'] = preg_replace('~(/\.\.|^\.\./)~', '', $this->panels['r']);
		$this->panels['r'] = preg_replace('!^/!', '', $this->panels['r']);
		while (!empty($this->panels['r'])
			&& !is_dir(Eresus_CMS::getLegacyKernel()->froot.$this->root.$this->panels['r']))
		{
			$this->panels['r'] = preg_replace('![^/]+/$!', '', $this->panels['r']);
		}
		$this->sp = substr(arg('sp', '/[^lr]/'), 0, 1);
		if (!$this->sp)
		{
			$this->sp = 'l';
		}
		if (count($_FILES))
		{
			$this->upload();
		}
		elseif (arg('mkdir'))
		{
			$this->mkDir();
		}
		elseif (arg('rename'))
		{
			$this->renameEntry();
		}
		elseif (arg('chmod'))
		{
			$this->chmodEntry();
		}
		elseif (arg('copyfile'))
		{
			$this->copyFile();
		}
		elseif (arg('movefile'))
		{
			$this->moveFile();
		}
		elseif (arg('delete'))
		{
			$this->deleteFile();
		}
		else
		{
			$root = Eresus_CMS::getLegacyKernel()->root;
			Eresus_Kernel::app()->getPage()->
				linkScripts($root . 'core/files.js');
			$result =
				"<table id=\"fileManager\">\n" .
					'<tr><td colspan="2" class="filesMenu">' . $this->renderMenu() . "</td></tr>\n" .
					'<tr><td colspan="2" class="filesControls">' . $this->renderControls() . "</td></tr>" .
					'<tr>' .
					'<td valign="top" class="filesPanel">' . $this->renderFileList('l') . "</td>\n" .
					'<td valign="top" class="filesPanel">' . $this->renderFileList('r') . "</td>\n" .
					"</tr>\n" .
					'<tr><td colspan="2" class="filesControls">' . $this->renderStatus() . "</td></tr>" .
					"</table>" .
					"<script type=\"text/javascript\"><!--\n" .
					" filesInit('" . $root . $this->root . "', '" . $this->sp . "');\n" .
					"--></script>\n";
			return $result;
		}
		return '';
	}
413818
private function setup_pages() {

		$args                 = array(
			'capability' => 'manage_options',
			'icon'       => null,
			'position'   => null,
		);
		$this->struct['args'] = array_merge( $args, $this->struct );

		if ( ! isset( $this->struct['parent'] ) ) {
			add_action( 'admin_menu', array( $this, 'add_settings_page' ), 9 );
		} else {
			add_action( 'admin_menu', array( $this, 'add_sub_page' ), 9 );
		}

	}
1356142
public function viewPage()
    {
        $page = isset($_GET['sub']) ? (string)$_GET['sub'] : self::DEFAULT_SUB_PAGE;
        View::page('admin/' . $page);
    }
642594
public function save(Banners_Banner_Abstract $banner)
    {
        $q = DB::createUpdateQuery();
        $q->update('banners')->
            set('caption', $q->bindValue($banner->getCaption(), null, PDO::PARAM_STR))->
            set('active', $q->bindValue($banner->getActive(), null, PDO::PARAM_BOOL))->
            set('section', $q->bindValue($banner->getSectionStr(), null, PDO::PARAM_STR))->
            set('priority', $q->bindValue($banner->getPriority(), null, PDO::PARAM_INT))->
            set('block', $q->bindValue($banner->getBlock(), null, PDO::PARAM_STR))->
            set('showFrom', $q->bindValue($banner->getShowFrom(), null, PDO::PARAM_STR))->
            set('showTill', $q->bindValue($banner->getShowTill(), null, PDO::PARAM_STR))->
            set('showCount', $q->bindValue($banner->getShowCount(), null, PDO::PARAM_INT))->
            set('html', $q->bindValue($banner->getHTML(), null, PDO::PARAM_STR))->
            set('image', $q->bindValue($banner->getImage(), null, PDO::PARAM_STR))->
            set('width', $q->bindValue($banner->getWidth(), null, PDO::PARAM_STR))->
            set('height', $q->bindValue($banner->getHeight(), null, PDO::PARAM_STR))->
            set('url', $q->bindValue($banner->getURL(), null, PDO::PARAM_STR))->
            set('target', $q->bindValue($banner->getTargetIsBlank(), null, PDO::PARAM_BOOL))->
            set('shows', $q->bindValue($banner->getShows(), null, PDO::PARAM_INT))->
            set('clicks', $q->bindValue($banner->getClicks(), null, PDO::PARAM_INT))->
            where($q->expr->eq('id', $q->bindValue($banner->getId(), null, PDO::PARAM_INT)));
        DB::execute($q);
    }
712339
protected function _layoutBadge()
    {
        $context->commands = $this->getTemplate()->renderHelper('toolbar.commands', 'toolbar');

        $this->set(array(
            'commands' => $context->commands,
        ));
    }
534942
public function index() {
        
        $tree = Globals::getTree();
        Theme::theme(new AdministrationTheme)->init($tree);
        $controller = new PageController();
        $controller
            ->restrictAccess(Auth::isAdmin())
            ->setPageTitle($this->module->getTitle());
			
		$token = $this->module->getSetting('MAJ_AT_FORCE_EXEC_TOKEN');
		if(is_null($token)) {
			$token = Functions::generateRandomToken();
			$this->module->setSetting('PAT_FORCE_EXEC_TOKEN', $token);
		}
        
        $data = new ViewBag();
        $data->set('title', $controller->getPageTitle());
        
        $table_id = 'table-admintasks-' . Uuid::uuid4();
        $data->set('table_id', $table_id);
		
		$data->set('trigger_url_root', WT_BASE_URL.'module.php?mod='.$this->module->getName().'&mod_action=Task@trigger');
		$token = $this->module->getSetting('MAJ_AT_FORCE_EXEC_TOKEN');
		if(is_null($token)) {
			$token = Functions::generateRandomToken();
			$this->module->setSetting('MAJ_AT_FORCE_EXEC_TOKEN', $token);
		}
		$data->set('trigger_token', $token);
		
		$this->provider->getInstalledTasks();
		
		$controller
            ->addExternalJavascript(WT_JQUERY_DATATABLES_JS_URL)
            ->addExternalJavascript(WT_DATATABLES_BOOTSTRAP_JS_URL)
            ->addInlineJavascript('
                //Datatable initialisation
				jQuery.fn.dataTableExt.oSort["unicode-asc"  ]=function(a,b) {return a.replace(/<[^<]*>/, "").localeCompare(b.replace(/<[^<]*>/, ""))};
				jQuery.fn.dataTableExt.oSort["unicode-desc" ]=function(a,b) {return b.replace(/<[^<]*>/, "").localeCompare(a.replace(/<[^<]*>/, ""))};
				jQuery.fn.dataTableExt.oSort["num-html-asc" ]=function(a,b) {a=parseFloat(a.replace(/<[^<]*>/, "")); b=parseFloat(b.replace(/<[^<]*>/, "")); return (a<b) ? -1 : (a>b ? 1 : 0);};
				jQuery.fn.dataTableExt.oSort["num-html-desc"]=function(a,b) {a=parseFloat(a.replace(/<[^<]*>/, "")); b=parseFloat(b.replace(/<[^<]*>/, "")); return (a>b) ? -1 : (a<b ? 1 : 0);};
	
				var adminTasksTable = jQuery("#'.$table_id.'").DataTable({
					'.I18N::datatablesI18N().',			
					sorting: [[3, "asc"]],
					pageLength: 10,
                    processing: true,
                    serverSide : true,
					ajax : {
						url : "module.php?mod='.$this->module->getName().'&mod_action=AdminConfig@jsonTasksList&ged='. $tree->getNameUrl().'",
                        type : "POST"
					},
                    columns: [
						/* 0 Edit		 	*/ { sortable: false, className: "text-center"},
                        /* 1 task_name      */ { visible: false },
						/* 2 Enabled 		*/ { sortable: false, className: "text-center"  },
						/* 3 Task Title		*/ null,
						/* 4 Last Run		*/ null,
						/* 5 Last status 	*/ { className: "text-center" },
						/* 6 Frequency      */ { sortable: false, className: "text-center" },
						/* 7 Nb Occcurrences*/ { sortable: false, className: "text-center" },
						/* 8 Is Running    	*/ { sortable: false, className: "text-center" },					
						/* 9 Run task		*/ { sortable: false, className: "text-center" }
					],
				});
                
                ')
                ->addInlineJavascript('					
					function generate_force_token() {
						jQuery("#bt_genforcetoken").attr("disabled", "disabled");
						jQuery("#bt_tokentext").empty().html("<i class=\"fa fa-spinner fa-pulse fa-fw\"></i>");
						jQuery("#token_url").load(
							"module.php?mod='.$this->module->getName().'&mod_action=AdminConfig@generateToken",
							function() {
								jQuery("#bt_genforcetoken").removeAttr("disabled");
								jQuery("#bt_tokentext").empty().html("'.I18N::translate('Regenerate token').'");
                                adminTasksTable.ajax.reload();
							}
						);
					}
				
                    function set_admintask_status(task, status) {
                		jQuery.ajax({
                            url: "module.php", 
                            type: "GET",
                            data: {
                			    mod: "' . $this->module->getName() .'",
                                mod_action:  "Task@setStatus",
                			    task: task,
                                status: status
                            },
                            error: function(result, stat, error) {
                                var err = typeof result.responseJSON === "undefined" ? error : result.responseJSON.error;
                                alert("' . I18N::translate('An error occured while editing this task:') . '" + err);
                            },
                            complete: function(result, stat) {
                                adminTasksTable.ajax.reload(null, false);
                            }                            
                		});
                    } 
                    
                    function run_admintask(taskname) {
                        jQuery("#bt_runtask_" + taskname).attr("disabled", "disabled");
				        jQuery("#bt_runtasktext_" + taskname).empty().html("<i class=\"fa fa-cog fa-spin fa-fw\"></i><span class=\"sr-only\">'.I18N::translate('Running').'</span>");
				        jQuery("#bt_runtasktext_" + taskname).load(
					       "module.php?mod='.$this->module->getName().'&mod_action=Task@trigger&force='.$token.'&task=" + taskname,
        					function() {
        						jQuery("#bt_runtasktext_" + taskname).empty().html("<i class=\"fa fa-check\"></i>'.I18N::translate('Done').'");
        						adminTasksTable.ajax.reload();
        					}
				        );
                    
                    } 
                ');
        
        ViewFactory::make('AdminConfig', $this, $controller, $data)->render();
    }
356267
public function actionAdd() 
	{
		$setting = BannerSetting::model()->findByPk(1, array(
			'select' => 'banner_file_type',
		));
		$banner_file_type = unserialize($setting->banner_file_type);
		if(empty($banner_file_type))
			$banner_file_type = array();
		
		$model=new Banners;

		// Uncomment the following line if AJAX validation is needed
		$this->performAjaxValidation($model);

		if(isset($_POST['Banners'])) {
			$model->attributes=$_POST['Banners'];

			if($model->save()) {
				Yii::app()->user->setFlash('success', Yii::t('phrase', 'Banner success created.'));
				$this->redirect(array('manage'));
			}
		}

		$this->pageTitle = Yii::t('phrase', 'Create Banner');
		$this->pageDescription = '';
		$this->pageMeta = '';
		$this->render('admin_add', array(
			'model'=>$model,
			'banner_file_type'=>$banner_file_type,
		));
	}
160134
public function display()
    {
        if (!$this->visible) {
            return;
        }

        parent::display();

        $count = count($this);
        $i = 1;

        $container_tag = $this->getContainerTag();
        $container_tag->open();

        foreach ($this->entries as $entry) {
            // display separator
            if ($i > 1) {
                echo SwatString::minimizeEntities($this->separator);
            }

            // link all entries or link all but the last entry
            $link = $this->link_last_entry || $i < $count;

            $this->displayEntry($entry, $link, $i === 1);

            $i++;
        }

        $container_tag->close();
    }
1173959
public function adminBar()
    {
        if (isset($_GET['id'])) {
            if (is_numeric($_GET['id']) && $_GET['id'] > 0) {
                $post = get_post($_GET['id']);

                if (!$post) {
                    return;
                }

                setup_postdata($post);

                add_action('admin_bar_menu', function () use ($post) {
                    global $wp_admin_bar;
                    $wp_admin_bar->add_node(array(
                        'id' => 'view_page',
                        'title' => __('View Page'),
                        'href' => get_permalink($post->ID),
                        'meta' => array(
                            'target' => '_blank'
                        )
                    ));
                }, 1050);

                self::$isEditing = array(
                    'id' => $post->ID,
                    'title' => $post->post_title
                );

                wp_reset_postdata();
            } else {
                global $archive;
                $archive = $_GET['id'];

                self::$isEditing = array(
                    'id' => null,
                    'title' => $archive
                );
            }

            self::$isEditing = apply_filters('Modularity/is_editing', self::$isEditing);

            add_action('Modularity/options_page_title_suffix', function () {
                echo ': ' . self::$isEditing['title'];
            });
        }
    }
66571
private function setUpLayout()
    {
        if (Layout::filename()) {
            return;
        }

        Layout::filename('layout' . $this->divisionPostfix . '.php');

        Layout::addJsMgr('layout' . ($this->_division === '' ? '' : '_' . $this->_division));
        Layout::addCss('layout' . $this->divisionPostfix . '.css');

        $fileBaseName = $this->_module . '_' . $this->_method;
        // add default js manager
        $jsPath   = $this->divisionPath . '/js/managers/';
        $jsName   = $this->divisionPrefix . $fileBaseName;
        $fileName = MODULES . $jsPath . $jsName . '_mgr.js';
        if (file_exists($fileName)) {
            Layout::addJsMgr($jsName, MOD . $jsPath);
        }

        // add default css
        $cssPath  = $this->divisionPath . '/css/';
        $cssName  = $this->divisionPrefix . $fileBaseName . '.css';
        $fileName = MODULES . $cssPath . $cssName;
        if (file_exists($fileName)) {
            Layout::addCss($cssName, MOD . $cssPath);
        }
    }
1190555
public function display()
    {
        \OWeb\manage\Events::getInstance()->sendEvent('DisplayContent_Start@OWeb\manage\Template');
        echo $this->content;
        \OWeb\manage\Events::getInstance()->sendEvent('DisplayContent_End@OWeb\manage\Template');
    }
1018943
public function getCMSFields()
    {
        $fields = parent::getCMSFields();

        $bannerGridConfig = GridFieldConfig_RelationEditor::create();
        if ($this->Banners()->Count() > 0) {
            $bannerGridConfig->addComponent(new GridFieldOrderableRows());
        }

        $fields->addFieldToTab(
            'Root.Main',
            GridField::create(
                'Banners',
                'Banner',
                $this->Banners(),
                $bannerGridConfig
            )
        );

        $this->extend('updateCMSFields', $fields);

        return $fields;
    }
211479
public function display()
    {
        if (!$this->visible) {
            return;
        }

        parent::display();

        $div_tag = new SwatHtmlTag('div');
        $div_tag->id = $this->id;
        $div_tag->class = $this->getCSSClassString();
        $div_tag->open();

        echo '<span class="swat-date-entry-span">';

        foreach ($this->getDatePartOrder() as $datepart) {
            if ($datepart == 'd' && $this->display_parts & self::DAY) {
                $day_flydown = $this->getCompositeWidget('day_flydown');

                if ($day_flydown->value === null && $this->value !== null) {
                    $day_flydown->value = $this->value->getDay();
                }

                $day_flydown->display();
            } elseif ($datepart == 'm' && $this->display_parts & self::MONTH) {
                $month_flydown = $this->getCompositeWidget('month_flydown');

                if ($month_flydown->value === null && $this->value !== null) {
                    $month_flydown->value = $this->value->getMonth();
                }

                $month_flydown->display();
            } elseif ($datepart == 'y' && $this->display_parts & self::YEAR) {
                $year_flydown = $this->getCompositeWidget('year_flydown');

                if ($year_flydown->value === null && $this->value !== null) {
                    $year_flydown->value = $this->value->getYear();
                }

                $year_flydown->display();
            }
        }

        echo '</span>';

        if ($this->display_parts & self::CALENDAR) {
            $calendar = $this->getCompositeWidget('calendar');
            $calendar->display();
        }

        if ($this->display_parts & self::TIME) {
            $time_entry = $this->getCompositeWidget('time_entry');

            // if we aren't using the current date then we won't use the
            // current time
            if (!$this->use_current_date) {
                $time_entry->use_current_time = false;
            }

            echo ' ';
            if ($time_entry->value === null && $this->value !== null) {
                $time_entry->value = $this->value;
            }

            $time_entry->display();
        }

        Swat::displayInlineJavaScript($this->getInlineJavaScript());

        $div_tag->close();
    }
52136
function _getScreen()
    {
        $output = '';
        $last_attr = $this->base_attr_cell;
        for ($i = 0; $i <= $this->max_y; $i++) {
            for ($j = 0; $j <= $this->max_x; $j++) {
                $cur_attr = $this->attrs[$i][$j];
                $output.= $this->_processCoordinate($last_attr, $cur_attr, isset($this->screen[$i][$j]) ? $this->screen[$i][$j] : '');
                $last_attr = $this->attrs[$i][$j];
            }
            $output.= "\r\n";
        }
        $output = substr($output, 0, -2);
        // close any remaining open tags
        $output.= $this->_processCoordinate($last_attr, $this->base_attr_cell, '');
        return rtrim($output);
    }