    public function testGetFilteredEventsDataProvider () {
        TestingAuxLib::loadX2NonWebUser ();
        TestingAuxLib::suLogin ('testuser');
        Yii::app()->settings->historyPrivacy = null;
        $profile = Profile::model()->findByAttributes(array('username' => 'testuser'));
        $retVal = Events::getFilteredEventsDataProvider ($profile, true, null, false);
        $dataProvider = $retVal['dataProvider'];
        $events = $dataProvider->getData ();
        $expectedEvents = Events::getEvents (0, 0, count ($events), $profile);

        // verify events from getData
        $this->assertEquals (
            Yii::app()->db->createCommand ("
                select id
                from x2_events
                where user='testuser' or visibility
                order by timestamp desc, id desc
            ")->queryColumn (),
            array_map (
                function ($event) { return $event->id; },
                $expectedEvents['events']
            )
        );

        // ensure that getFilteredEventsDataProvider returns same events as getData
        $this->assertEquals (
            array_map (
                function ($event) { return $event->id; },
                $expectedEvents['events']
            ),
            array_map (
                function ($event) { return $event->id; },
                $events
            )
        );
        TestingAuxLib::restoreX2WebUser ();
    }


    protected function tearDown()
    {
        static::$functions = [];
        static::$fopen = null;
        static::$fread = null;
        parent::tearDown();
    }


    public function fetchRow($sql)
    {
        // retrieve row
        $query_id = $this->query($sql);

        $record = mysql_fetch_row($this->query_id);

        $this->freeResult($query_id);

        return $record;
    }#-#fetchArray()


    public function update()
    {
        $project = $this->getProject();

        $values = $this->request->getValues();
        list($valid, $errors) = $this->swimlaneValidator->validateModification($values);

        if ($valid) {
            if ($this->swimlaneModel->update($values['id'], $values)) {
                $this->flash->success(t('Swimlane updated successfully.'));
                return $this->response->redirect($this->helper->url->to('SwimlaneController', 'index', array('project_id' => $project['id'])));
            } else {
                $errors = array('name' => array(t('Another swimlane with the same name exists in the project')));
            }
        }

        return $this->edit($values, $errors);
    }


function db_properties($table)
{
	global $DatabaseType, $DatabaseUsername;

	switch ($DatabaseType) {
		case 'mysqli':
			$result = DBQuery("SHOW COLUMNS FROM $table");
			while ($row = db_fetch_row($result)) {
				$properties[strtoupper($row['FIELD'])]['TYPE'] = strtoupper($row['TYPE'], strpos($row['TYPE'], '('));
				if (!$pos = strpos($row['TYPE'], ','))
					$pos = strpos($row['TYPE'], ')');
				else
					$properties[strtoupper($row['FIELD'])]['SCALE'] = substr($row['TYPE'], $pos + 1);

				$properties[strtoupper($row['FIELD'])]['SIZE'] = substr($row['TYPE'], strpos($row['TYPE'], '(') + 1, $pos);

				if ($row['NULL'] != '')
					$properties[strtoupper($row['FIELD'])]['NULL'] = "Y";
				else
					$properties[strtoupper($row['FIELD'])]['NULL'] = "N";
			}
			break;
	}
	return $properties;
}


    function reset_stats() {
//        global $db;

        // reset the counters
//        $db->sql ('UPDATE '.$db->prefix.'banner SET impressions=0 WHERE 1');
        banner::resetImpressions();
//        $db->sql ('UPDATE '.$db->prefix.'banner SET clicks=0 WHERE 1');
        banner::resetClicks();

        // let the user know we did stuff.
        flash('message', gt("Banner statistics reset."));
        expHistory::back();
    }


    public function confirm()
    {
        $project = $this->getProject();
        $category = $this->getCategory();

        $this->response->html($this->helper->layout->project('category/remove', array(
            'project'  => $project,
            'category' => $category,
        )));
    }


                foreach ($grpusers as $u) {
                    $emails[$u->email] = trim(user::getUserAttribution($u->id));
                }


function phoromatic_error_page($title, $description)
{
	echo phoromatic_webui_header(array(''), '');

	$box = '
' . $title . '

' . $description . '

To fix this error, try returning to the previous page. Still having problems? Consider opening a GitHub issue report; commercial support customers should contact Phoronix Media.

';
	echo phoromatic_webui_box($box);
	echo phoromatic_webui_footer();
}


					$tableBody[] = array($row['label'], $row['nb_visits'], $row['bounce_rate']);
					if ($count == 10) break;
				}
				$this->table($tableHead, $tableBody, null);
			}
		}


	public function beforeFilter() { // TODO REMOVE
		parent::beforeFilter();
		$this->Security->unlockedActions = array('saveElementSorting', 'populateEventFromTemplate', 'uploadFile', 'deleteTemporaryFile');
	}


function twig_array_reduce(Environment $env, $array, $arrow, $initial = null)
{
    if (!$arrow instanceof Closure && $env->hasExtension('\Twig\Extension\SandboxExtension') && $env->getExtension('\Twig\Extension\SandboxExtension')->isSandboxed()) {
        throw new RuntimeError('The callable passed to the "reduce" filter must be a Closure in sandbox mode.');
    }

    if (!\is_array($array)) {
        if (!$array instanceof \Traversable) {
            throw new RuntimeError(sprintf('The "reduce" filter only works with arrays or "Traversable", got "%s" as first argument.', \gettype($array)));
        }

        $array = iterator_to_array($array);
    }

    return array_reduce($array, $arrow, $initial);
}


							 * function my_query_args_filter( $field_query ) {
							 *     // your code here
							 *     return $field_query;
							 * }


    public function remove()
    {
        $project = $this->getProject();
        $this->checkCSRFParam();
        $column_id = $this->request->getIntegerParam('column_id');

        if ($this->columnModel->remove($column_id)) {
            $this->flash->success(t('Column removed successfully.'));
        } else {
            $this->flash->failure(t('Unable to remove this column.'));
        }

        $this->response->redirect($this->helper->url->to('ColumnController', 'index', array('project_id' => $project['id'])));
    }


    public function saveConfig() {
        if (!empty($this->params['aggregate']) || !empty($this->params['pull_rss'])) {
            if ($this->params['order'] == 'rank ASC') {
                expValidator::failAndReturnToForm(gt('User defined ranking is not allowed when aggregating or pull RSS data feeds.'), $this->params);
            }
        }

        parent::saveConfig();
    }


$f = function (\Symfony\Component\DependencyInjection\Tests\Fixtures\TestServiceSubscriber $v) { return $v; }; return $f(${($_ = isset($this->services['Symfony\Component\DependencyInjection\Tests\Fixtures\TestServiceSubscriber']) ? $this->services['Symfony\Component\DependencyInjection\Tests\Fixtures\TestServiceSubscriber'] : ($this->services['Symfony\Component\DependencyInjection\Tests\Fixtures\TestServiceSubscriber'] = new \Symfony\Component\DependencyInjection\Tests\Fixtures\TestServiceSubscriber())) && false ?: '_'});


    public function getIterator()
    {
        @trigger_error('The '.__METHOD__.' method is deprecated since version 2.4 and will be removed in 3.0.', E_USER_DEPRECATED);

        return new \ArrayIterator($this->all());
    }


    public function getUpcoming(){
        $url = "http://api.themoviedb.org/3/movie/upcoming?api_key=".$this->apikey;
        $upcoming = $this->curl($url);
        return $upcoming;
    }


    function update() {
        parent::update();
        expSession::clearAllUsersSessionCache('navigation');
    }


function csrf_get_tokens()
{
    $has_cookies = !empty($_COOKIE);

    // $ip implements a composite key, which is sent if the user hasn't sent
    // any cookies. It may or may not be used, depending on whether or not
    // the cookies "stick"
    $secret = csrf_get_secret();
    if (!$has_cookies && $secret) {
        // :TODO: Harden this against proxy-spoofing attacks
        $ip = ';ip:' . csrf_hash($_SERVER['IP_ADDRESS']);
    } else {
        $ip = '';
    }
    csrf_start();

    // These are "strong" algorithms that don't require per se a secret
    if (session_id()) {
        return 'sid:' . csrf_hash(session_id()) . $ip;
    }
    if ($GLOBALS['csrf']['cookie']) {
        $val = csrf_generate_secret();
        setcookie($GLOBALS['csrf']['cookie'], $val);
        return 'cookie:' . csrf_hash($val) . $ip;
    }
    if ($GLOBALS['csrf']['key']) {
        return 'key:' . csrf_hash($GLOBALS['csrf']['key']) . $ip;
    }
    // These further algorithms require a server-side secret
    if (!$secret) {
        return 'invalid';
    }
    if ($GLOBALS['csrf']['user'] !== false) {
        return 'user:' . csrf_hash($GLOBALS['csrf']['user']);
    }
    if ($GLOBALS['csrf']['allow-ip']) {
        return ltrim($ip, ';');
    }
    return 'invalid';
}


static function description() { return gt("Places navigation links/menus on the page."); }


            } elseif (!empty($this->params['src'])) {
                if ($this->params['src'] == $loc->src) {
                    $this->config = $config->config;
                    break;
                }
            }
        }


    public function show()
    {
        $task = $this->getTask();
        $subtask = $this->getSubtask();

        $this->response->html($this->template->render('subtask_restriction/show', array(
            'status_list' => array(
                SubtaskModel::STATUS_TODO => t('Todo'),
                SubtaskModel::STATUS_DONE => t('Done'),
            ),
            'subtask_inprogress' => $this->subtaskStatusModel->getSubtaskInProgress($this->userSession->getId()),
            'subtask' => $subtask,
            'task' => $task,
        )));
    }


    public function showall() {
        global $user, $sectionObj, $sections;

        expHistory::set('viewable', $this->params);
        $id      = $sectionObj->id;
        $current = null;
        // all we need to do is determine the current section
        $navsections = $sections;
        if ($sectionObj->parent == -1) {
            $current = $sectionObj;
        } else {
            foreach ($navsections as $section) {
                if ($section->id == $id) {
                    $current = $section;
                    break;
                }
            }
        }
        assign_to_template(array(
            'sections'     => $navsections,
            'current'      => $current,
            'canManage'    => ((isset($user->is_acting_admin) && $user->is_acting_admin == 1) ? 1 : 0),
        ));
    }


function clean_input_value($value) {
    if (is_string($value)) {
        return descript($value);
    }
    if (is_array($value)) {
        return array_map('descript', $value);
    }
    return '';
}


	public function authenticate_by_email($website, $email, $password)
    {
        global $DB;

        // find the webuser username assigned to an email address
        // because it may exist more than one account with the same email,
        // only the first _created_ will be used

        $username = $DB->query_single(
            'username',
            'nv_webusers',
            'website = '.intval($website).' AND email = '.protect($email)
        );

        if(empty($username))
            return false;

        return $this->authenticate($website, $username, $password);
    }


function VerifyFixedSchedule($columns,$columns_var,$update=false)
{

    $qr_teachers=  DBGet(DBQuery('select TEACHER_ID,SECONDARY_TEACHER_ID from course_periods where course_period_id=\''.$_REQUEST['course_period_id'].'\''));
    $teacher=($_REQUEST['tables']['course_periods'][$_REQUEST['course_period_id']]['TEACHER_ID']!=''?$_REQUEST['tables']['course_periods'][$_REQUEST['course_period_id']]['TEACHER_ID']:$qr_teachers[1]['TEACHER_ID']);
    $secteacher=($_REQUEST['tables']['course_periods'][$_REQUEST['course_period_id']]['SECONDARY_TEACHER_ID']!=''?$_REQUEST['tables']['course_periods'][$_REQUEST['course_period_id']]['SECONDARY_TEACHER_ID']:$qr_teachers[1]['SECONDARY_TEACHER_ID']);
//    $secteacher=$qr_teachers[1]['SECONDARY_TEACHER_ID'];

    if($_REQUEST['tables']['course_periods'][$_REQUEST['course_period_id']]['TEACHER_ID']!='')
     $all_teacher=$teacher.($secteacher!=''?','.$secteacher:'');


    public function __construct(BufferingLogger $bootstrappingLogger = null)
    {
        if ($bootstrappingLogger) {
            $this->bootstrappingLogger = $bootstrappingLogger;
            $this->setDefaultLogger($bootstrappingLogger);
        }
        $this->traceReflector = new \ReflectionProperty('Exception', 'trace');
        $this->traceReflector->setAccessible(true);
    }


    public static function navtojson() {
        return json_encode(self::navhierarchy());
    }


    function showallSubcategories() {
//        global $db;

        expHistory::set('viewable', $this->params);
//        $parent = isset($this->params['cat']) ? $this->params['cat'] : expSession::get('catid');
        $catid = expSession::get('catid');
        $parent = !empty($catid) ? $catid : (!empty($this->params['cat']) ? $this->params['cat'] : 0);
        $category = new storeCategory($parent);
        $categories = $category->getEcomSubcategories();
        $ancestors = $category->pathToNode();
        assign_to_template(array(
            'categories' => $categories,
            'ancestors'  => $ancestors,
            'category'   => $category
        ));
    }


	public function newModel() {
		return new APIModel('testuser','5f4dcc3b5aa765d61d8327deb882cf99',rtrim(TEST_BASE_URL,'/'));
	}


    public function getBranches()
    {
        if (null === $this->branches) {
            $branches = array();

            $this->process->execute('git branch --no-color --no-abbrev -v', $output, $this->repoDir);
            foreach ($this->process->splitLines($output) as $branch) {
                if ($branch && !Preg::isMatch('{^ *[^/]+/HEAD }', $branch)) {
                    if (Preg::isMatch('{^(?:\* )? *(\S+) *([a-f0-9]+)(?: .*)?$}', $branch, $match)) {
                        $branches[$match[1]] = $match[2];
                    }
                }
            }

            $this->branches = $branches;
        }

        return $this->branches;
    }


    function reparent_standalone() {
        $standalone = $this->section->find($this->params['page']);
        if ($standalone) {
            $standalone->parent = $this->params['parent'];
            $standalone->update();
            expSession::clearAllUsersSessionCache('navigation');
            expHistory::back();
        } else {
            notfoundController::handle_not_found();
        }
    }


    function manage() {
        global $db, $router, $user;

        expHistory::set('manageable', $router->params);
        assign_to_template(array(
            'canManageStandalones' => self::canManageStandalones(),
            'sasections'           => $db->selectObjects('section', 'parent=-1'),
            'user'                 => $user,
//            'canManagePagesets'    => $user->isAdmin(),
//            'templates'            => $db->selectObjects('section_template', 'parent=0'),
        ));
    }


    public function delete(){
        $id = I("id/d")? I("id/d") : 0;
        $login_user = $this->checkLogin();
        if ($id && $login_user['uid']) {
            $ret = D("Team")->where(" id = '$id' and uid = '$login_user[uid]'")->delete();
        }
        if ($ret) {
            D("TeamItem")->where(" team_id = '$id' ")->delete();
            D("TeamItemMember")->where(" team_id = '$id' ")->delete();
            D("TeamMember")->where(" team_id = '$id' ")->delete();
           $this->sendResult($ret);
        }else{
            $return['error_code'] = 10103 ;
            $return['error_message'] = 'request  fail' ;
            $this->sendResult($return);
        }
    }


    public function update() {

        //populate the alt tag field if the user didn't
        if (empty($this->params['alt'])) $this->params['alt'] = $this->params['title'];

        // call expController update to save the image
        parent::update();
    }


            $pageView = $this->get($page->getUrl());
            $pageView->assertStatus(200);
            $pageView->assertElementNotContains('.page-content', '<a id="xss">');
            $pageView->assertElementNotContains('.page-content', 'href=javascript:');
        }


	public function load_from_post()
	{
		$this->codename		= $_REQUEST['codename'];
		$this->icon		    = $_REQUEST['icon'];
   		$this->lid		    = $_REQUEST['lid'];
   		$this->notes	    = $_REQUEST['notes'];
		$this->enabled		= ($_REQUEST['enabled']=='1'? '1' : '0');

		// load associated functions
		$functions = explode('#', $_REQUEST['menu-functions']);
		$this->functions = array();
		foreach($functions as $function)
		{
			if(!empty($function))
				$this->functions[] = $function;
		}
	}


	function insertCommandCategorieInDB(){
		global $pearDB;

		if (testCommandCategorieExistence($_POST["category_name"])){
			$DBRESULT = $pearDB->query("INSERT INTO `command_categories` (`category_name` , `category_alias`, `category_order`) VALUES ('".$_POST["category_name"]."', '".$_POST["category_alias"]."', '1')");
		}
	}


	protected function _fclose($fp, $path='') {
		@fclose($fp);
		if ($path) {
			@unlink($this->getTempFile($path));
		}
	}


function form_confirm_buttons($action_url, $cancel_url) {
	global $config;
	?>

			<input type='button' onClick='cactiReturnTo("<?php print htmlspecialchars($config['url_path'] . $cancel_url);?>")' value='<?php print __esc('Cancel');?>'>
			<input type='button' onClick='cactiReturnTo("<?php print htmlspecialchars($config['url_path'] . $action_url . '&confirm=true');?>")' value='<?php print __esc('Delete');?>'>

<?php }


    public function action_edge_mode_enable() {
        w3_require_once(W3TC_INC_FUNCTIONS_DIR . '/activation.php');
        $config_path = w3_get_wp_config_path();

        $config_data = @file_get_contents($config_path);
        if ($config_data === false)
            return;

        $new_config_data = $this->wp_config_evaluation_mode_remove_from_content($config_data);
        $new_config_data = preg_replace(
            '~<\?(php)?~',
            "\\0\r\n" . $this->wp_config_evaluation_mode(),
            $new_config_data,
            1);

        if ($new_config_data != $config_data) {
            try {
                w3_wp_write_to_file($config_path, $new_config_data);
            } catch (FilesystemOperationException $ex) {
                throw new FilesystemModifyException(
                    $ex->getMessage(), $ex->credentials_form(),
                    'Edit file <strong>' . $config_path .
                    '</strong> and add the next lines:', $config_path,
                    $this->wp_config_evaluation_mode());
            }
            try {
                $this->_config_admin->set('notes.edge_mode', false);
                $this->_config_admin->save();
            } catch (Exception $ex) {}
        }
        w3_admin_redirect(array('w3tc_note' => 'enabled_edge'));
    }


	private function _allrevisionssince( $option ) {
		$this->addTable( 'revision_actor_temp', 'rev' );
		$this->addSelect(
			[
				'rev.revactor_rev',
				'rev.revactor_timestamp'
			]
		);
		$this->addOrderBy( 'rev.revactor_rev' );
		$this->setOrderDir( 'DESC' );
		$this->addWhere(
			[
				$this->tableNames['page'] . '.page_id = rev.revactor_page',
				'rev.revactor_timestamp >= ' . $this->convertTimestamp( $option )
			]
		);
	}


                    }elseif($p->group == 4){
                        $grp = GENERAL_MEMBER;
                    }


    private function getCategory()
    {
        $category = $this->categoryModel->getById($this->request->getIntegerParam('category_id'));

        if (empty($category)) {
            throw new PageNotFoundException();
        }

        return $category;
    }


    public function manage() {
        expHistory::set('manageable', $this->params);

        // build out a SQL query that gets all the data we need and is sortable.
        $sql  = 'SELECT b.*, c.title as companyname, f.expfiles_id as file_id ';
        $sql .= 'FROM '.DB_TABLE_PREFIX.'_banner b, '.DB_TABLE_PREFIX.'_companies c , '.DB_TABLE_PREFIX.'_content_expFiles f ';
        $sql .= 'WHERE b.companies_id = c.id AND (b.id = f.content_id AND f.content_type="banner")';

		$page = new expPaginator(array(
			'model'=>'banner',
			'sql'=>$sql,
			'order'=>'title',
            'page'=>(isset($this->params['page']) ? $this->params['page'] : 1),
            'controller'=>$this->params['controller'],
            'action'=>$this->params['action'],
            'src'=>$this->loc->src,
			'columns'=>array(
                gt('Title')=>'title',
                gt('Company')=>'companyname',
                gt('Impressions')=>'impressions',
                gt('Clicks')=>'clicks'
            )
        ));

		assign_to_template(array(
            'page'=>$page
        ));
    }


    function process_subsections($parent_section, $subtpl) {
        global $db, $router;

        $section              = new stdClass();
        $section->parent      = $parent_section->id;
        $section->name        = $subtpl->name;
        $section->sef_name    = $router->encode($section->name);
        $section->subtheme    = $subtpl->subtheme;
        $section->active      = $subtpl->active;
        $section->public      = $subtpl->public;
        $section->rank        = $subtpl->rank;
        $section->page_title  = $subtpl->page_title;
        $section->keywords    = $subtpl->keywords;
        $section->description = $subtpl->description;
        $section->id          = $db->insertObject($section, 'section');
        self::process_section($section, $subtpl);
    }


	private function _maxrevisions( $option ) {
		$this->addWhere( "((SELECT count(rev_aux3.revactor_page) FROM {$this->tableNames['revision_actor_temp']} AS rev_aux3 WHERE rev_aux3.revactor_page = {$this->tableNames['page']}.page_id) <= {$option})" );
	}


function nvweb_menu_load_routes()
{
	global $DB;
	global $structure;
	global $current;
	global $website;

	if(empty($structure['routes']))
	{
		$structure['routes'] = array();

		$DB->query('SELECT object_id, path
					  FROM nv_paths
					 WHERE type = "structure"
					   AND lang = '.protect($current['lang']).'
					   AND website = '.$website->id);

		$data = $DB->result();

		if(!is_array($data)) $data = array();
		$dictionary = array();

		foreach($data as $item)
		{
			$structure['routes'][$item->object_id] = $item->path;
		}
	}
}


	function getTextColumns($table) {
		$sql = "SHOW COLUMNS FROM " . $this->prefix.$table . " WHERE type = 'text' OR type like 'varchar%'";
		$res = @mysqli_query($this->connection, $sql);
		if ($res == null)
            return array();
		$records = array();
		while($row = mysqli_fetch_object($res)) {
			$records[] = $row->Field;
		}

		return $records;
	}


    public function wipecache()
    {
        $type = $this->request->request("type");
        switch ($type) {
            case 'all':
            case 'content':
                rmdirs(CACHE_PATH, false);
                Cache::clear();
                if ($type == 'content')
                    break;
            case 'template':
                rmdirs(TEMP_PATH, false);
                if ($type == 'template')
                    break;
            case 'addons':
                Service::refresh();
                if ($type == 'addons')
                    break;
        }

        \think\Hook::listen("wipecache_after");
        $this->success();
    }


    public function testPOSTForRegularUser()
    {
        $post_resource = json_encode([
            'label' => 'Test Request 9747 regular user',
            'shortname'  => 'test9747-regular-user',
            'description' => 'Test of Request 9747 for REST API Project Creation',
            'is_public' => true,
            'template_id' => 100,
        ]);

        $response = $this->getResponseByName(
            REST_TestDataBuilder::TEST_USER_2_NAME,
            $this->request_factory->createRequest(
                'POST',
                'projects'
            )->withBody(
                $this->stream_factory->createStream($post_resource)
            )
        );

        self::assertEquals(201, $response->getStatusCode());

        $create_project_id = json_decode($response->getBody()->getContents(), true, 512, JSON_THROW_ON_ERROR)['id'];

        $this->removeAdminFromProjectMembers(
            $create_project_id,
            REST_TestDataBuilder::TEST_USER_2_NAME,
        );
    }


    function columnUpdate($table, $col, $val, $where=1) {
        $res = @mysqli_query($this->connection, "UPDATE `" . $this->prefix . "$table` SET `$col`='" . $val . "' WHERE $where");
        /*if ($res == null)
            return array();
        $objects = array();
        for ($i = 0; $i < mysqli_num_rows($res); $i++)
            $objects[] = mysqli_fetch_object($res);*/
        //return $objects;
    }


    public function approve_submit() {
        global $history;

        if (empty($this->params['id'])) {
            flash('error', gt('No ID supplied for comment to approve'));
            $lastUrl = expHistory::getLast('editable');
        }

        /* The global constants can be overriden by passing appropriate params */
        //sure wish I could do this once in the constructor. sadly $this->params[] isn't set yet
        $require_login = empty($this->params['require_login']) ? SIMPLENOTE_REQUIRE_LOGIN : $this->params['require_login'];
        $require_approval = empty($this->params['require_approval']) ? SIMPLENOTE_REQUIRE_APPROVAL : $this->params['require_approval'];
        $require_notification = empty($this->params['require_notification']) ? SIMPLENOTE_REQUIRE_NOTIFICATION : $this->params['require_notification'];
        $notification_email = empty($this->params['notification_email']) ? SIMPLENOTE_NOTIFICATION_EMAIL : $this->params['notification_email'];

        $simplenote = new expSimpleNote($this->params['id']);
        //FIXME here is where we might sanitize the note before approving it
        $simplenote->body = $this->params['body'];
        $simplenote->approved = $this->params['approved'];
        $simplenote->save();

        $lastUrl = makelink($history->history[$history->history['lasts']['type']][count($history->history[$history->history['lasts']['type']])-1]['params']);
        if (!empty($this->params['tab']))
        {
            $lastUrl .= "#".$this->params['tab'];
        }
        redirect_to($lastUrl);
    }


    public function test_invite_set_password()
    {
        Notification::fake();
        $user = $this->getViewer();
        $inviteService = app(UserInviteService::class);

        $inviteService->sendInvitation($user);
        $token = DB::table('user_invites')->where('user_id', '=', $user->id)->first()->token;

        $setPasswordPageResp = $this->get('/register/invite/' . $token);
        $setPasswordPageResp->assertSuccessful();
        $setPasswordPageResp->assertSee('Welcome to BookStack!');
        $setPasswordPageResp->assertSee('Password');
        $setPasswordPageResp->assertSee('Confirm Password');

        $setPasswordResp = $this->followingRedirects()->post('/register/invite/' . $token, [
            'password' => 'my test password',
        ]);
        $setPasswordResp->assertSee('Password set, you now have access to BookStack!');
        $newPasswordValid = auth()->validate([
            'email'    => $user->email,
            'password' => 'my test password',
        ]);
        $this->assertTrue($newPasswordValid);
        $this->assertDatabaseMissing('user_invites', [
            'user_id' => $user->id,
        ]);
    }


    public function confirm()
    {
        $project = $this->getProject();
        $category = $this->getCategory();

        $this->response->html($this->helper->layout->project('category/remove', array(
            'project'  => $project,
            'category' => $category,
        )));
    }


    function categoryBreadcrumb() {
//        global $db, $router;

        //eDebug($this->category);

        /*if(isset($router->params['action']))
        {
            $ancestors = $this->category->pathToNode();
        }else if(isset($router->params['section']))
        {
            $current = $db->selectObject('section',' id= '.$router->params['section']);
            $ancestors[] = $current;
            if( $current->parent != -1 || $current->parent != 0 )
            {
                while ($db->selectObject('section',' id= '.$router->params['section']);)
                    if ($section->id == $id) {
                        $current = $section;
                        break;
                    }
                }
            }
            eDebug($sections);
            $ancestors = $this->category->pathToNode();
        }*/

        $ancestors = $this->category->pathToNode();
        // eDebug($ancestors);
        assign_to_template(array(
            'ancestors' => $ancestors
        ));
    }


    public function setAuthorizedBackendSession()
    {
        $_SESSION['authorized'] = true;
        $_SESSION['lastSessionId'] = time();
        $_SESSION['tstamp'] = time();
        $_SESSION['expires'] = time() + $this->expireTimeInMinutes * 60;
        $_SESSION['isBackendSession'] = true;
        // Renew the session id to avoid session fixation
        $this->renewSession();
    }


function rsvpmaker_stripecharge( $atts ) {

	if ( is_admin() || wp_is_json_request() ) {

		return;
	}

	global $current_user;

	$vars['description'] = ( ! empty( $atts['description'] ) ) ? $atts['description'] : __( 'charge from', 'rsvpmaker' ) . ' ' . get_bloginfo( 'name' );

	$vars['paymentType'] = $paymentType = ( empty( $atts['paymentType'] ) ) ? 'once' : $atts['paymentType'];

	$vars['paypal'] = (empty($atts['paypal'])) ? 0 : $atts['paypal'];

	$show = ( ! empty( $atts['showdescription'] ) && ( $atts['showdescription'] == 'yes' ) ) ? true : false;

	if ( $paymentType == 'schedule' ) {

		$months = array( 'january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december' );

		$index = date( 'n' ) - 1;

		if ( isset( $_GET['next'] ) ) {

			if ( $index == 11 ) {

				$index = 0;

			} else {
				$index++;
			}
		}

		$month = $months[ $index ];

		$vars['amount'] = $atts[ $month ];

		$vars['description'] = $vars['description'] . ': ' . ucfirst( $month );

		if ( ! empty( $current_user->user_email ) ) {

			$vars['email'] = $current_user->user_email;
		}

		return rsvpmaker_stripe_form( $vars, $show );

	}

	$vars['amount'] = ( ! empty( $atts['amount'] ) ) ? $atts['amount'] : '';

	if ( $paymentType != 'once' ) {

		$vars['description'] .= ' ' . $paymentType;
	}

	return rsvpmaker_stripe_form( $vars, $show );

	// return rsvpmaker_stripe_form($vars,$show);
}


    function searchByModelForm() {
        // get the search terms
        $terms = $this->params['search_string'];

        $sql = "model like '%" . $terms . "%'";

        $limit = !empty($this->config['limit']) ? $this->config['limit'] : 10;
        $page = new expPaginator(array(
            'model'      => 'product',
            'where'      => $sql,
            'limit'      => !empty($this->config['pagination_default']) ? $this->config['pagination_default'] : $limit,
            'order'      => 'title',
            'dir'        => 'DESC',
            'page'       => (isset($this->params['page']) ? $this->params['page'] : 1),
            'controller' => $this->params['controller'],
            'action'     => $this->params['action'],
            'columns'    => array(
                gt('Model #')      => 'model',
                gt('Product Name') => 'title',
                gt('Price')        => 'base_price'
            ),
        ));

        assign_to_template(array(
            'page'  => $page,
            'terms' => $terms
        ));
    }


	 function manage_upcharge() {
		$this->loc->src = "@globalstoresettings";
        $config = new expConfig($this->loc);
		$this->config = $config->config;

		$gc = new geoCountry();
        $countries = $gc->find('all');

        $gr = new geoRegion();
        $regions = $gr->find('all',null,'rank asc,name asc');
        assign_to_template(array(
            'countries'=>$countries,
            'regions'=>$regions,
            'upcharge'=>!empty($this->config['upcharge'])?$this->config['upcharge']:''
        ));
	 }


    public function __construct () {
        global $vars;
        if(DB_DRIVER == 'mysql') {
            mysql_connect(DB_HOST, DB_USER, DB_PASS);
            mysql_select_db(DB_NAME);
        }elseif(DB_DRIVER == 'mysqli') {
            try {
                self::$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
                if (self::$mysqli->connect_error) {
                    Control::error('db', self::$mysqli->connect_error);
                    exit;
                }else{
                    return true;
                }
            } catch (exception $e) {
                Control::error('db', $e->getMessage() );
            }

            //return self::$mysqli;
        }
    }


						$value = (int)$_POST[$key];
					} else {
						$value = strtotime($_POST[$key]);
					}
					$icmsObj->setVar($key, $value);
					break;

				case XOBJ_DTYPE_URL:
					if (isset($_POST[$key])) {
						$icmsObj->setVar($key, filter_var($_POST[$key], FILTER_SANITIZE_URL));
					}
					break;

				case XOBJ_DTYPE_ARRAY:
					if (is_array($_POST[$key])) {
						$icmsObj->setVar($key, serialize($_POST[$key]));
					}
					break;

				default:
					$icmsObj->setVar($key, $_POST[$key]);
					break;
			}
		}
	}


                        $body = str_replace(array("\n"), "<br />", $body);
                    } else {
                        // It's going elsewhere (doesn't like quoted-printable)
                        $body = str_replace(array("\n"), " -- ", $body);
                    }
                    $title = $items[$i]->title;

                    $msg .= "BEGIN:VEVENT\n";
                    $msg .= $dtstart . $dtend;
                    $msg .= "UID:" . $items[$i]->date_id . "\n";
                    $msg .= "DTSTAMP:" . date("Ymd\THis", time()) . "Z\n";
                    if ($title) {
                        $msg .= "SUMMARY:$title\n";
                    }
                    if ($body) {
                        $msg .= "DESCRIPTION;ENCODING=QUOTED-PRINTABLE:" . $body . "\n";
                    }
                    //	if($link_url) { $msg .= "URL: $link_url\n";}
                    if (!empty($this->config['usecategories'])) {
                        if (!empty($items[$i]->expCat[0]->title)) {
                            $msg .= "CATEGORIES:".$items[$i]->expCat[0]->title."\n";
                        } else {
                            $msg .= "CATEGORIES:".$this->config['uncat']."\n";
                        }
                    }
                    $msg .= "END:VEVENT\n";
                }


    public function show()
    {
        $task = $this->getTask();
        $subtask = $this->getSubtask();

        $this->response->html($this->template->render('subtask_restriction/show', array(
            'status_list' => array(
                SubtaskModel::STATUS_TODO => t('Todo'),
                SubtaskModel::STATUS_DONE => t('Done'),
            ),
            'subtask_inprogress' => $this->subtaskStatusModel->getSubtaskInProgress($this->userSession->getId()),
            'subtask' => $subtask,
            'task' => $task,
        )));
    }


    public function scopeSearch(Builder $query, array $search = [])
    {
        if (empty($search)) {
            return $query;
        }

        if (!array_intersect(array_keys($search), $this->searchable)) {
            return $query;
        }

        return $query->where($search);
    }


    public function backup($type='json')
    {
        global $DB;
        global $website;

        $out = array();
        $DB->query('SELECT * FROM nv_products WHERE website = '.protect($website->id), 'object');

        if($type='json')
            $out = json_encode($DB->result());

        return $out;
    }


    private function getStateId(string $state, string $machine)
    {
        return $this->getContainer()->get(Connection::class)
            ->fetchColumn('
                SELECT LOWER(HEX(state_machine_state.id))
                FROM state_machine_state
                    INNER JOIN  state_machine
                    ON state_machine.id = state_machine_state.state_machine_id
                    AND state_machine.technical_name = :machine
                WHERE state_machine_state.technical_name = :state
            ', [
                'state' => $state,
                'machine' => $machine,
            ]);
    }


    function addDiscountToCart() {
//        global $user, $order;
        global $order;
        //lookup discount to see if it's real and valid, and not already in our cart
        //this will change once we allow more than one coupon code

        $discount = new discounts();
        $discount = $discount->getCouponByName($this->params['coupon_code']);

        if (empty($discount)) {
            flash('error', gt("This discount code you entered does not exist."));
            //redirect_to(array('controller'=>'cart', 'action'=>'checkout'));
            expHistory::back();
        }

        //check to see if it's in our cart already
        if ($this->isDiscountInCart($discount->id)) {
            flash('error', gt("This discount code is already in your cart."));
            //redirect_to(array('controller'=>'cart', 'action'=>'checkout'));
            expHistory::back();
        }

        //this should really be reworked, as it shoudn't redirect directly and not return
        $validateDiscountMessage = $discount->validateDiscount();
        if ($validateDiscountMessage == "") {
            //if all good, add to cart, otherwise it will have redirected
            $od               = new order_discounts();
            $od->orders_id    = $order->id;
            $od->discounts_id = $discount->id;
            $od->coupon_code  = $discount->coupon_code;
            $od->title        = $discount->title;
            $od->body         = $discount->body;
            $od->save();
            // set this to just the discount applied via this coupon?? if so, when though? $od->discount_total = ??;
            flash('message', gt("The discount code has been applied to your cart."));
        } else {
            flash('error', $validateDiscountMessage);
        }
        //redirect_to(array('controller'=>'cart', 'action'=>'checkout'));
        expHistory::back();
    }


    public function create_file() {
        if (!AuthUser::hasPermission('file_manager_mkfile')) {
            Flash::set('error', __('You do not have sufficient permissions to create a file.'));
            redirect(get_url('plugin/file_manager/browse/'));
        }

        // CSRF checks
        if (isset($_POST['csrf_token'])) {
            $csrf_token = $_POST['csrf_token'];
            if (!SecureToken::validateToken($csrf_token, BASE_URL.'plugin/file_manager/create_file')) {
                Flash::set('error', __('Invalid CSRF token found!'));
                redirect(get_url('plugin/file_manager/browse/'));
            }
        }
        else {
            Flash::set('error', __('No CSRF token found!'));
            redirect(get_url('plugin/file_manager/browse/'));
        }

        $data = $_POST['file'];

        $path = str_replace('..', '', $data['path']);
        $filename = str_replace('..', '', $data['name']);
        $file = FILES_DIR . DS . $path . DS . $filename;

        if (file_put_contents($file, '') !== false) {
            $mode = Plugin::getSetting('filemode', 'file_manager');
            chmod($file, octdec($mode));
        } else {
            Flash::set('error', __('File :name has not been created!', array(':name' => $filename)));
        }
        redirect(get_url('plugin/file_manager/browse/' . $path));
    }


    public static function find($code)
    {
        global $DB;
        global $website;

        $DB->query('
            SELECT *
            FROM nv_coupons
            WHERE website = '.protect($website->id).' AND
                  code = '.protect($code),
            'object'
        );

        $rs = $DB->result();
        $out = false;

        if(!empty($rs))
        {
            $coupon = new coupon();
            $coupon->load_from_resultset($rs);
            $out = $coupon;
        }

        return $out;
    }


    public function getViewFileParams () {
        if (!isset ($this->_viewFileParams)) {
            $this->_viewFileParams = array_merge (
                parent::getViewFileParams (),
                array (
                    'chartType' => $this->chartType,
			        'chartSettingsDataProvider' => self::getChartSettingsProvider (
                        $this->chartType),
                    'eventTypes' =>
                        array ('all'=>Yii::t('app', 'All Events')) + Events::$eventLabels,
                    'socialSubtypes' => json_decode (
			            Dropdowns::model()->findByPk(113)->options,true),
                    'visibilityFilters' => array (
                        '1'=>'Public',
                        '0'=>'Private',
                    ),
                    'suppressChartSettings' => false,
                    'chartType' => 'usersChart',
                    'widgetUID' => $this->widgetUID,
                    'metricTypes' => User::getUserOptions (),
                )
            );
        }
        return $this->_viewFileParams;
    }


    public function delete($id)
    {
        $ret = $this->get($id);
        if (!$ret) {
            /* get() already logged */
            return self::ID_NOT_EXITS;
        }

        if ($this->isUsed($id)) {
            $this->errors[] = _T("Cannot delete this label: it's still used");
            return false;
        }

        try {
            $this->zdb->connection->beginTransaction();
            $delete = $this->zdb->delete($this->table);
            $delete->where($this->fpk . ' = ' . $id);

            $this->zdb->execute($delete);
            $this->deleteTranslation($ret->{$this->flabel});

            Analog::log(
                $this->getType() . ' ' . $id . ' deleted successfully.',
                Analog::INFO
            );

            $this->zdb->connection->commit();
            return true;
        } catch (Throwable $e) {
            $this->zdb->connection->rollBack();
            Analog::log(
                'Unable to delete ' . $this->getType() . ' ' . $id .
                ' | ' . $e->getMessage(),
                Analog::ERROR
            );
            throw $e;
        }
    }


    public function confirm()
    {
        $project = $this->getProject();

        $this->response->html($this->helper->layout->project('action/remove', array(
            'action' => $this->actionModel->getById($this->request->getIntegerParam('action_id')),
            'available_events' => $this->eventManager->getAll(),
            'available_actions' => $this->actionManager->getAvailableActions(),
            'project' => $project,
            'title' => t('Remove an action')
        )));
    }


    public function update()
    {
        $project = $this->getProject();
        $tag_id = $this->request->getIntegerParam('tag_id');
        $tag = $this->tagModel->getById($tag_id);
        $values = $this->request->getValues();
        list($valid, $errors) = $this->tagValidator->validateModification($values);

        if ($tag['project_id'] != $project['id']) {
            throw new AccessForbiddenException();
        }

        if ($valid) {
            if ($this->tagModel->update($values['id'], $values['name'])) {
                $this->flash->success(t('Tag updated successfully.'));
            } else {
                $this->flash->failure(t('Unable to update this tag.'));
            }

            $this->response->redirect($this->helper->url->to('ProjectTagController', 'index', array('project_id' => $project['id'])));
        } else {
            $this->edit($values, $errors);
        }
    }


    public function confirm()
    {
        $task = $this->getTask();
        $link = $this->getTaskLink();

        $this->response->html($this->template->render('task_internal_link/remove', array(
            'link' => $link,
            'task' => $task,
        )));
    }


function layout_navbar() {
	$t_logo_url = config_get('logo_url');

	echo '
';
	echo '
';

	echo '<button id="menu-toggler" type="button" class="navbar-toggle menu-toggler pull-left hidden-lg" data-target="#sidebar">';
	echo 'Toggle sidebar';
	echo '';
	echo '';
	echo '';
	echo '</button>';

	echo '
';
	echo '';
	echo ' ';
	echo config_get('window_title');
	echo ' ';
	echo '';

	$t_toggle_class = (OFF == config_get('show_avatar') ? 'navbar-toggle' : 'navbar-toggle-img');
	echo '<button type="button" class="navbar-toggle ' . $t_toggle_class . ' collapsed pull-right hidden-sm hidden-md hidden-lg" data-toggle="collapse" data-target=".navbar-buttons,.navbar-menu">';
	echo 'Toggle user menu';
	if (auth_is_user_authenticated()) {
		layout_navbar_user_avatar();
	}
	echo '</button>';

	echo '
';

	echo '
';
	echo '
';
	if (auth_is_user_authenticated()) {
		# shortcuts button bar
		layout_navbar_button_bar();
		# projects dropdown menu
		layout_navbar_projects_menu();
		# user buttons such as messages, notifications and user menu
		layout_navbar_user_menu();
	}
	echo '
';
	echo '
';

	echo '
';
	echo '
';
}


						unset($return[$key]);
				}
			}
			break;
	}
	return @array_change_key_case($return, CASE_UPPER);
}


	public static function update_object_votes($webuser, $object, $object_id, $value, $replace=false)
	{
		global $DB;
		global $website;
		global $events;

		$status = false;
		$voted = false;
		$webuser_vote_id = null;

		// user has voted in the past?
		if($DB->query('
				SELECT *
				  FROM nv_webuser_votes
				 WHERE webuser = '.intval($webuser).'
				   AND object  = '.protect($object).'
				   AND object_id = '.protect($object_id)
			)
		)
		{
			$data = $DB->result();
			$data = $data[0];
			$voted = ($data->webuser == $webuser);
			$webuser_vote_id = $data->id;
		}

		if($voted && $replace) // update
		{
			$ok = $DB->execute('
 				UPDATE nv_webuser_votes
				   SET `value`	=  '.protect($value).',
						date 	=  '.protect(core_time()).'
				 WHERE id = '.$webuser_vote_id
			);

			if(!$ok)
				throw new Exception($DB->get_last_error());
			else
				$status = true;
		}
		else if($voted)
		{
			$status = 'already_voted';
		}
		else	// insert
		{
			$wv = new webuser_vote();
			$wv->website = $website->id;
			$wv->webuser = $webuser;
			$wv->object  = $object;
			$wv->object_id = $object_id;
			$wv->value 	 = $value;
			$wv->insert();
			$webuser_vote_id = $wv->id;
			$status = true;
		}

		// now update the object score
		if($status === true)
			webuser_vote::update_object_score($object, $object_id);

		$events->trigger(
			'webuser',
			'vote',
			array(
				'status' => $status,
				'webuser_vote_id' => $webuser_vote_id,
				'webuser' => $webuser,
				'object' => $object,
				'object_id' => $object_id,
				'value' => $value,
				'replace' => $replace
			)
		);

		return $status;
	}


                foreach ($grpusers as $u) {
                    $emails[$u->email] = trim(user::getUserAttribution($u->id));
                }


			return \DPL\Variables::setVarDefault( $args );
		}
		return \DPL\Variables::getVar( $cmd );
	}


$cols .= '\'' . Util::sqlAddSlashes($col_select) . '\',';
        }
        $cols = trim($cols, ',');
        $has_list = PMA_findExistingColNames($db, $cols);
        foreach ($field_select as $column) {
            if (!in_array($column, $has_list)) {
                $colNotExist[] = "'" . $column . "'";
            }
        }
    }
    if (!empty($colNotExist)) {
        $colNotExist = implode(",", array_unique($colNotExist));
        $message = Message::notice(
            sprintf(
                __(
                    'Couldn\'t remove Column(s) %1$s '
                    . 'as they don\'t exist in central columns list!'
                ), htmlspecialchars($colNotExist)
            )
        );
    }
    $GLOBALS['dbi']->selectDb($pmadb, $GLOBALS['controllink']);

    $query = 'DELETE FROM ' . Util::backquote($central_list_table) . ' '
        . 'WHERE db_name = \'' . $db . '\' AND col_name IN (' . $cols . ');';

    if (!$GLOBALS['dbi']->tryQuery($query, $GLOBALS['controllink'])) {
        $message = Message::error(__('Could not remove columns!'));
        $message->addMessage('
' . htmlspecialchars($cols) . '
');
        $message->addMessage(
            Message::rawError(
                $GLOBALS['dbi']->getError($GLOBALS['controllink'])
            )
        );
    }
    return $message;
}


    public function save()
    {
        $project = $this->getProject();

        $values = $this->request->getValues();
        list($valid, $errors) = $this->categoryValidator->validateCreation($values);

        if ($valid) {
            if ($this->categoryModel->create($values) !== false) {
                $this->flash->success(t('Your category have been created successfully.'));
                $this->response->redirect($this->helper->url->to('CategoryController', 'index', array('project_id' => $project['id'])), true);
                return;
            } else {
                $errors = array('name' => array(t('Another category with the same name exists in this project')));
            }
        }

        $this->create($values, $errors);
    }


    public static function DragnDropReRank2() {
        global $router, $db;

        $id = $router->params['id'];
        $page = new section($id);
        $old_rank = $page->rank;
        $old_parent = $page->parent;
        $new_rank = $router->params['position'] + 1;  // rank
        $new_parent = intval($router->params['parent']);

        $db->decrement($page->tablename, 'rank', 1, 'rank>' . $old_rank . ' AND parent=' . $old_parent);  // close in hole
        $db->increment($page->tablename, 'rank', 1, 'rank>=' . $new_rank . ' AND parent=' . $new_parent);  // make room

        $params = array();
        $params['parent'] = $new_parent;
        $params['rank'] = $new_rank;
        $page->update($params);

        self::checkForSectionalAdmins($id);
        expSession::clearAllUsersSessionCache('navigation');
    }


    public static function deactivate($id){
        $act = Db::query(
            sprintf("UPDATE `user` SET `status` = '0' WHERE `id` = '%d'",
                Typo::int($id)
                )
            );
        if($act){
            return true;
        }else{
            return false;
        }
    }


    public function editTitle() {
        global $user;
        $file = new expFile($this->params['id']);
        if ($user->id==$file->poster || $user->isAdmin()) {
            $file->title = $this->params['newValue'];
            $file->save();
            $ar = new expAjaxReply(200, gt('Your title was updated successfully'), $file);
        } else {
            $ar = new expAjaxReply(300, gt("You didn't create this file, so you can't edit it."));
        }
        $ar->send();
    }


    public function testPrintAction()
    {
        $client = $this->getClientForAuthenticatedUser(User::ROLE_TEAMLEAD);

        $fixture = new InvoiceTemplateFixtures();
        $templates = $this->importFixture($fixture);
        $id = $templates[0]->getId();

        $begin = new \DateTime('first day of this month');
        $end = new \DateTime('last day of this month');
        $fixture = new TimesheetFixtures();
        $fixture
            ->setUser($this->getUserByRole(User::ROLE_TEAMLEAD))
            ->setAmount(20)
            ->setStartDate($begin)
        ;
        $this->importFixture($fixture);

        $this->request($client, '/invoice/');
        $this->assertTrue($client->getResponse()->isSuccessful());

        $dateRange = $begin->format('Y-m-d') . DateRangeType::DATE_SPACER . $end->format('Y-m-d');

        $params = [
            'daterange' => $dateRange,
            'projects' => [1],
        ];

        $action = '/invoice/preview/1/' . $id . '?' . http_build_query($params);
        $this->request($client, $action);
        $this->assertTrue($client->getResponse()->isSuccessful());
        $node = $client->getCrawler()->filter('body');
        $this->assertEquals(1, $node->count());
        $this->assertEquals('invoice_print', $node->getIterator()[0]->getAttribute('class'));
    }


    public function handle(Request $request, Closure $next, int $keyType)
    {
        if (is_null($request->bearerToken()) && is_null($request->user())) {
            throw new HttpException(401, null, null, ['WWW-Authenticate' => 'Bearer']);
        }

        // This is a request coming through using cookies, we have an authenticated user
        // not using an API key. Make some fake API key models and continue on through
        // the process.
        if ($request->user() instanceof User) {
            $model = (new ApiKey())->forceFill([
                'user_id' => $request->user()->id,
                'key_type' => ApiKey::TYPE_ACCOUNT,
            ]);
        } else {
            $model = $this->authenticateApiKey($request->bearerToken(), $keyType);

            $this->auth->guard()->loginUsingId($model->user_id);
        }

        $request->attributes->set('api_key', $model);

        return $next($request);
    }


            $files[$key]->save();
        }

//        eDebug($files,true);
    }


function captureAuthorization() {
        //eDebug($this->params,true);
        $order = new order($this->params['id']);
        /*eDebug($this->params);
        //eDebug($order,true);*/
        //eDebug($order,true);
        //$billing = new billing();

        //eDebug($billing, true);
        //$billing->calculator = new $calcname($order->billingmethod[0]->billingcalculator_id);
        $calc         = $order->billingmethod[0]->billingcalculator->calculator;
        $calc->config = $order->billingmethod[0]->billingcalculator->config;

        //$calc = new $calc-
        //eDebug($calc,true);
        if (!method_exists($calc, 'delayed_capture')) {
            flash('error', gt('The Billing Calculator does not support delayed capture'));
            expHistory::back();
        }

        $result = $calc->delayed_capture($order->billingmethod[0], $this->params['capture_amt'], $order);

        if (empty($result->errorCode)) {
            flash('message', gt('The authorized payment was successfully captured'));
            expHistory::back();

        } else {
            flash('error', gt('An error was encountered while capturing the authorized payment.') . '

' . $result->message);
            expHistory::back();
        }
    }


    public function testUserCredentials($email, $password, $server, $port, $security) {
        require_once(realpath(Yii::app()->basePath.'/components/phpMailer/class.phpmailer.php'));
        require_once(realpath(Yii::app()->basePath.'/components/phpMailer/class.smtp.php'));
        $phpMail = new PHPMailer(true);

        $phpMail->isSMTP();
        $phpMail->SMTPAuth = true;
        $phpMail->Username = $email;
        $phpMail->Password = $password;
        $phpMail->Host = $server;
        $phpMail->Port = $port;
        $phpMail->SMTPSecure = $security;

        try {
            $validCredentials = $phpMail->SmtpConnect();
        } catch(phpmailerException $error) {
            $validCredentials = false;
        }
        return $validCredentials;
    }


    public static function get($vars) {
        $op = Db::result("SELECT `value` FROM `options` WHERE `name` = '{$vars}' LIMIT 1");
        if(Db::$num_rows > 0){
            return $op[0]->value;
        }else{
            return false;
        }
    }


    public function confirm()
    {
        $task = $this->getTask();
        $link_id = $this->request->getIntegerParam('link_id');
        $link = $this->taskExternalLinkModel->getById($link_id);

        if (empty($link)) {
            throw new PageNotFoundException();
        }

        $this->response->html($this->template->render('task_external_link/remove', array(
            'link' => $link,
            'task' => $task,
        )));
    }


            $q = self::$mysqli->query($vars) ;
            if($q === false) {
                Control::error('db',"Query failed: ".self::$mysqli->error."<br />\n");
            }
        }

        return $q;
    }


	public function manage_versions() {
	    expHistory::set('manageable', $this->params);

	    $hv = new help_version();
	    $current_version = $hv->find('first', 'is_current=1');

	    $sql  = 'SELECT hv.*, COUNT(h.title) AS num_docs FROM '.DB_TABLE_PREFIX.'_help h ';
	    $sql .= 'RIGHT JOIN '.DB_TABLE_PREFIX.'_help_version hv ON h.help_version_id=hv.id GROUP BY hv.version';

	    $page = new expPaginator(array(
            'sql'=>$sql,
            'limit'=>30,
            'order'      => (isset($this->params['order']) ? $this->params['order'] : 'version'),
            'dir'        => (isset($this->params['dir']) ? $this->params['dir'] : 'DESC'),
            'page'=>(isset($this->params['page']) ? $this->params['page'] : 1),
            'controller'=>$this->baseclassname,
            'action'=>$this->params['action'],
            'src'=>$this->loc->src,
            'columns'=>array(
                gt('Version')=>'version',
                gt('Title')=>'title',
                gt('Current')=>'is_current',
                gt('# of Docs')=>'num_docs'
            ),
        ));

	    assign_to_template(array(
            'current_version'=>$current_version,
            'page'=>$page
        ));
	}


   static function getTypeName($nb = 0) {
      return __('Maintenance');
   }


    public static function getURI () {
        $uri = $_SERVER['REQUEST_URI'];
        // echo $uri;
        // strip any $_REQUEST variable
        $uri = explode('?', $uri);

        if (count($uri) > 0) {

            unset($uri[1]);

        }
        // print_r($uri[0]);
        if (self::inFolder()) {

            $uri = self::stripFolder($uri[0]);

        }else{

            $uri2 = explode('/', $uri[0]);
            unset($uri2[0]);
            $uri = implode('/', $uri2);

        }
        $uri = (Options::v('permalink_use_index_php') == "on")?
            str_replace("/index.php", "", $uri): $uri;
        return '/' . trim($uri, '/');
    }


    function display($text, $inline_images=true, $balance=true) {
        // Make showing offsite images optional
        $text = preg_replace_callback('/<img ([^>]*)(src="http[^"]+")([^>]*)\/>/',
            function($match) {
                // Drop embedded classes -- they don't refer to ours
                $match = preg_replace('/class="[^"]*"/', '', $match);
                return sprintf('<span %s class="non-local-image" data-%s %s></span>',
                    $match[1], $match[2], $match[3]);
            },
            $text);

        if ($balance)
            $text = self::html_balance($text, false);

        // make urls clickable.
        $text = Format::clickableurls($text);

        if ($inline_images)
            return self::viewableImages($text);

        return $text;
    }


function DateInputAY($value, $name, $counter = 1, $placeholder = _enterDate)
{

    $show = "";
    $date_sep = "";
    $monthVal = "";
    $yearVal = "";
    $dayVal = "";
    $display = "";

    if ($value != '')
        return '

' . ProperDateAY($value) . '
	<input type=text id="date_' . $counter . '" ' . $show . '  style="display:none" readonly>		<input type=hidden ' . $monthVal . ' id="monthSelect' . $counter . '" name="month_' . $name . '" ><input type=hidden ' . $dayVal . '  id="daySelect' . $counter . '"   name="day_' . $name . '"><input type=hidden ' . $yearVal . '  id="yearSelect' . $counter . '" name="year_' . $name . '" >

';
    else {
        if ($counter == 2)
            return '<input type="text" id="date_' . $counter . '"  data-placeholder="' . $placeholder . '" class="form-control daterange-single"><input type=hidden ' . $monthVal . ' id="monthSelect' . $counter . '" name="month_' . $name . '" /><input type=hidden ' . $dayVal . '  id="daySelect' . $counter . '"   name="day_' . $name . '" /><input type=hidden ' . $yearVal . '  id="yearSelect' . $counter . '" name="year_' . $name . '" />';
        else
            return '<input type="text" id="date_' . $counter . '"  data-placeholder="' . $placeholder . '" class="form-control daterange-single"><input type=hidden ' . $monthVal . ' id="monthSelect' . $counter . '" name="month_' . $name . '" /><input type=hidden ' . $dayVal . '  id="daySelect' . $counter . '"   name="day_' . $name . '"><input type=hidden ' . $yearVal . '  id="yearSelect' . $counter . '" name="year_' . $name . '" />';
    }
}


		$result = sqlrequest($database_ged, $sql);
		if(!$result){
			$success = false;
		}
	}

	// display the final message
	if($success){
		message(11, " : ".getLabel("message.event_edited"), "ok");
	} else {
		message(11, " : ".getLabel("message.event_edited_error"), "danger");
	}
}


				print '>' . title_trim(null_out_substitutions(htmlspecialchars($form_data[$id])), 75) . "</option>\n";
			}
		}


    function delete_selected() {
        $item = $this->event->find('first', 'id=' . $this->params['id']);
        if ($item && $item->is_recurring == 1) {
            $event_remaining = false;
            $eventdates = $item->eventdate[0]->find('all', 'event_id=' . $item->id);
            foreach ($eventdates as $ed) {
                if (array_key_exists($ed->id, $this->params['dates'])) {
                    $ed->delete();
                } else {
                    $event_remaining = true;
                }
            }
            if (!$event_remaining) {
                $item->delete(); // model will also ensure we delete all event dates
            }
            expHistory::back();
        } else {
            notfoundController::handle_not_found();
        }
    }


	public function jsonError(Exception $exception) {
		$message = $exception->getMessage();
		$code = $this->getHttpStatusCode($exception);

		return new JSONResponse(
			[
				'message' => $message . ' (' . $code . ')',
				'success' => false
			],
			$code
		);
	}


	public function setError ($pn_error_number, $ps_error_description='', $ps_error_context='', $ps_error_source='') {
		$this->opn_error_number = $pn_error_number;
		$this->ops_error_description = $ps_error_description;
		$this->ops_error_context = $ps_error_context;
		$this->ops_error_source = $ps_error_source;

		if (($this->opb_halt_on_error) || ($this->opb_report_on_error)) {
			$this->halt();
		}
		return 1;
	}


function init_args() {

	$args = new stdClass();

	$_REQUEST = strings_stripSlashes($_REQUEST);

	$args->build_id = isset($_REQUEST['build_id']) ? $_REQUEST['build_id'] : 0;
	$args->confirmed = isset($_REQUEST['confirmed']) && $_REQUEST['confirmed'] == 'yes' ? true : false;

	$args->user_id = $_SESSION['userID'];
	$args->testproject_id = $_SESSION['testprojectID'];
	$args->testproject_name = $_SESSION['testprojectName'];

	$args->refreshTree = isset($_SESSION['setting_refresh_tree_on_action']) ?
	                     $_SESSION['setting_refresh_tree_on_action'] : false;

	return $args;
}


    public function buildControl() {
        $control = new colorcontrol();
        if (!empty($this->params['value'])) $control->value = $this->params['value'];
        if ($this->params['value'][0] != '#') $this->params['value'] = '#' . $this->params['value'];
        $control->default = $this->params['value'];
        if (!empty($this->params['hide'])) $control->hide = $this->params['hide'];
        if (isset($this->params['flip'])) $control->flip = $this->params['flip'];
        $this->params['name'] = !empty($this->params['name']) ? $this->params['name'] : '';
        $control->name  = $this->params['name'];
        $this->params['id'] = !empty($this->params['id']) ? $this->params['id'] : '';
        $control->id  = isset($this->params['id']) && $this->params['id'] != "" ? $this->params['id'] : "";
        //echo $control->id;
        if (empty($control->id)) $control->id = $this->params['name'];
        if (empty($control->name)) $control->name = $this->params['id'];

        // attempt to translate the label
        if (!empty($this->params['label'])) {
            $this->params['label'] = gt($this->params['label']);
        } else {
            $this->params['label'] = null;
        }
        echo $control->toHTML($this->params['label'], $this->params['name']);
//        $ar = new expAjaxReply(200, gt('The control was created'), json_encode(array('data'=>$code)));
//        $ar->send();
    }


    public function testGetDeepWithInvalidPaths($path)
    {
        $bag = new ParameterBag(array('foo' => array('bar' => 'moo')));

        $bag->get($path, null, true);
    }


function HackingLog()
{
	echo "" . _youReNotAllowedToUseThisProgram . "! " . _thisAttemptedViolationHasBeenLoggedAndYourIpAddressWasCaptured . ".";
	Warehouse('footer');

	if ($_SERVER['HTTP_X_FORWARDED_FOR']) {
		$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
	} else {
		$ip = $_SERVER['REMOTE_ADDR'];
	}

	if ($openSISNotifyAddress)
		mail($openSISNotifyAddress, 'HACKING ATTEMPT', "INSERT INTO hacking_log (HOST_NAME,IP_ADDRESS,LOGIN_DATE,VERSION,PHP_SELF,DOCUMENT_ROOT,SCRIPT_NAME,MODNAME,USERNAME) values('$_SERVER[SERVER_NAME]','$ip','" . date('Y-m-d') . "','$openSISVersion','$_SERVER[PHP_SELF]','$_SERVER[DOCUMENT_ROOT]','$_SERVER[SCRIPT_NAME]','$_REQUEST[modname]','" . User('USERNAME') . "')");

	if (false && function_exists('query')) {

		if ($_SERVER['HTTP_X_FORWARDED_FOR']) {
			$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
		} else {
			$ip = $_SERVER['REMOTE_ADDR'];
		}

		$connection = new mysqli('os4ed.com', 'openSIS_log', 'openSIS_log', 'openSIS_log');

		$connection->query("INSERT INTO hacking_log (HOST_NAME,IP_ADDRESS,LOGIN_DATE,VERSION,PHP_SELF,DOCUMENT_ROOT,SCRIPT_NAME,MODNAME,USERNAME) values('$_SERVER[SERVER_NAME]','$ip','" . date('Y-m-d') . "','$openSISVersion','$_SERVER[PHP_SELF]','$_SERVER[DOCUMENT_ROOT]','$_SERVER[SCRIPT_NAME]','" . optional_param('modname', '', PARAM_CLEAN) . "','" . User('USERNAME') . "')");
		mysqli_close($link);
	}
}


			$eml->prepareBody();
		}

        list ($success, $message) = $this->checkDoNotEmailFields ($eml);
        if (!$success) {
            return array ($success, $message);
        }

		$result = $eml->send($historyFlag);
		if (isset($result['code']) && $result['code'] == 200) {
            if (YII_UNIT_TESTING) {
                return array(true, $eml->message);
            } else {
                return array(true, "");
            }
        } else {
            return array (false, Yii::t('app', "Email could not be sent"));
        }
	}


	public function update_groupdiscounts() {
	    global $db;

	    if (empty($this->params['id'])) {
	        // look for existing discounts for the same group
	        $existing_id = $db->selectValue('groupdiscounts', 'id', 'group_id='.$this->params['group_id']);
	        if (!empty($existing_id)) flashAndFlow('error',gt('There is already a discount for that group.'));
	    }

        $gd = new groupdiscounts();
	    $gd->update($this->params);
	    expHistory::back();
	}


    public function getQueryGroupby()
    {
        $R1 = 'R1_' . $this->field->id;
        $R2 = 'R2_' . $this->field->id;
        return "$R2.id";
    }


                    $sort    = in_array(strtolower($val), array('asc', 'desc')) ? ' ' . $val : '';
                    $array[] = $this->parseKey($key, true) . $sort;
                }
            }


	public function load_from_resultset($rs)
	{
		global $DB;

		$main = $rs[0];

		$this->id      		= $main->id;
		$this->codename		= $main->codename;
		$this->icon		    = $main->icon;
   		$this->lid		    = $main->lid;
   		$this->notes	    = $main->notes;
		$this->enabled		= $main->enabled;

		/*
		$DB->query('SELECT function_id
					  FROM nv_menu_items
					 WHERE menu_id = '.$this->id.' ORDER BY position ASC');

		$this->functions = $DB->result('function_id');
		*/
		$this->functions	= json_decode($main->functions);
		if(empty($this->functions))	$this->functions = array();
	}


    public function testDeleteCommentAction()
    {
        $client = $this->getClientForAuthenticatedUser(User::ROLE_ADMIN);
        $this->assertAccessIsGranted($client, '/admin/customer/1/details');
        $form = $client->getCrawler()->filter('form[name=customer_comment_form]')->form();
        $client->submit($form, [
            'customer_comment_form' => [
                'message' => 'Blah foo bar',
            ]
        ]);
        $this->assertIsRedirect($client, $this->createUrl('/admin/customer/1/details'));
        $client->followRedirect();
        $node = $client->getCrawler()->filter('div.box#comments_box .direct-chat-msg');
        self::assertStringContainsString('Blah foo bar', $node->html());
        $node = $client->getCrawler()->filter('div.box#comments_box .box-body a.confirmation-link');
        self::assertStringEndsWith('/comment_delete', $node->attr('href'));

        $comments = $this->getEntityManager()->getRepository(CustomerComment::class)->findAll();
        $id = $comments[0]->getId();

        $this->request($client, '/admin/customer/' . $id . '/comment_delete');
        $this->assertIsRedirect($client, $this->createUrl('/admin/customer/1/details'));
        $client->followRedirect();
        $node = $client->getCrawler()->filter('div.box#comments_box .box-body');
        self::assertStringContainsString('There were no comments posted yet', $node->html());
    }


    private function runCallback() {
        foreach ($this->records as &$record) {
            if (isset($record->ref_type)) {
                $refType = $record->ref_type;
                if (class_exists($record->ref_type)) {
                    $type = new $refType();
                    $classinfo = new ReflectionClass($type);
                    if ($classinfo->hasMethod('paginationCallback')) {
                        $item = new $type($record->original_id);
                        $item->paginationCallback($record);
                    }
                }
            }
        }
    }


    public static function country_region_name_by_code($code, $language="")
    {
        global $DB;

        // TODO: region names have no translation in database at this time
        // $lang = core_get_language($language);

        $DB->query('SELECT name
					FROM nv_countries_regions
		 			WHERE `numeric` = '.protect($code));

        $row = $DB->first();

        return $row->name;
    }


    protected function getComment()
    {
        $comment = $this->commentModel->getById($this->request->getIntegerParam('comment_id'));

        if (empty($comment)) {
            throw new PageNotFoundException();
        }

        if (! $this->userSession->isAdmin() && $comment['user_id'] != $this->userSession->getId()) {
            throw new AccessForbiddenException();
        }

        return $comment;
    }


    function preview()
    {
        if ($this->params['id'] == 0) { // we want the default editor
            $demo = new stdClass();
            $demo->id = 0;
            $demo->name = "Default";
            if ($this->params['editor'] == 'ckeditor') {
                $demo->skin = 'kama';
            } elseif ($this->params['editor'] == 'tinymce') {
                $demo->skin = 'lightgray';
            }
        } else {
            $demo = self::getEditorSettings($this->params['id'], expString::escape($this->params['editor']));
        }
        assign_to_template(
            array(
                'demo' => $demo,
                'editor' => $this->params['editor']
            )
        );
    }


    public function detach()
    {
        global $zdb, $hist;

        try {
            $update = $zdb->update(self::TABLE);
            $update->set(
                array('parent_group' => new Expression('NULL'))
            )->where(
                self::PK . ' = ' . $this->id
            );

            $edit = $zdb->execute($update);

            //edit == 0 does not mean there were an error, but that there
            //were nothing to change
            if ($edit->count() > 0) {
                $this->parent_group = null;
                $hist->add(
                    _T("Group has been detached from its parent"),
                    $this->group_name
                );
            }

            return true;
        } catch (Throwable $e) {
            Analog::log(
                'Something went wrong detaching group `' . $this->group_name .
                '` (' . $this->id . ') from its parent:\'( | ' .
                $e->getMessage() . "\n" .
                $e->getTraceAsString(),
                Analog::ERROR
            );
            throw $e;
        }
    }


                new SessionHandlerProxy(new \SessionHandler()) : new NativeProxy();
        }


                foreach ($page as $pageperm) {
                    if (!empty($pageperm['manage'])) return true;
                }


	public function attributeLabels() {
		return array(
			'actionId' => Yii::t('actions','Action ID'),
			'text' => Yii::t('actions','Action Text'),
		);
	}


    function edit_freeform() {
        $section = isset($this->params['id']) ? $this->section->find($this->params['id']) : new section($this->params);
        if ($section->parent == -1) {
            notfoundController::handle_not_found();
            exit;
        } // doesn't work for standalone pages
        if (empty($section->id)) {
            $section->public = 1;
            if (!isset($section->parent)) {
                // This is another precaution.  The parent attribute
                // should ALWAYS be set by the caller.
                //FJD - if that's the case, then we should die.
                notfoundController::handle_not_authorized();
                exit;
                //$section->parent = 0;
            }
        }
        assign_to_template(array(
            'section' => $section,
            'glyphs' => self::get_glyphs(),
        ));
    }


function initEnv() {
  $iParams = array("reqURI" => array(tlInputParameter::STRING_N,0,4000));
  $pParams = G_PARAMS($iParams);

  $args = new stdClass();
  $args->ssodisable = getSSODisable();

  // CWE-79:
  // Improper Neutralization of Input
  // During Web Page Generation ('Cross-site Scripting')
  //
  // https://cxsecurity.com/issue/WLB-2019110139
  $args->reqURI = '';
  if ($pParams["reqURI"] != '') {
    $args->reqURI = $pParams["reqURI"];

    // some sanity checks
    // strpos ( string $haystack , mixed $needle
    if (strpos($args->reqURI,'javascript') !== false) {
      $args->reqURI = null;
    }
  }
  if (null == $args->reqURI) {
    $args->reqURI = 'lib/general/mainPage.php';
  }
  $args->reqURI = $_SESSION['basehref'] . $args->reqURI;

  $args->tproject_id = isset($_REQUEST['tproject_id']) ? intval($_REQUEST['tproject_id']) : 0;
  $args->tplan_id = isset($_REQUEST['tplan_id']) ? intval($_REQUEST['tplan_id']) : 0;

  $gui = new stdClass();
  $gui->title = lang_get('main_page_title');
  $gui->mainframe = $args->reqURI;
  $gui->navbar_height = config_get('navbar_height');

  $sso = ($args->ssodisable ? '&ssodisable' : '');
  $gui->titleframe = "lib/general/navBar.php?" .
                     "tproject_id={$args->tproject_id}&" .
                     "tplan_id={$args->tplan_id}&" .
                     "updateMainPage=1" . $sso;
  $gui->logout = 'logout.php?viewer=' . $sso;

  return array($args,$gui);
}


	public function initializeObject() {
		$this->initializeFormStateFromRequest();
		$this->initializeCurrentPageFromRequest();

		if (!$this->isFirstRequest()) {
			$this->processSubmittedFormValues();
		}
	}


    function insertObject($object, $table) {
        //if ($table=="text") eDebug($object,true);
        $sql = "INSERT INTO `" . $this->prefix . "$table` (";
        $values = ") VALUES (";
        foreach (get_object_vars($object) as $var => $val) {
            //We do not want to save any fields that start with an '_'
            if ($var{0} != '_') {
                $sql .= "`$var`,";
                if ($values != ") VALUES (") {
                    $values .= ",";
                }
                $values .= "'" . mysqli_real_escape_string($this->connection, $val) . "'";
            }
        }
        $sql = substr($sql, 0, -1) . substr($values, 0) . ")";
        //if($table=='text')eDebug($sql,true);
        if (@mysqli_query($this->connection, $sql) != false) {
            $id = mysqli_insert_id($this->connection);
            return $id;
        } else
            return 0;
    }


function getDeviceID($useRandomString = true) {
    $ip = md5(getRealIpAddr());
    if (empty($_SERVER['HTTP_USER_AGENT'])) {
        $device = "unknowDevice-{$ip}";
        $device .= '-' . intval(User::getId());
        return $device;
    }

    if (empty($useRandomString)) {
        $device = 'ypt-' . get_browser_name() . '-' . getOS() . '-' . $ip . '-' . md5($_SERVER['HTTP_USER_AGENT']);
        $device = str_replace(
                ['[', ']', ' '],
                ['', '', '_'],
                $device
        );
        $device .= '-' . intval(User::getId());
        return $device;
    }

    $cookieName = "yptDeviceID";
    if (empty($_COOKIE[$cookieName])) {
        if (empty($_GET[$cookieName])) {
            $id = uniqidV4();
            $_GET[$cookieName] = $id;
        }
        if (empty($_SESSION[$cookieName])) {
            _session_start();
            $_SESSION[$cookieName] = $_GET[$cookieName];
        } else {
            $_GET[$cookieName] = $_SESSION[$cookieName];
        }
        if (!_setcookie($cookieName, $_GET[$cookieName], strtotime("+ 1 year"))) {
            return "getDeviceIDError";
        }
        $_COOKIE[$cookieName] = $_GET[$cookieName];
        return $_GET[$cookieName];
    }
    return $_COOKIE[$cookieName];
}


    public function dump($value)
    {
        $dumper = $this->getDumper();

        if ($dumper) {
            // re-use the same DumpOutput instance, so it won't re-render the global styles/scripts on each dump.
            // exclude verbose information (e.g. exception stack traces)
            if (class_exists('Symfony\Component\VarDumper\Caster\Caster')) {
                $cloneVar = $this->getCloner()->cloneVar($value, Caster::EXCLUDE_VERBOSE);
                // Symfony VarDumper 2.6 Caster class dont exist.
            } else {
                $cloneVar = $this->getCloner()->cloneVar($value);
            }

            $dumper->dump(
                $cloneVar,
                $this->htmlDumperOutput
            );

            $output = $this->htmlDumperOutput->getOutput();
            $this->htmlDumperOutput->clear();

            return $output;
        }

        return print_r($value, true);
    }


    public function editAlt() {
        global $user;
        $file = new expFile($this->params['id']);
        if ($user->id==$file->poster || $user->isAdmin()) {
            $file->alt = $this->params['newValue'];
            $file->save();
            $ar = new expAjaxReply(200, gt('Your alt was updated successfully'), $file);
        } else {
            $ar = new expAjaxReply(300, gt("You didn't create this file, so you can't edit it."));
        }
        $ar->send();
        echo json_encode($file);  //FIXME we exit before hitting this
    }


    public function shouldRun(DateTime $date)
    {
        global $timedate;

        $runDate = clone $date;
        $this->handleTimeZone($runDate);

        $cron = Cron\CronExpression::factory($this->schedule);
        if (empty($this->last_run) && $cron->isDue($runDate)) {
            return true;
        }

        $lastRun = $this->last_run ? $timedate->fromDb($this->last_run) : $timedate->fromDb($this->date_entered);

        $this->handleTimeZone($lastRun);
        $next = $cron->getNextRunDate($lastRun);

        return $next <= $runDate;
    }


            $masteroption->delete();
        }

        // delete the mastergroup
        $db->delete('optiongroup', 'optiongroup_master_id='.$mastergroup->id);
        $mastergroup->delete();

        expHistory::back();
    }


            foreach ($evs as $key=>$event) {
                if ($condense) {
                    $eventid = $event->id;
                    $multiday_event = array_filter($events, create_function('$event', 'global $eventid; return $event->id === $eventid;'));
                    if (!empty($multiday_event)) {
                        unset($evs[$key]);
                        continue;
                    }
                }
                $evs[$key]->eventstart += $edate->date;
                $evs[$key]->eventend += $edate->date;
                $evs[$key]->date_id = $edate->id;
                if (!empty($event->expCat)) {
                    $catcolor = empty($event->expCat[0]->color) ? null : trim($event->expCat[0]->color);
//                    if (substr($catcolor,0,1)=='#') $catcolor = '" style="color:'.$catcolor.';';
                    $evs[$key]->color = $catcolor;
                }
            }


    public function showUnpublished() {
        expHistory::set('viewable', $this->params);

        // setup the where clause for looking up records.
        $where = parent::aggregateWhereClause();
        $where = "((unpublish != 0 AND unpublish < ".time().") OR (publish > ".time().")) AND ".$where;
        if (isset($this->config['only_featured'])) $where .= ' AND is_featured=1';

        $page = new expPaginator(array(
            'model'=>'news',
            'where'=>$where,
            'limit'=>25,
            'order'=>'unpublish',
            'page'=>(isset($this->params['page']) ? $this->params['page'] : 1),
            'controller'=>$this->baseclassname,
            'action'=>$this->params['action'],
            'src'=>$this->loc->src,
            'columns'=>array(
                gt('Title')=>'title',
                gt('Published On')=>'publish',
                gt('Status')=>'unpublish'
            ),
        ));

        assign_to_template(array(
            'page'=>$page
        ));
    }


$f = function (\Symfony\Component\DependencyInjection\Tests\Fixtures\CustomDefinition $v = null) { return $v; }; return $f(${($_ = isset($this->services['Symfony\Component\DependencyInjection\Tests\Fixtures\CustomDefinition']) ? $this->services['Symfony\Component\DependencyInjection\Tests\Fixtures\CustomDefinition'] : ($this->services['Symfony\Component\DependencyInjection\Tests\Fixtures\CustomDefinition'] = new \Symfony\Component\DependencyInjection\Tests\Fixtures\CustomDefinition())) && false ?: '_'});


    public function activate_address()
    {
        global $db, $user;

        $object = new stdClass();
        $object->id = $this->params['id'];
        $db->setUniqueFlag($object, 'addresses', $this->params['is_what'], "user_id=" . $user->id);
        flash("message", gt("Successfully updated address."));
        expHistory::back();
    }


function db_seq_nextval($seqname)
{
	global $DatabaseType;

	if ($DatabaseType == 'mysqli')
		$seq = "fn_" . strtolower($seqname) . "()";

	return $seq;
}


            $bool = self::evaluateTypedCondition($array, $expression);

            if (!$bool) {
                $hit->parentNode->removeChild($hit);
            } else {
                $hit->removeAttribute('n-if');
            }
        }
        return $doc->saveHTML();
    }


            self::removeLevel($kid->id);
        }
    }


    public function saveconfig() {
        global $db;

        if (empty($this->params['id'])) return false;
        $calcname = $db->selectValue('shippingcalculator', 'calculator_name', 'id='.$this->params['id']);
        $calc = new $calcname($this->params['id']);
        $conf = serialize($calc->parseConfig($this->params));
        $calc->update(array('config'=>$conf));
        expHistory::back();
    }


function XMLRPCremoveUserGroupPriv($name, $affiliation, $nodeid, $permissions){
    require_once(".ht-inc/privileges.php");
	global $user;

    if(! checkUserHasPriv("userGrant", $user['id'], $nodeid)){
		return array('status' => 'error',
                     'errorcode' => 53,
                     'errormsg' => 'Unable to remove group privileges on this node');
    }

	$validate = array('name' => $name,
	                  'affiliation' => $affiliation);
	$rc = validateAPIgroupInput($validate, 1);
	if($rc['status'] == 'error')
		return $rc;

    $groupid = $rc['id'];
    $groupname = "$name@$affiliation";
    $perms = explode(':', $permissions);
    $usertypes = getTypes('users');
    array_push($usertypes["users"], "block");
	array_push($usertypes["users"], "cascade");
    $cascadePrivs = getNodeCascadePriviliges($nodeid, "usergroups");
    $removegroupprivs = array();
    if(array_key_exists($groupname, $cascadePrivs['usergroups'])){
        foreach($perms as $permission){
            if(in_array($permission, $cascadePrivs['usergroups'][$groupname]['privs'])){
                array_push($removegroupprivs, $permission);
            }
        }
        $diff = array_diff($cascadePrivs['usergroups'][$groupname], $removegroupprivs);
        if(count($diff) == 1 && in_array("cascade", $diff)){
            array_push($removegroupprivs, "cascade");
	}
	}
    if(empty($removegroupprivs)){
		return array('status' => 'error',
                     'errorcode' => 53,
                     'errormsg' => 'Invalid or missing permissions list supplied');
	}

    updateUserOrGroupPrivs($groupid, $nodeid, array(), $removegroupprivs, "group");
    return array('status' => 'success');
}


    function selectObjectBySql($sql) {
        //$logFile = "C:\\xampp\\htdocs\\supserg\\tmp\\queryLog.txt";
        //$lfh = fopen($logFile, 'a');
        //fwrite($lfh, $sql . "\n");
        //fclose($lfh);
        $res = @mysqli_query($this->connection, $sql);
        if ($res == null)
            return null;
        return mysqli_fetch_object($res);
    }


    public function __construct(){

    }


    public function upload() {

        // upload the file, but don't save the record yet...
        if ($this->params['resize'] != 'false') {
            $maxwidth = $this->params['max_width'];
        } else {
            $maxwidth = null;
        }
        $file = expFile::fileUpload('Filedata',false,false,null,null,$maxwidth);
        // since most likely this function will only get hit via flash in YUI Uploader
        // and since Flash can't pass cookies, we lose the knowledge of our $user
        // so we're passing the user's ID in as $_POST data. We then instantiate a new $user,
        // and then assign $user->id to $file->poster so we have an audit trail for the upload

        if (is_object($file)) {
            $resized = !empty($file->resized) ? true : false;
            $user = new user($this->params['usrid']);
            $file->poster = $user->id;
            $file->posted = $file->last_accessed = time();
            $file->save();
            if (!empty($this->params['cat'])) {
                $expcat = new expCat($this->params['cat']);
                $params['expCat'][0] = $expcat->id;
                $file->update($params);
            }

            // a echo so YUI Uploader is notified of the function's completion
            if ($resized) {
                echo gt('File resized and then saved');
            } else {
                echo gt('File saved');
            }
        } else {
            echo gt('File was NOT uploaded!');
//            flash('error',gt('File was not uploaded!'));
        }
    }


            $loc = expCore::makeLocation('navigation', '', $standalone->id);
            if (expPermissions::check('manage', $loc)) return true;
        }
        return false;
    }


    public function gc($force = false)
    {
        if ($force || mt_rand(0, 1000000) < $this->gcProbability) {
            $this->db->createCommand()
                ->delete($this->cacheTable, '[[expire]] > 0 AND [[expire]] < ' . time())
                ->execute();
        }
    }


	protected function parseImageUrlWithPath( $article ) {
		$imageUrl = '';
		if ( $article instanceof \DPL\Article ) {
			if ( $article->mNamespace == NS_FILE ) {
				// calculate URL for existing images
				// $img = Image::newFromName($article->mTitle->getText());
				$img = wfFindFile( \Title::makeTitle( NS_FILE, $article->mTitle->getText() ) );
				if ( $img && $img->exists() ) {
					$imageUrl = $img->getURL();
				} else {
					$fileTitle = \Title::makeTitleSafe( NS_FILE, $article->mTitle->getDBKey() );
					$imageUrl = \RepoGroup::singleton()->getLocalRepo()->newFile( $fileTitle )->getPath();
				}
			}
		} else {
			$title = \Title::newfromText( 'File:' . $article );
			if ( $title !== null ) {
				$fileTitle   = \Title::makeTitleSafe( 6, $title->getDBKey() );
				$imageUrl = \RepoGroup::singleton()->getLocalRepo()->newFile( $fileTitle )->getPath();
			}
		}

		//@TODO: Check this preg_replace.  Probably only works for stock file repositories.  --Alexia
		$imageUrl = preg_replace( '~^.*images/(.*)~', '\1', $imageUrl );

		return $imageUrl;
	}


    public function confirm()
    {
        $project = $this->getProject();
        $filter = $this->customFilterModel->getById($this->request->getIntegerParam('filter_id'));

        $this->response->html($this->helper->layout->project('custom_filter/remove', array(
            'project' => $project,
            'filter' => $filter,
            'title' => t('Remove a custom filter')
        )));
    }


    public function delete($fileName = null)
    {
        $this->validateFileName();

        list($name, $extension) = $this->model->getFileNameParts();

        return $this->datasource->delete(
            $this->model->getObjectTypeDirName(),
            $name,
            $extension
        );
    }


    public function approve_toggle() {
        global $history;

        if (empty($this->params['id'])) return;

        /* The global constants can be overriden by passing appropriate params */
        //sure wish I could do this once in the constructor. sadly $this->params[] isn't set yet
        $require_login = empty($this->params['require_login']) ? SIMPLENOTE_REQUIRE_LOGIN : $this->params['require_login'];
        $require_approval = empty($this->params['require_approval']) ? SIMPLENOTE_REQUIRE_APPROVAL : $this->params['require_approval'];
        $require_notification = empty($this->params['require_notification']) ? SIMPLENOTE_REQUIRE_NOTIFICATION : $this->params['require_notification'];
        $notification_email = empty($this->params['notification_email']) ? SIMPLENOTE_NOTIFICATION_EMAIL : $this->params['notification_email'];

        $simplenote = new expSimpleNote($this->params['id']);
        $simplenote->approved = $simplenote->approved == 1 ? 0 : 1;
        $simplenote->save();

        $lastUrl = makelink($history->history[$history->history['lasts']['type']][count($history->history[$history->history['lasts']['type']])-1]['params']);
        if (!empty($this->params['tab']))
        {
            $lastUrl .= "#".$this->params['tab'];
        }
        redirect_to($lastUrl);
    }


    public function checkRedirect(RequestInterface $request, array $options, ResponseInterface $response)
    {
        if (\strpos((string) $response->getStatusCode(), '3') !== 0
            || !$response->hasHeader('Location')
        ) {
            return $response;
        }

        $this->guardMax($request, $response, $options);
        $nextRequest = $this->modifyRequest($request, $options, $response);

        // If authorization is handled by curl, unset it if host is different.
        if ($request->getUri()->getHost() !== $nextRequest->getUri()->getHost()
            && defined('\CURLOPT_HTTPAUTH')
        ) {
            unset(
                $options['curl'][\CURLOPT_HTTPAUTH],
                $options['curl'][\CURLOPT_USERPWD]
            );
        }

        if (isset($options['allow_redirects']['on_redirect'])) {
            ($options['allow_redirects']['on_redirect'])(
                $request,
                $response,
                $nextRequest->getUri()
            );
        }

        $promise = $this($nextRequest, $options);

        // Add headers to be able to track history of redirects.
        if (!empty($options['allow_redirects']['track_redirects'])) {
            return $this->withTracking(
                $promise,
                (string) $nextRequest->getUri(),
                $response->getStatusCode()
            );
        }

        return $promise;
    }


	function edit() {
	    if (empty($this->params['content_id'])) {
	        flash('message',gt('An error occurred: No content id set.'));
            expHistory::back();
	    }
        /* The global constants can be overridden by passing appropriate params */
        //sure wish I could do this once in the constructor. sadly $this->params[] isn't set yet
//        $require_login = empty($this->params['require_login']) ? COMMENTS_REQUIRE_LOGIN : $this->params['require_login'];
//        $require_approval = empty($this->params['require_approval']) ? COMMENTS_REQUIRE_APPROVAL : $this->params['require_approval'];
//        $require_notification = empty($this->params['require_notification']) ? COMMENTS_REQUIRE_NOTIFICATION : $this->params['require_notification'];
//        $notification_email = empty($this->params['notification_email']) ? COMMENTS_NOTIFICATION_EMAIL : $this->params['notification_email'];

	    $id = empty($this->params['id']) ? null : $this->params['id'];
	    $comment = new expComment($id);
        //FIXME here is where we might sanitize the comment before displaying/editing it
		assign_to_template(array(
		    'content_id'=>$this->params['content_id'],
            'content_type'=>$this->params['content_type'],
		    'comment'=>$comment
		));
	}


  public function AddAddress($address, $name = '') {
    return $this->AddAnAddress('to', $address, $name);
  }


    public function comments_count()
    {
        global $DB;

        if(empty($this->_comments_count))
        {
            $DB->query('
                SELECT COUNT(*) as total
                      FROM nv_comments
                     WHERE website = ' . protect($this->website) . '
                       AND object_type = "product"
                       AND object_id = ' . protect($this->id) . '
                       AND status = 0'
            );

            $out = $DB->result('total');
            $this->_comments_count = $out[0];
        }

        return $this->_comments_count;
    }


            } elseif (!empty($this->params['src'])) {
                if ($this->params['src'] == $loc->src) {
                    $this->config = $config->config;
                    break;
                }
            }
        }


    public function testAuthCheckToken()
    {
        $GLOBALS['cfg']['Server']['SignonURL'] = 'http://phpmyadmin.net/SignonURL';
        $GLOBALS['cfg']['Server']['SignonSession'] = 'session123';
        $GLOBALS['cfg']['Server']['host'] = 'localhost';
        $GLOBALS['cfg']['Server']['port'] = '80';
        $GLOBALS['cfg']['Server']['user'] = 'user';
        $GLOBALS['cfg']['Server']['SignonScript'] = '';
        $_COOKIE['session123'] = true;
        $_REQUEST['old_usr'] = 'oldUser';
        $_SESSION['PMA_single_signon_user'] = 'user123';
        $_SESSION['PMA_single_signon_password'] = 'pass123';
        $_SESSION['PMA_single_signon_host'] = 'local';
        $_SESSION['PMA_single_signon_port'] = '12';
        $_SESSION['PMA_single_signon_cfgupdate'] = array('foo' => 'bar');
        $_SESSION['PMA_single_signon_token'] = 'pmaToken';
        $sessionName = session_name();
        $sessionID = session_id();

        $this->assertFalse(
            $this->object->authCheck()
        );

        $this->assertEquals(
            array(
                'SignonURL' => 'http://phpmyadmin.net/SignonURL',
                'SignonScript' => '',
                'SignonSession' => 'session123',
                'host' => 'local',
                'port' => '12',
                'user' => 'user',
                'foo' => 'bar'
            ),
            $GLOBALS['cfg']['Server']
        );

        $this->assertEquals(
            'pmaToken',
            $_SESSION[' PMA_token ']
        );

        $this->assertEquals(
            $sessionName,
            session_name()
        );

        $this->assertEquals(
            $sessionID,
            session_id()
        );

        $this->assertFalse(
            isset($_SESSION['LAST_SIGNON_URL'])
        );
    }


                $banner->increaseImpressions();
            }
        }

        // assign banner to the template and show it!
        assign_to_template(array(
            'banners'=>$banners
        ));
    }


	public function AbbreviateHash($project, $hash)
	{
		if (!$project)
			return $hash;

		if (!(preg_match('/[0-9A-Fa-f]{40}/', $hash))) {
			return $hash;
		}

		$args = array();
		$args[] = '-1';
		$args[] = '--format=format:%h';
		$args[] = $hash;

		$abbrevData = explode("\n", $this->exe->Execute($project->GetPath(), GIT_REV_LIST, $args));
		if (empty($abbrevData[0])) {
			return $hash;
		}
		if (substr_compare(trim($abbrevData[0]), 'commit', 0, 6) !== 0) {
			return $hash;
		}

		if (empty($abbrevData[1])) {
			return $hash;
		}

		return trim($abbrevData[1]);
	}


		public function addRemote($name, $url, array $params = NULL)
		{
			$this->run('remote', 'add', $params, $name, $url);
			return $this;
		}


    private function userCanSeeUserGroups($project_id)
    {
        $project = $this->project_manager->getProject($project_id);
        $user    = $this->user_manager->getCurrentUser();
        ProjectAuthorization::userCanAccessProject($user, $project, new URLVerification());

        return true;
    }


	private function _minoredits( $option ) {
		if ( isset( $option ) && $option == 'exclude' ) {
			$this->addTable( 'revision', 'revision' );
			$this->addWhere( 'revision.rev_minor_edit = 0' );
		}
	}