    public static function lang($vars) {

        $file = GX_PATH.'/inc/lang/'.$vars.'.lang.php';
        if (file_exists($file)) {

            include($file);

        }

    }


            foreach ($allgroups as $gid) {
                $g = group::getGroupById($gid);
                expPermissions::grantGroup($g, 'manage', $sloc);
            }


$contents = ['form' => tep_draw_form('customer_data_groups', 'customer_data_groups.php', 'page=' . $_GET['page'] . '&action=insert')];


    function remove() {
        global $db;

        $section = $db->selectObject('section', 'id=' . $this->params['id']);
        if ($section) {
            section::removeLevel($section->id);
            $db->decrement('section', 'rank', 1, 'rank > ' . $section->rank . ' AND parent=' . $section->parent);
            $section->parent = -1;
            $db->updateObject($section, 'section');
            expSession::clearAllUsersSessionCache('navigation');
            expHistory::back();
        } else {
            notfoundController::handle_not_authorized();
        }
    }


	public static function login() {
		user::login(expString::sanitize($_POST['username']),expString::sanitize($_POST['password']));
		if (!isset($_SESSION[SYS_SESSION_KEY]['user'])) {  // didn't successfully log in
			flash('error', gt('Invalid Username / Password'));
			if (expSession::is_set('redirecturl_error')) {
				$url = expSession::get('redirecturl_error');
				expSession::un_set('redirecturl_error');
				header("Location: ".$url);
			} else {
				expHistory::back();
			}
		} else {  // we're logged in
			global $user;

            if (expSession::get('customer-login')) expSession::un_set('customer-login');
			if (!empty($_POST['username'])) flash('message', gt('Welcome back').' '.expString::sanitize($_POST['username']));
            if ($user->isAdmin()) {
                expHistory::back();
            } else {
                foreach ($user->groups as $g) {
                    if (!empty($g->redirect)) {
                        $url = URL_FULL.$g->redirect;
                        break;
                    }
                }
                if (isset($url)) {
                    header("Location: ".$url);
                } else {
                    expHistory::back();
                }
            }
		}
	}


    public static function getLatestVersion ($now) {

        $v = file_get_contents("https://raw.githubusercontent.com/semplon/GeniXCMS/master/VERSION");

        $arr = array(
                'version' => trim($v),
                'last_check' => $now
            );
        $arr = json_encode($arr);

        Options::update('system_check', $arr);

        return $v;

    }


    public function confirm() {
        global $db;

        // make sure we have what we need.
        if (empty($this->params['key'])) expQueue::flashAndFlow('error', gt('The security key for account was not supplied.'));
        if (empty($this->params['id'])) expQueue::flashAndFlow('error', gt('The subscriber id for account was not supplied.'));

        // verify the id/key pair
        $id = $db->selectValue('subscribers','id', 'id='.$this->params['id'].' AND hash="'.$this->params['key'].'"');
        if (empty($id)) expQueue::flashAndFlow('error', gt('We could not find any subscriptions matching the ID and Key you provided.'));

        // activate this users pending subscriptions
        $sub = new stdClass();
        $sub->enabled = 1;
        $db->updateObject($sub, 'expeAlerts_subscribers', 'subscribers_id='.$id);

        // find the users active subscriptions
        $ealerts = expeAlerts::getBySubscriber($id);
        assign_to_template(array(
            'ealerts'=>$ealerts
        ));
    }


    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 pathTestNoAuthority()
    {
        return [
            // path-rootless
            ['urn:example:animal:ferret:nose'],
            // path-absolute
            ['urn:/example:animal:ferret:nose'],
            ['urn:/'],
            // path-empty
            ['urn:'],
            ['urn'],
        ];
    }


    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);
    }


    protected function renderImageByImagick($code)
    {
        $backColor = $this->transparent ? new \ImagickPixel('transparent') : new \ImagickPixel('#' . str_pad(dechex($this->backColor), 6, 0, STR_PAD_LEFT));
        $foreColor = new \ImagickPixel('#' . str_pad(dechex($this->foreColor), 6, 0, STR_PAD_LEFT));

        $image = new \Imagick();
        $image->newImage($this->width, $this->height, $backColor);

        $draw = new \ImagickDraw();
        $draw->setFont($this->fontFile);
        $draw->setFontSize(30);
        $fontMetrics = $image->queryFontMetrics($draw, $code);

        $length = strlen($code);
        $w = (int) $fontMetrics['textWidth'] - 8 + $this->offset * ($length - 1);
        $h = (int) $fontMetrics['textHeight'] - 8;
        $scale = min(($this->width - $this->padding * 2) / $w, ($this->height - $this->padding * 2) / $h);
        $x = 10;
        $y = round($this->height * 27 / 40);
        for ($i = 0; $i < $length; ++$i) {
            $draw = new \ImagickDraw();
            $draw->setFont($this->fontFile);
            $draw->setFontSize((int) (mt_rand(26, 32) * $scale * 0.8));
            $draw->setFillColor($foreColor);
            $image->annotateImage($draw, $x, $y, mt_rand(-10, 10), $code[$i]);
            $fontMetrics = $image->queryFontMetrics($draw, $code[$i]);
            $x += (int) $fontMetrics['textWidth'] + $this->offset;
        }

        $image->setImageFormat('png');
        return $image->getImageBlob();
    }


    public static function _date2timestamp( $datetime, $wtz=null ) {
      if( !isset( $datetime['hour'] )) $datetime['hour'] = 0;
      if( !isset( $datetime['min'] ))  $datetime['min']  = 0;
      if( !isset( $datetime['sec'] ))  $datetime['sec']  = 0;
      if( empty( $wtz ) && ( !isset( $datetime['tz'] ) || empty(  $datetime['tz'] )))
        return mktime( $datetime['hour'], $datetime['min'], $datetime['sec'], $datetime['month'], $datetime['day'], $datetime['year'] );
      $output = $offset = 0;
      if( empty( $wtz )) {
        if( iCalUtilityFunctions::_isOffset( $datetime['tz'] )) {
          $offset = iCalUtilityFunctions::_tz2offset( $datetime['tz'] ) * -1;
          $wtz    = 'UTC';
        }
        else
          $wtz    = $datetime['tz'];
      }
      if(( 'Z' == $wtz ) || ( 'GMT' == strtoupper( $wtz )))
        $wtz      = 'UTC';
      try {
        $strdate  = sprintf( '%04d-%02d-%02d %02d:%02d:%02d', $datetime['year'], $datetime['month'], $datetime['day'], $datetime['hour'], $datetime['min'], $datetime['sec'] );
        $d        = new DateTime( $strdate, new DateTimeZone( $wtz ));
        if( 0    != $offset )  // adjust for offset
          $d->modify( $offset.' seconds' );
        $output   = $d->format( 'U' );
        unset( $d );
      }
      catch( Exception $e ) {
        $output = mktime( $datetime['hour'], $datetime['min'], $datetime['sec'], $datetime['month'], $datetime['day'], $datetime['year'] );
      }
      return $output;
    }


    public function testCanGiveCustomReason()
    {
        $r = new Response(200, [], null, '1.1', 'bar');
        $this->assertEquals('bar', $r->getReasonPhrase());
    }


    public function confirm()
    {
        $task = $this->getTask();
        $comment = $this->getComment();

        $this->response->html($this->template->render('comment/remove', array(
            'comment' => $comment,
            'task' => $task,
            'title' => t('Remove a comment')
        )));
    }


    public function testStartedOutside()
    {
        $storage = $this->getStorage();

        $this->assertFalse($storage->getSaveHandler()->isActive());
        $this->assertFalse($storage->isStarted());

        session_start();
        $this->assertTrue(isset($_SESSION));
        if (PHP_VERSION_ID >= 50400) {
            // this only works in PHP >= 5.4 where session_status is available
            $this->assertTrue($storage->getSaveHandler()->isActive());
        }
        // PHP session might have started, but the storage driver has not, so false is correct here
        $this->assertFalse($storage->isStarted());

        $key = $storage->getMetadataBag()->getStorageKey();
        $this->assertFalse(isset($_SESSION[$key]));
        $storage->start();
    }


  public function Close() {
    $this->error = null; // so there is no confusion
    $this->helo_rply = null;
    if(!empty($this->smtp_conn)) {
      // close the connection and cleanup
      fclose($this->smtp_conn);
      $this->smtp_conn = 0;
    }
  }


    public static function data($vars){
        $file = GX_THEME.'/'.$vars.'/themeinfo.php';
        $handle = fopen($file, 'r');
        $data = fread($handle, filesize($file));
        fclose($handle);
        preg_match('/\* Name: (.*)\n\*/U', $data, $matches);
        $d['name'] = $matches[1];
        preg_match('/\* Desc: (.*)\n\*/U', $data, $matches);
        $d['desc'] = $matches[1];
        preg_match('/\* Version: (.*)\n\*/U', $data, $matches);
        $d['version'] = $matches[1];
        preg_match('/\* Build: (.*)\n\*/U', $data, $matches);
        $d['build'] = $matches[1];
        preg_match('/\* Developer: (.*)\n\*/U', $data, $matches);
        $d['developer'] = $matches[1];
        preg_match('/\* URI: (.*)\n\*/U', $data, $matches);
        $d['url'] = $matches[1];
        preg_match('/\* License: (.*)\n\*/U', $data, $matches);
        $d['license'] = $matches[1];
        preg_match('/\* Icon: (.*)\n\*/U', $data, $matches);
        $d['icon'] = $matches[1];
        return $d;
    }


    public function autocomplete() {
        return;
        global $db;

        $model = $this->params['model'];
        $mod = new $model();
        $srchcol = explode(",",$this->params['searchoncol']);
        /*for ($i=0; $i<count($srchcol); $i++) {
            if ($i>=1) $sql .= " OR ";
            $sql .= $srchcol[$i].' LIKE \'%'.$this->params['query'].'%\'';
        }*/
        //    $sql .= ' AND parent_id=0';
        //eDebug($sql);

        //$res = $mod->find('all',$sql,'id',25);
        $sql = "select DISTINCT(p.id), p.title, model, sef_url, f.id as fileid from ".$db->prefix."product as p INNER JOIN ".$db->prefix."content_expfiles as cef ON p.id=cef.content_id INNER JOIN ".$db->prefix."expfiles as f ON cef.expfiles_id = f.id where match (p.title,p.model,p.body) against ('" . $this->params['query'] . "') AND p.parent_id=0 order by match (p.title,p.model,p.body) against ('" . $this->params['query'] . "') desc LIMIT 25";
        //$res = $db->selectObjectsBySql($sql);
        //$res = $db->selectObjectBySql('SELECT * FROM `exponent_product`');

        $ar = new expAjaxReply(200, gt('Here\'s the items you wanted'), $res);
        $ar->send();
    }


	public function goingForthAndBackStoresFormValuesOfSecondPageAndTriggersValidationOnlyWhenGoingForward() {
		$this->browser->request('http://localhost/test/form/simpleform/ThreePageFormWithValidation');

		$this->gotoNextFormPage($this->browser->getForm());

		$form = $this->browser->getForm();
		$form['--three-page-form-with-validation']['text2-1']->setValue('My Text on the second page');
		$this->gotoPreviousFormPage($form);
		$this->gotoNextFormPage($this->browser->getForm());
		$r = $this->gotoNextFormPage($this->browser->getForm());

		$this->assertSame(' error', $this->browser->getCrawler()->filterXPath('//*[contains(@class,"error")]//input[@id="three-page-form-with-validation-text2-1"]')->attr('class'));
		$form = $this->browser->getForm();
		$form['--three-page-form-with-validation']['text2-1']->setValue('42');
		$this->gotoNextFormPage($form);

		$form = $this->browser->getForm();
		$this->assertSame('', $form['--three-page-form-with-validation']['text3-1']->getValue());
	}


public function display_sdm_thumbnail_meta_box($post) {  // Thumbnail upload metabox
	$old_thumbnail = get_post_meta($post->ID, 'sdm_upload_thumbnail', true);
	$old_value = isset($old_thumbnail) ? $old_thumbnail : '';
	_e('Manually enter a valid URL, or click "Select Image" to upload (or choose) the file thumbnail image.', 'simple-download-monitor');
	?>

	<input id="sdm_upload_thumbnail" type="text" size="100" name="sdm_upload_thumbnail" value="<?php echo $old_value; ?>" placeholder="http://..." />

	<input id="upload_thumbnail_button" type="button" class="button-primary" value="<?php _e('Select Image', 'simple-download-monitor'); ?>" />
	<input id="remove_thumbnail_button" type="button" class="button" value="<?php _e('Remove Image', 'simple-download-monitor'); ?>" />

	    <?php
	    if (!empty($old_value)) {
		?><img id="sdm_thumbnail_image" src="<?php echo $old_value; ?>" style="max-width:200px;" />
		<?php
	    }
	    ?>

	<?php
	echo '
';
	_e('This thumbnail image will be used to create a fancy file download box if you want to use it.', 'simple-download-monitor');
	echo '
';

	wp_nonce_field('sdm_thumbnail_box_nonce', 'sdm_thumbnail_box_nonce_check');
    }


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

        $page = new expPaginator(array(
			'model'=>'order_status',
			'where'=>1,
            'limit'=>10,
			'order'=>'rank',
            'page'=>(isset($this->params['page']) ? $this->params['page'] : 1),
            'controller'=>$this->params['controller'],
            'action'=>$this->params['action'],
            //'columns'=>array('Name'=>'title')
        ));

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


    public function event()
    {
        $project = $this->getProject();
        $values = $this->request->getValues();

        if (empty($values['action_name']) || empty($values['project_id'])) {
            return $this->create();
        }

        return $this->response->html($this->template->render('action_creation/event', array(
            'values' => $values,
            'project' => $project,
            'available_actions' => $this->actionManager->getAvailableActions(),
            'events' => $this->actionManager->getCompatibleEvents($values['action_name']),
        )));
    }


    protected function checkMaintenanceMode()
    {
        if (Yii::$app->settings->get('maintenanceMode')) {
            if (!Yii::$app->user->isGuest) {
                Yii::$app->user->logout();
                Yii::$app->getView()->warn(Yii::t('error', 'Maintenance mode activated: You have been automatically logged out and will no longer have access the platform until the maintenance has been completed.'));
            }
            return Yii::$app->getResponse()->redirect(['/user/auth/login']);
        }
    }


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


    public function confirm(string $token)
    {
        try {
            $userId = $this->emailConfirmationService->checkTokenAndGetUserId($token);
        } catch (UserTokenNotFoundException $exception) {
            $this->showErrorNotification(trans('errors.email_confirmation_invalid'));

            return redirect('/register');
        } catch (UserTokenExpiredException $exception) {
            $user = $this->userRepo->getById($exception->userId);
            $this->emailConfirmationService->sendConfirmation($user);
            $this->showErrorNotification(trans('errors.email_confirmation_expired'));

            return redirect('/register/confirm');
        }

        $user = $this->userRepo->getById($userId);
        $user->email_confirmed = true;
        $user->save();

        $this->emailConfirmationService->deleteByUser($user);
        $this->showSuccessNotification(trans('auth.email_confirm_success'));
        $this->loginService->login($user, auth()->getDefaultDriver());

        return redirect('/');
    }


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

        /* 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'];

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

        $simplenote = new expSimpleNote($this->params['id']);
        assign_to_template(array(
            'simplenote'=>$simplenote,
            'require_login'=>$require_login,
            'require_approval'=>$require_approval,
            'require_notification'=>$require_notification,
            'notification_email'=>$notification_email,
            'tab'=>$this->params['tab']
        ));
    }


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;
}


  private function edebug($str) {
    if ($this->Debugoutput == "error_log") {
        error_log($str);
    } else {
        echo $str;
    }
  }


function db_seq_nextval($seqname)
{
	global $DatabaseType;

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

	return $seq;
}


    public function testCookiePathWithEmptySetCookiePath($uriPath, $cookiePath)
    {
        $response = (new Response(200))
            ->withAddedHeader(
                'Set-Cookie',
                "foo=bar; expires={$this->futureExpirationDate()}; domain=www.example.com; path=;"
            )
            ->withAddedHeader(
                'Set-Cookie',
                "bar=foo; expires={$this->futureExpirationDate()}; domain=www.example.com; path=foobar;"
            )
        ;
        $request = (new Request('GET', $uriPath))->withHeader('Host', 'www.example.com');
        $this->jar->extractCookies($request, $response);

        self::assertSame($cookiePath, $this->jar->toArray()[0]['Path']);
        self::assertSame($cookiePath, $this->jar->toArray()[1]['Path']);
    }


        foreach ($value as $valueKey => $valueValue) {
            if (\is_int($valueKey)) {
                $filteredKey = $valueKey;
            } else {
                $filteredKey = self::filterValue($valueKey, $regex, $stripTags);
            }

            if ($filteredKey === '' || $filteredKey === null) {
                continue;
            }

            $filteredValue = $valueValue;

            if (\is_array($valueValue)) {
                $filteredValue = self::filterArrayValue($valueValue, $regex, $stripTags);
            }

            if (\is_string($valueValue)) {
                $filteredValue = self::filterValue($valueValue, $regex, $stripTags);
            }

            $newReturn[$filteredKey] = $filteredValue;
        }


	function unlockTables() {
        $sql = "UNLOCK TABLES";

        $res = mysqli_query($this->connection, $sql);
        return $res;
    }


    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 urlOrExistingFilepath($fields)
    {
        if ($this->isFeedLocal($this->data)) {
            if ($this->data['Feed']['source_format'] == 'misp') {
                if (!is_dir($this->data['Feed']['url'])) {
                    return 'For MISP type local feeds, please specify the containing directory.';
                }
            } else {
                if (!file_exists($this->data['Feed']['url'])) {
                    return 'Invalid path or file not found. Make sure that the path points to an existing file that is readable and watch out for typos.';
                }
            }
        } else {
            if (!filter_var($this->data['Feed']['url'], FILTER_VALIDATE_URL)) {
                return false;
            }
        }
        return true;
    }


			$result  = $search->getSearchResults($item->query, false, true);
			if(empty($result) && !in_array($item->query, $badSearchArr)) {
				$badSearchArr[] = $item->query;
				$badSearch[$ctr2]['query'] = $item->query;
				$badSearch[$ctr2]['count'] = $db->countObjects("search_queries", "query='{$item->query}'");
				$ctr2++;
			}

		}

		//Check if the user choose from the dropdown
		if(!empty($user_default)) {
			if($user_default == $anonymous) {
				$u_id = 0;
			} else {
				$u_id = $user_default;
			}
			$where .= "user_id = {$u_id}";
		}

		//Get all the search query records
		$records = $db->selectObjects('search_queries', $where);
        for ($i = 0, $iMax = count($records); $i < $iMax; $i++) {
			if(!empty($records[$i]->user_id)) {
				$u = user::getUserById($records[$i]->user_id);
				$records[$i]->user = $u->firstname . ' ' . $u->lastname;
			}
		}

        $page = new expPaginator(array(
            'records' => $records,
            'where'=>1,
            'model'=>'search_queries',
            'limit'=>(isset($this->config['limit']) && $this->config['limit'] != '') ? 10 : $this->config['limit'],
            'order'=>empty($this->config['order']) ? 'timestamp' : $this->config['order'],
            'page'=>(isset($this->params['page']) ? $this->params['page'] : 1),
            'controller'=>$this->baseclassname,
            'action'=>$this->params['action'],
            'columns'=>array(
                'ID'=>'id',
                gt('Query')=>'query',
                gt('Timestamp')=>'timestamp',
                gt('User')=>'user_id',
            ),
        ));

        $uname['id'] = implode($uname['id'],',');
        $uname['name'] = implode($uname['name'],',');
        assign_to_template(array(
            'page'=>$page,
            'users'=>$uname,
            'user_default' => $user_default,
            'badSearch' => $badSearch
        ));

	}


    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 delete(AvailableBudget $availableBudget)
    {
        $this->abRepository->destroyAvailableBudget($availableBudget);
        session()->flash('success', trans('firefly.deleted_ab'));

        return redirect(route('budgets.index'));
    }


    function edit_optiongroup_master() {
        expHistory::set('editable', $this->params);

        $id = isset($this->params['id']) ? $this->params['id'] : null;
        $record = new optiongroup_master($id);
        assign_to_template(array(
            'record'=>$record
        ));
    }


    public function getSiteInfo()
    {
        // check for a site request param
        if(empty($this->getSite())){
            $this->setName(get_bloginfo('name'));
            $this->setDescription(get_bloginfo('description'));
            $this->setRestApiUrl(get_rest_url());
            $this->setSite(get_bloginfo('url'));
            $this->setLocal(true);
            return;
        }
        // If they forgot to add http(s), add it for them.
        if(strpos($this->getSite(), 'http://') === false && strpos($this->getSite(), 'https://') === false) {
            $this->setSite( 'http://' . $this->getSite());
        }
        // if there is one, check if it exists in wordpress.com, eg "retirementreflections.com"
        $site = trailingslashit(sanitize_text_field($this->getSite()));

        // Let's see if it's self-hosted...
        $data = $this->getSelfHostedSiteInfo($site);
//        if($data === false){
//            // Alright, there was no link to the REST API index. But maybe it's a WordPress.com site...
//            $data = $this->guessSelfHostedSiteInfo($site);
//        }
        if($data === false){
            // Alright, there was no link to the REST API index. But maybe it's a WordPress.com site...
            $data = $this->getWordPressComSiteInfo($site);
        }

        return $data;
    }


    public function subscriptions() {
        global $db;

        expHistory::set('manageable', $this->params);
        // make sure we have what we need.
        if (empty($this->params['key'])) expQueue::flashAndFlow('error', gt('The security key for account was not supplied.'));
        if (empty($this->params['id'])) expQueue::flashAndFlow('error', gt('The subscriber id for account was not supplied.'));

        // verify the id/key pair
        $sub = new subscribers($this->params['id']);
        if (empty($sub->id)) expQueue::flashAndFlow('error', gt('We could not find any subscriptions matching the ID and Key you provided.'));

        // get this users subscriptions
        $subscriptions = $db->selectColumn('expeAlerts_subscribers', 'expeAlerts_id', 'subscribers_id='.$sub->id);

        // get a list of all available E-Alerts
        $ealerts = new expeAlerts();
        assign_to_template(array(
            'subscriber'=>$sub,
            'subscriptions'=>$subscriptions,
            'ealerts'=>$ealerts->find('all')
        ));
    }


    protected function renderImageByGD($code)
    {
        $image = imagecreatetruecolor($this->width, $this->height);

        $backColor = imagecolorallocate(
            $image,
            (int) ($this->backColor % 0x1000000 / 0x10000),
            (int) ($this->backColor % 0x10000 / 0x100),
            $this->backColor % 0x100
        );
        imagefilledrectangle($image, 0, 0, $this->width - 1, $this->height - 1, $backColor);
        imagecolordeallocate($image, $backColor);

        if ($this->transparent) {
            imagecolortransparent($image, $backColor);
        }

        $foreColor = imagecolorallocate(
            $image,
            (int) ($this->foreColor % 0x1000000 / 0x10000),
            (int) ($this->foreColor % 0x10000 / 0x100),
            $this->foreColor % 0x100
        );

        $length = strlen($code);
        $box = imagettfbbox(30, 0, $this->fontFile, $code);
        $w = $box[4] - $box[0] + $this->offset * ($length - 1);
        $h = $box[1] - $box[5];
        $scale = min(($this->width - $this->padding * 2) / $w, ($this->height - $this->padding * 2) / $h);
        $x = 10;
        $y = round($this->height * 27 / 40);
        for ($i = 0; $i < $length; ++$i) {
            $fontSize = (int) (mt_rand(26, 32) * $scale * 0.8);
            $angle = mt_rand(-10, 10);
            $letter = $code[$i];
            $box = imagettftext($image, $fontSize, $angle, $x, $y, $foreColor, $this->fontFile, $letter);
            $x = $box[2] + $this->offset;
        }

        imagecolordeallocate($image, $foreColor);

        ob_start();
        imagepng($image);
        imagedestroy($image);

        return ob_get_clean();
    }


    public function getTrackingId()
    {
        if(isset($this->ectid)) return $this->ectid;
        else return '';
    }


    public function autocomplete() {
        return;
        global $db;

        $model = $this->params['model'];
        $mod = new $model();
        $srchcol = explode(",",$this->params['searchoncol']);
        /*for ($i=0; $i<count($srchcol); $i++) {
            if ($i>=1) $sql .= " OR ";
            $sql .= $srchcol[$i].' LIKE \'%'.$this->params['query'].'%\'';
        }*/
        //    $sql .= ' AND parent_id=0';
        //eDebug($sql);

        //$res = $mod->find('all',$sql,'id',25);
        $sql = "select DISTINCT(p.id), p.title, model, sef_url, f.id as fileid from ".$db->prefix."product as p INNER JOIN ".$db->prefix."content_expfiles as cef ON p.id=cef.content_id INNER JOIN ".$db->prefix."expfiles as f ON cef.expfiles_id = f.id where match (p.title,p.model,p.body) against ('" . $this->params['query'] . "') AND p.parent_id=0 order by match (p.title,p.model,p.body) against ('" . $this->params['query'] . "') desc LIMIT 25";
        //$res = $db->selectObjectsBySql($sql);
        //$res = $db->selectObjectBySql('SELECT * FROM `exponent_product`');

        $ar = new expAjaxReply(200, gt('Here\'s the items you wanted'), $res);
        $ar->send();
    }


    function delete_option_master() {
        global $db;

        $masteroption = new option_master($this->params['id']);

        // delete any implementations of this option master
        $db->delete('option', 'option_master_id='.$masteroption->id);
        $masteroption->delete('optiongroup_master_id=' . $masteroption->optiongroup_master_id);
        //eDebug($masteroption);
        expHistory::back();
    }


    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')
        )));
    }


    private function getTaskLink()
    {
        $link = $this->taskLinkModel->getById($this->request->getIntegerParam('link_id'));

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

        return $link;
    }


public static function insert ($vars) {
        if(is_array($vars)){
            $set = "";
            $k = "";
            foreach ($vars['key'] as $key => $val) {
                $set .= "'$val',";
                $k .= "`$key`,";
            }

            $set = substr($set, 0,-1);
            $k = substr($k, 0,-1);

            $sql = sprintf("INSERT INTO `%s` (%s) VALUES (%s) ", $vars['table'], $k, $set) ;
        }else{
            $sql = $vars;
        }
        if(DB_DRIVER == 'mysql') {
            mysql_query('SET CHARACTER SET utf8');
            $q = mysql_query($sql) or die(mysql_error());
            self::$last_id = mysql_insert_id();
        }elseif(DB_DRIVER == 'mysqli'){
            try {
                if(!self::query($sql)){
                    printf("
Errormessage: %s
\n", self::$mysqli->error);
                }else{
                    self::$last_id = self::$mysqli->insert_id;
                }

            } catch (exception $e) {
                echo $e->getMessage();
            }

        }

        return true;
    }


    protected function markCompleted($endStatus, ServiceResponse $serviceResponse, $gatewayMessage)
    {
        parent::markCompleted($endStatus, $serviceResponse, $gatewayMessage);
        $this->createMessage(Message\VoidedResponse::class, $gatewayMessage);

        ErrorHandling::safeExtend($this->payment, 'onVoid', $serviceResponse);
    }


    public static function hasChildren($i) {
        global $sections;

        if (($i + 1) >= count($sections)) return false;
        return ($sections[$i]->depth < $sections[$i + 1]->depth) ? true : false;
    }


    public function actionGetItems(){
        $sql = 'SELECT id, name as value FROM x2_products WHERE name LIKE :qterm ORDER BY name ASC';
        $command = Yii::app()->db->createCommand($sql);
        $qterm = $_GET['term'].'%';
        $command->bindParam(":qterm", $qterm, PDO::PARAM_STR);
        $result = $command->queryAll();
        echo CJSON::encode($result); exit;
    }


        $ret = array_merge($ret, csrf_flattenpost2(1, $n, $v));
    }


    public function testAddsDefaultReason()
    {
        $r = new Response('200');
        $this->assertSame(200, $r->getStatusCode());
        $this->assertEquals('OK', $r->getReasonPhrase());
    }


    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')
        )));
    }


function generate_key($size)
{
  if (
    is_callable('openssl_random_pseudo_bytes')
    and !(version_compare(PHP_VERSION, '5.3.4') < 0 and defined('PHP_WINDOWS_VERSION_MAJOR'))
    )
  {
    return substr(
      str_replace(
        array('+', '/'),
        '',
        base64_encode(openssl_random_pseudo_bytes($size+10))
        ),
      0,
      $size
      );
  }
  else
  {
    $alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    $l = strlen($alphabet)-1;
    $key = '';
    for ($i=0; $i<$size; $i++)
    {
      $key.= $alphabet[mt_rand(0, $l)];
    }
    return $key;
  }
}


    public static function admin () {

    }


    public function active($id, $active) {
        $this->auth->checkIfOperationIsAllowed('list_users');
        $this->users_model->setActive($id, $active);
        $this->session->set_flashdata('msg', lang('users_edit_flash_msg_success'));
        redirect('users');
    }


	private function _notuses( $option ) {
		if ( count( $option ) > 0 ) {
			$where = $this->tableNames['page'] . '.page_id NOT IN (SELECT ' . $this->tableNames['templatelinks'] . '.tl_from FROM ' . $this->tableNames['templatelinks'] . ' WHERE (';
			$ors = [];
			foreach ( $option as $linkGroup ) {
				foreach ( $linkGroup as $link ) {
					$_or = '(' . $this->tableNames['templatelinks'] . '.tl_namespace=' . intval( $link->getNamespace() );
					if ( $this->parameters->getParameter( 'ignorecase' ) ) {
						$_or .= ' AND LOWER(CAST(' . $this->tableNames['templatelinks'] . '.tl_title AS char))=LOWER(' . $this->DB->addQuotes( $link->getDbKey() ) . '))';
					} else {
						$_or .= ' AND ' . $this->tableNames['templatelinks'] . '.tl_title=' . $this->DB->addQuotes( $link->getDbKey() ) . ')';
					}
					$ors[] = $_or;
				}
			}
			$where .= implode( ' OR ', $ors ) . '))';
		}
		$this->addWhere( $where );
	}


                $criteria->addCondition (
                    'user IN (' .
                        'SELECT DISTINCT b.username ' .
                        'FROM x2_group_to_user a JOIN x2_group_to_user b ' .
                        'ON a.groupId=b.groupId ' .
                        'WHERE a.username=:getAccessCriteria_username' .
                    ') OR (user = :getAccessCriteria_username)');
            } else { // default history privacy (public or assigned)
                $criteria->addCondition ("(user=:getAccessCriteria_username OR visibility=1)");
            }
        }

        if ($profile) {
            $criteria->params[':getAccessCriteria_profileUsername'] = $profile->username;
            /* only show events associated with current profile which current user has
              permission to see */
            $criteria->addCondition ("user=:getAccessCriteria_profileUsername");
            if (!Yii::app()->params->isAdmin) {
                $criteria->addCondition ("visibility=1");
            }
        }
        return $criteria;
    }


    public function clearTags() {
        $this->_tags = array(); // clear tag cache

        return (bool) CActiveRecord::model('Tags')->deleteAllByAttributes(array(
                    'type' => get_class($this->getOwner()),
                    'itemId' => $this->getOwner()->id)
        );
    }


    public function toolbar() {
//        global $user;

        $menu = array();
		$dirs = array(
			BASE.'framework/modules/administration/menus',
			BASE.'themes/'.DISPLAY_THEME.'/modules/administration/menus'
		);

		foreach ($dirs as $dir) {
		    if (is_readable($dir)) {
			    $dh = opendir($dir);
			    while (($file = readdir($dh)) !== false) {
				    if (substr($file,-4,4) == '.php' && is_readable($dir.'/'.$file) && is_file($dir.'/'.$file)) {
					    $menu[substr($file,0,-4)] = include($dir.'/'.$file);
                        if (empty($menu[substr($file,0,-4)])) unset($menu[substr($file,0,-4)]);
				    }
			    }
		    }
		}

        // sort the top level menus alphabetically by filename
		ksort($menu);
		$sorted = array();
		foreach($menu as $m) $sorted[] = $m;

        // slingbar position
        if (isset($_COOKIE['slingbar-top'])){
            $top = $_COOKIE['slingbar-top'];
        } else {
            $top = SLINGBAR_TOP;
        }

		assign_to_template(array(
            'menu'=>(bs3()) ? $sorted : json_encode($sorted),
            "top"=>$top
        ));
    }


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

        $page = new expPaginator(array(
			'model'=>'order_status',
			'where'=>1,
            'limit'=>10,
			'order'=>'rank',
            'page'=>(isset($this->params['page']) ? $this->params['page'] : 1),
            'controller'=>$this->params['controller'],
            'action'=>$this->params['action'],
            //'columns'=>array('Name'=>'title')
        ));

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


    public function __construct () {

    }


	function unlockTables() {
        $sql = "UNLOCK TABLES";

        $res = mysqli_query($this->connection, $sql);
        return $res;
    }


    public function __construct(UserInviteService $inviteService, LoginService $loginService, UserRepo $userRepo)
    {
        $this->middleware('guest');
        $this->middleware('guard:standard');

        $this->inviteService = $inviteService;
        $this->loginService = $loginService;
        $this->userRepo = $userRepo;
    }


   static function getRSSFeed($url, $cache_duration = DAY_TIMESTAMP) {
      global $CFG_GLPI;

      $feed = new SimplePie();
      $feed->set_cache_location(GLPI_RSS_DIR);
      $feed->set_cache_duration($cache_duration);

      // proxy support
      if (!empty($CFG_GLPI["proxy_name"])) {
         $prx_opt = [];
         $prx_opt[CURLOPT_PROXY]     = $CFG_GLPI["proxy_name"];
         $prx_opt[CURLOPT_PROXYPORT] = $CFG_GLPI["proxy_port"];
         if (!empty($CFG_GLPI["proxy_user"])) {
            $prx_opt[CURLOPT_HTTPAUTH]     = CURLAUTH_ANYSAFE;
            $prx_opt[CURLOPT_PROXYUSERPWD] = $CFG_GLPI["proxy_user"].":".
                                             Toolbox::decrypt($CFG_GLPI["proxy_passwd"],
                                                              GLPIKEY);
         }
         $feed->set_curl_options($prx_opt);
      }

      $feed->enable_cache(true);
      $feed->set_feed_url($url);
      $feed->force_feed(true);
      // Initialize the whole SimplePie object.  Read the feed, process it, parse it, cache it, and
      // all that other good stuff.  The feed's information will not be available to SimplePie before
      // this is called.
      $feed->init();

      // We'll make sure that the right content type and character encoding gets set automatically.
      // This function will grab the proper character encoding, as well as set the content type to text/html.
      $feed->handle_content_type();
      if ($feed->error()) {
         return false;
      }
      return $feed;
   }


    function fopen($filename, $mode)
    {
        if (\yiiunit\framework\base\SecurityTest::$fopen !== null) {
            return \yiiunit\framework\base\SecurityTest::$fopen;
        }

        return \fopen($filename, $mode);
    }


    protected function defaultExtensions()
    {
        return [
            'jpg',
            'jpeg',
            'bmp',
            'png',
            'webp',
            'gif',
            'svg',
            'js',
            'map',
            'ico',
            'css',
            'less',
            'scss',
            'ics',
            'odt',
            'doc',
            'docx',
            'ppt',
            'pptx',
            'pdf',
            'swf',
            'txt',
            'xml',
            'ods',
            'xls',
            'xlsx',
            'eot',
            'woff',
            'woff2',
            'ttf',
            'flv',
            'wmv',
            'mp3',
            'ogg',
            'wav',
            'avi',
            'mov',
            'mp4',
            'mpeg',
            'webm',
            'mkv',
            'rar',
            'xml',
            'zip'
        ];
    }


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

        $this->response->html($this->template->render('subtask_converter/show', array(
            'subtask' => $subtask,
            'task' => $task,
        )));
    }


    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();
    }


	public function post_prop () {
		$file = urldecode (join ('/', func_get_args ()));
		if (! FileManager::verify_file ($file)) {
			return $this->error (__ ('Invalid file name'));
		}

		// handle multiple properties at once
		if (isset ($_POST['props'])) {
			if (! is_array ($_POST['props'])) {
				return $this->error (__ ('Invalid properties'));
			}

			foreach ($_POST['props'] as $k => $v) {
				if (FileManager::prop ($file, $k, $v) === false) {
					return $this->error (__ ('Error saving properties.'));
				}
			}

			return array (
				'file' => $file,
				'props' => $_POST['props'],
				'msg' => __ ('Properties saved.')
			);
		}

		// handle a single property
		if (! isset ($_POST['prop'])) {
			return $this->error (__ ('Missing property name'));
		}
		if (isset ($_POST['value'])) {
			// update and fetch
			$res = FileManager::prop ($file, $_POST['prop'], $_POST['value']);
		} else {
			// fetch
			$res = FileManager::prop ($file, $_POST['prop']);
		}
		return array (
			'file' => $file,
			'prop' => $_POST['prop'],
			'value' => $res,
			'msg' => __ ('Properties saved.')
		);
	}


	public function showall() {
	    expHistory::set('viewable', $this->params);
	    $hv = new help_version();
	    //$current_version = $hv->find('first', 'is_current=1');
	    $ref_version = $hv->find('first', 'version=\''.$this->help_version.'\'');

        // pagination parameter..hard coded for now.
		$where = $this->aggregateWhereClause();
	    $where .= 'AND help_version_id='.(empty($ref_version->id)?'0':$ref_version->id);


    function move_standalone() {
        expSession::clearAllUsersSessionCache('navigation');
        assign_to_template(array(
            'parent' => $this->params['parent'],
        ));
    }


    protected function registerBackendPermissions()
    {
        BackendAuth::registerCallback(function ($manager) {
            $manager->registerPermissions('October.Backend', [
                'backend.access_dashboard' => [
                    'label' => 'system::lang.permissions.view_the_dashboard',
                    'tab'   => 'system::lang.permissions.name'
                ],
                'backend.manage_default_dashboard' => [
                    'label' => 'system::lang.permissions.manage_default_dashboard',
                    'tab'   => 'system::lang.permissions.name',
                ],
                'backend.manage_users' => [
                    'label' => 'system::lang.permissions.manage_other_administrators',
                    'tab'   => 'system::lang.permissions.name'
                ],
                'backend.impersonate_users' => [
                    'label' => 'system::lang.permissions.impersonate_users',
                    'tab'   => 'system::lang.permissions.name',
                ],
                'backend.manage_preferences' => [
                    'label' => 'system::lang.permissions.manage_preferences',
                    'tab'   => 'system::lang.permissions.name'
                ],
                'backend.manage_editor' => [
                    'label' => 'system::lang.permissions.manage_editor',
                    'tab'   => 'system::lang.permissions.name'
                ],
                'backend.manage_branding' => [
                    'label' => 'system::lang.permissions.manage_branding',
                    'tab'   => 'system::lang.permissions.name'
                ],
                'media.manage_media' => [
                    'label' => 'backend::lang.permissions.manage_media',
                    'tab' => 'system::lang.permissions.name',
                ]
            ]);
        });
    }


    function searchCategory() {
        return gt('Event');
    }


    protected function _move($source, $targetDir, $name)
    {
        $target = $this->_joinPath($targetDir, $name);
        return $this->connect->rename($source, $target) ? $target : false;
    }


        foreach ($flatArray as $key => $value) {
            $pattern = '/' . $key . '([^.]|$)/';
            if (preg_match($pattern, $expression, $matches)) {

                switch (gettype($flatArray[$key])) {
                    case 'boolean':
                        $expression = str_replace($key, $flatArray[$key] ? 'true' : 'false', $expression);
                        break;
                    case 'NULL':
                        $expression = str_replace($key, 'false', $expression);
                        break;
                    case 'string':
                        $expression = str_replace($key, '"' . $flatArray[$key] . '"', $expression);
                        break;
                    case 'object':
                        $expression = self::executeClosure($expression, $key, $flatArray[$key], $flatArray);
                        break;
                    default:
                        $expression = str_replace($key, $flatArray[$key], $expression);
                        break;
                }
                $bool = eval("return $expression;");
            }
        }


                    $db->updateObject($value, 'section');
                }
                $db->updateObject($moveSec, 'section');
                //handle re-ranking of previous parent
                $oldSiblings = $db->selectObjects("section", "parent=" . $oldParent . " AND rank>" . $oldRank . " ORDER BY rank");
                $rerank      = 1;
                foreach ($oldSiblings as $value) {
                    if ($value->id != $moveSec->id) {
                        $value->rank = $rerank;
                        $db->updateObject($value, 'section');
                        $rerank++;
                    }
                }
                if ($oldParent != $moveSec->parent) {
                    //we need to re-rank the children of the parent that the moving section has just left
                    $childOfLastMove = $db->selectObjects("section", "parent=" . $oldParent . " ORDER BY rank");
                    for ($i = 0, $iMax = count($childOfLastMove); $i < $iMax; $i++) {
                        $childOfLastMove[$i]->rank = $i;
                        $db->updateObject($childOfLastMove[$i], 'section');
                    }
                }
            }
        }
        self::checkForSectionalAdmins($move);
        expSession::clearAllUsersSessionCache('navigation');
    }


    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 getDisplayName ($plural=true) {
        return Yii::t('contacts', '{contact} List|{contact} Lists', array(
            (int) $plural,
            '{contact}' => Modules::displayName(false, 'Contacts'),
        ));
    }


    protected function moveVotes()
    {
        $sql = "SELECT * FROM package_proposal_votes WHERE pkg_prop_id = {$this->proposal}";
        $res = $this->mdb2->query($sql);
        if (MDB2::isError($res)) {
            throw new RuntimeException("DB error occurred: {$res->getDebugInfo()}");
        }
        if ($res->numRows() == 0) {
            return; // nothing to do
        }

        $insert  = "INSERT INTO package_proposal_comments (";
        $insert .= "user_handle, pkg_prop_id, timestamp, comment";
        $insert .= ") VALUES(%s, {$this->proposal}, %d, %s)";

        $delete  = "DELETE FROM package_proposal_votes WHERE";
        $delete .= " pkg_prop_id = {$this->proposal}";
        $delete .= " AND user_handle = %s";

        while ($row = $res->fetchRow(MDB2_FETCHMODE_OBJECT)) {

            $comment  = "Original vote: {$row->value}\n";
            $comment .= "Conditional vote: " . ($row->is_conditional != 0)?'yes':'no' . "\n";
            $comment .= "Comment on vote: " . $row->comment . "\n\n";
            $comment .= "Reviewed: " . implode(", ", unserialize($row->reviews));

            $sql = sprintf(
                $insert,
                $this->mdb2->quote($row->user_handle),
                $row->timestamp,
                $this->mdb2->quote($comment)
            );
            $this->queryChange($sql);

            $sql = sprintf(
                $delete,
                $this->mdb2->quote($row->user_handle)
            );
            $this->queryChange($sql);
        }


    public static function filterValue($value, $regex, $stripTags = true)
    {
        if (empty($value)) {
            return $value;
        }

        if ($stripTags) {
            $value = strip_tags($value);
        }

        if (preg_match($regex, $value)) {
            return null;
        }

        return $value;
    }


	public function save()
	{
		global $DB;

		if(!empty($this->id))
			return $this->update();
		else
			return $this->insert();
	}


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


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


            $file = explode('.', $lang);
            if ($var == $file[0]) {
                $sel = 'SELECTED';
            }else{
                $sel = '';
            }
            $opt .= "<option {$sel}>{$file[0]}</option>";
        }
        return $opt;
    }


    public function search() {
//        global $db, $user;
        global $db;

        $sql = "select DISTINCT(a.id) as id, a.firstname as firstname, a.middlename as middlename, a.lastname as lastname, a.organization as organization, a.email as email ";
        $sql .= "from " . $db->prefix . "addresses as a "; //R JOIN " .
        //$db->prefix . "billingmethods as bm ON bm.addresses_id=a.id ";
        $sql .= " WHERE match (a.firstname,a.lastname,a.email,a.organization) against ('" . $this->params['query'] .
            "*' IN BOOLEAN MODE) ";
        $sql .= "order by match (a.firstname,a.lastname,a.email,a.organization)  against ('" . $this->params['query'] . "*' IN BOOLEAN MODE) ASC LIMIT 12";
        $res = $db->selectObjectsBySql($sql);
        foreach ($res as $key=>$record) {
            $res[$key]->title = $record->firstname . ' ' . $record->lastname;
        }
        //eDebug($sql);
        $ar = new expAjaxReply(200, gt('Here\'s the items you wanted'), $res);
        $ar->send();
    }


    function get(&$dbh, $proposalId, $handle)
    {
        $sql = "SELECT *, UNIX_TIMESTAMP(timestamp) AS timestamp FROM package_proposal_votes WHERE pkg_prop_id = ". $dbh->quoteSmart($proposalId) ." AND user_handle= ". $dbh->quoteSmart($handle);
        $res = $dbh->query($sql);
        if (DB::isError($res)) {
            return $res;
        }
        if (!$res->numRows()) {
            return null;
        }
        $set = $res->fetchRow(DB_FETCHMODE_ASSOC);
        $set['reviews'] = unserialize($set['reviews']);
        $vote = new ppVote($set);
        return $vote;
    }


    public function params()
    {
        $project = $this->getProject();
        $values = $this->request->getValues();

        if (empty($values['action_name']) || empty($values['project_id']) || empty($values['event_name'])) {
            $this->create();
            return;
        }

        $action = $this->actionManager->getAction($values['action_name']);
        $action_params = $action->getActionRequiredParameters();

        if (empty($action_params)) {
            $this->doCreation($project, $values + array('params' => array()));
        }

        $projects_list = $this->projectUserRoleModel->getActiveProjectsByUser($this->userSession->getId());
        unset($projects_list[$project['id']]);

        $this->response->html($this->template->render('action_creation/params', array(
            'values' => $values,
            'action_params' => $action_params,
            'columns_list' => $this->columnModel->getList($project['id']),
            'users_list' => $this->projectUserRoleModel->getAssignableUsersList($project['id']),
            'projects_list' => $projects_list,
            'colors_list' => $this->colorModel->getList(),
            'categories_list' => $this->categoryModel->getList($project['id']),
            'links_list' => $this->linkModel->getList(0, false),
            'priorities_list' => $this->projectTaskPriorityModel->getPriorities($project),
            'project' => $project,
            'available_actions' => $this->actionManager->getAvailableActions(),
            'swimlane_list' => $this->swimlaneModel->getList($project['id']),
            'events' => $this->actionManager->getCompatibleEvents($values['action_name']),
        )));
    }


    public function testFullRun()
    {
        $command = $this->getCommand();
        $commandTester = new CommandTester($command);
        $commandTester->setInputs(['no']);
        $commandTester->execute([
            'command' => $command->getName(),
        ]);

        $result = $commandTester->getDisplay();

        self::assertStringContainsString('Kimai updates running', $result);
        // make sure migrations run always
        self::assertStringContainsString('Application Migrations', $result);
        self::assertStringContainsString('No migrations to execute.', $result);

        self::assertStringContainsString(
            sprintf('[OK] Congratulations! Successfully updated Kimai to version %s (%s)', Constants::VERSION, Constants::STATUS),
            $result
        );

        self::assertEquals(0, $commandTester->getStatusCode());
    }


    public static function getHelpVersion($version_id) {
        global $db;

        return $db->selectValue('help_version', 'version', 'id="'.$version_id.'"');
    }


    public static function canView($section) {
        global $db;

        if ($section == null) {
            return false;
        }
        if ($section->public == 0) {
            // Not a public section.  Check permissions.
            return expPermissions::check('view', expCore::makeLocation('navigation', '', $section->id));
        } else { // Is public.  check parents.
            if ($section->parent <= 0) {
                // Out of parents, and since we are still checking, we haven't hit a private section.
                return true;
            } else {
                $s = $db->selectObject('section', 'id=' . $section->parent);
                return self::canView($s);
            }
        }
    }


    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 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();
        }
    }


    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 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'),
        ));
    }


    function productFeed() {
//        global $db;
        //check query password to avoid DDOS
        /*
            * condition  = new
            * description
            * id - SKU
            * link
            * price
            * title
            * brand - manufacturer
            * image link - fullsized image, up to 10, comma seperated
            * product type - category - "Electronics > Audio > Audio Accessories MP3 Player Accessories","Health & Beauty > Healthcare > Biometric Monitors > Pedometers"
         */
        $out = '"id","condition","description","like","price","title","brand","image link","product type"' . chr(13) . chr(10);

        $p = new product();
        $prods = $p->find('all', 'parent_id=0 AND ');
        //$prods =  $db->selectObjects('product','parent_id=0 AND');
    }


    public static function insert($vars){
        if(is_array($vars)){
            $sql = array(
                        'table' => 'menus',
                        'key' => $vars
                    );
            $menu = Db::insert($sql);
        }
    }


    private function load($id)
    {
        global $zdb;
        try {
            $select = $zdb->select(self::TABLE);
            $select->limit(1)->where(self::PK . ' = ' . $id);

            $results = $zdb->execute($select);
            $res = $results->current();

            $this->id = $id;
            $this->short = $res->short_label;
            $this->long = $res->long_label;
        } catch (Throwable $e) {
            Analog::log(
                'An error occurred loading title #' . $id . "Message:\n" .
                $e->getMessage(),
                Analog::ERROR
            );
            throw $e;
        }
    }


	public function approvedFileExtension($filename, $type = 'image')
	{
		$ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
		if ($type == 'image') {
			switch ($ext) {
				case 'gif':
				case 'png':
				case 'jpeg':
				case 'jpg':
				case 'svg':
					return true;
				default:
					return false;
			}
		} elseif ($type == 'cert') {
			switch ($ext) {
				case 'pem':
					return true;
				default:
					return false;
			}
		}
	}


    public static function getIconName($module)
    {
        return isset(static::$iconNames[$module])
            ? static::$iconNames[$module]
            : strtolower(str_replace('_', '-', $module));
    }


    public static function dropdown($vars) {

        return Categories::dropdown($vars);

    }


    public function testSetSaveHandler53()
    {
        if (PHP_VERSION_ID >= 50400) {
            $this->markTestSkipped('Test skipped, for PHP 5.3 only.');
        }

        $this->iniSet('session.save_handler', 'files');
        $storage = $this->getStorage();
        $storage->setSaveHandler();
        $this->assertInstanceOf('Symfony\Component\HttpFoundation\Session\Storage\Proxy\NativeProxy', $storage->getSaveHandler());
        $storage->setSaveHandler(null);
        $this->assertInstanceOf('Symfony\Component\HttpFoundation\Session\Storage\Proxy\NativeProxy', $storage->getSaveHandler());
        $storage->setSaveHandler(new NativeSessionHandler());
        $this->assertInstanceOf('Symfony\Component\HttpFoundation\Session\Storage\Proxy\NativeProxy', $storage->getSaveHandler());
        $storage->setSaveHandler(new SessionHandlerProxy(new NullSessionHandler()));
        $this->assertInstanceOf('Symfony\Component\HttpFoundation\Session\Storage\Proxy\SessionHandlerProxy', $storage->getSaveHandler());
        $storage->setSaveHandler(new NullSessionHandler());
        $this->assertInstanceOf('Symfony\Component\HttpFoundation\Session\Storage\Proxy\SessionHandlerProxy', $storage->getSaveHandler());
        $storage->setSaveHandler(new NativeProxy());
        $this->assertInstanceOf('Symfony\Component\HttpFoundation\Session\Storage\Proxy\NativeProxy', $storage->getSaveHandler());
    }


   function prepareInputForAdd($input) {

      //If it's the first ldap directory then set it as the default directory
      if (!self::getNumberOfServers()) {
         $input['is_default'] = 1;
      }

      if (isset($input["rootdn_passwd"]) && !empty($input["rootdn_passwd"])) {
         $input["rootdn_passwd"] = Toolbox::encrypt(stripslashes($input["rootdn_passwd"]), GLPIKEY);
      }

      return $input;
   }


   function getRights($interface = 'central') {

      $values = [READ                => __('Read'),
                      CREATE              => __('Create'),
                      PURGE               => _x('button', 'Delete permanently'),
                      self::CHECKUPDATE   => __('Check for upgrade')];
      return $values;
   }


    private function formatMessage($message)
    {
        if ($this->timezone) {
            $graylogTime = new DateTime($message['message']['timestamp']);
            $offset = $this->timezone->getOffset($graylogTime);

            $timeInterval = DateInterval::createFromDateString((string) $offset . 'seconds');
            $graylogTime->add($timeInterval);
            $displayTime = $graylogTime->format('Y-m-d H:i:s');
        } else {
            $displayTime = $message['message']['timestamp'];
        }

        $device = $this->deviceFromSource($message['message']['source']);
        $level = $message['message']['level'] ?? '';
        $facility = $message['message']['facility'] ?? '';

        return [
            'severity'  => $this->severityLabel($level),
            'timestamp' => $displayTime,
            'source'    => $device ? Url::deviceLink($device) : $message['message']['source'],
            'message'   => $message['message']['message'] ?? '',
            'facility'  => is_numeric($facility) ? "($facility) " . __("syslog.facility.$facility") : $facility,
            'level'     => (is_numeric($level) && $level >= 0) ? "($level) " . __("syslog.severity.$level") : $level,
        ];
    }


function httpsTestController($serverPort) {
  $args = array('HTTPS' => '');
  var_dump(request(php_uname('n'), $serverPort, "test_https.php",
                  [], [], $args));
}


return ${($_ = isset($this->services['Symfony\Component\DependencyInjection\Tests\Dumper\Rot13EnvVarProcessor']) ? $this->services['Symfony\Component\DependencyInjection\Tests\Dumper\Rot13EnvVarProcessor'] : ($this->services['Symfony\Component\DependencyInjection\Tests\Dumper\Rot13EnvVarProcessor'] = new \Symfony\Component\DependencyInjection\Tests\Dumper\Rot13EnvVarProcessor())) && false ?: '_'};


  public function Connected() {
    if(!empty($this->smtp_conn)) {
      $sock_status = socket_get_status($this->smtp_conn);
      if($sock_status["eof"]) {
        // the socket is valid but we are not connected
        if($this->do_debug >= 1) {
            $this->edebug("SMTP -> NOTICE:" . $this->CRLF . "EOF caught while checking if connected");
        }
        $this->Close();
        return false;
      }
      return true; // everything looks good
    }
    return false;
  }


$curVal[$key] = $tp->post_toForm($val);
			}
		}

		$target = e107::getUrl()->create('user/myprofile/edit',array('id'=>USERID));

		$text = '<form method="post" action="'.$target.'" id="dataform" class="usersettings-form form-horizontal"  enctype="multipart/form-data" autocomplete="off">';

		//$text = (is_numeric($_uid) ? $rs->form_open("post", e_SELF."?".e_QUERY, "dataform", "", " class='form-horizontal' role='form' enctype='multipart/form-data'") : $rs->form_open("post", e_SELF, "dataform", "", " class='form-horizontal' role='form' enctype='multipart/form-data'"));

		if (e_QUERY == "update")
		{
			$text .= "

".str_replace("*", "*", LAN_USET_9)."
".LAN_USET_10."

";
		}

		// e107::scStyle($sc_style);
		e107::getScBatch('usersettings')->setVars($curVal)->reset();

		$USERSETTINGS_EDIT = $this->getTemplate('edit');
		$USERSETTINGS_EDIT_CAPTION = $this->getTemplate('edit_caption');

		$text .= $tp->parseTemplate($USERSETTINGS_EDIT, true, $this->sc); //ParseSC must be set to true so that custom plugin -shortcodes can be utilized.

		$text .= "
<input type='hidden' name='_uid' value='{$uuid}' />

		</form>
		";

		$caption = (isset($USERSETTINGS_EDIT_CAPTION)) ? $USERSETTINGS_EDIT_CAPTION : LAN_USET_39; // 'Update User Settings'

		$ns->tablerender($caption, $text);

	}


    public static function autoload() {
        include (GX_LIB."Vendor/autoload.php");
    }


    public function manage()
    {
        expHistory::set('manageable',$this->params);
        $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
        ));
    }


    function function_exists($name)
    {
        if (isset(\yiiunit\framework\base\SecurityTest::$functions[$name])) {
            return \yiiunit\framework\base\SecurityTest::$functions[$name];
        }

        return \function_exists($name);
    }


    public static function attach($hooks_name, $func) {
        $hooks = self::$hooks;
        $hooks[$hooks_name][] = $func;
        self::$hooks = $hooks;
        return self::$hooks;
    }


	public function save()
	{
		global $DB;

		if(!empty($this->id))
		  return $this->update();
		else
		  return $this->insert();
	}


	public function validateByMode(App\Request $request)
	{
		if ($request->isEmpty('purifyMode') || !$request->has('value')) {
			throw new \App\Exceptions\NoPermitted('ERR_ILLEGAL_VALUE', 406);
		}
		$response = new Vtiger_Response();
		$response->setResult([
			'raw' => $request->getByType('value', $request->getByType('purifyMode')),
		]);
		$response->emit();
	}


                        foreach ($days as $value) {
                            $regitem[] = $value;
                        }


    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();
    }


					$dt = date('Y-m-d', strtotime($match));
					$sql = par_rep("/'$match'/", "'$dt'", $sql);
				}
			}
			if (substr($sql, 0, 6) == "BEGIN;") {
				$array = explode(";", $sql);
				foreach ($array as $value) {
					if ($value != "") {
						$result = $connection->query($value);
						if (!$result) {
							$connection->query("ROLLBACK");
							die(db_show_error($sql, _dbExecuteFailed, mysql_error()));
						}
					}
				}
			} else {
				$result = $connection->query($sql) or die(db_show_error($sql, _dbExecuteFailed, mysql_error()));
			}
			break;
	}


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

        $this->response->html($this->helper->layout->project('column/remove', array(
            'column' => $this->columnModel->getById($this->request->getIntegerParam('column_id')),
            'project' => $project,
        )));
    }


    private function resolveTrustedProxy()
    {
        if (!$trustedProxies = Request::getTrustedProxies()) {
            return '127.0.0.1';
        }

        $firstTrustedProxy = reset($trustedProxies);

        return false !== ($i = strpos($firstTrustedProxy, '/')) ? substr($firstTrustedProxy, 0, $i) : $firstTrustedProxy;
    }


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

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

        if($type='json')
            $out = json_encode($out);

        return $out;
    }


    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
    }


	static function validUTF($string) {
		if(!mb_check_encoding($string, 'UTF-8') OR !($string === mb_convert_encoding(mb_convert_encoding($string, 'UTF-32', 'UTF-8' ), 'UTF-8', 'UTF-32'))) {
			return false;
		}
		return true;
	}


        } elseif ($part != '.') {
            $depath++;
        }


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

        $this->checkPermission($project, $filter);

        if ($this->customFilterModel->remove($filter['id'])) {
            $this->flash->success(t('Custom filter removed successfully.'));
        } else {
            $this->flash->failure(t('Unable to remove this custom filter.'));
        }

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


				$this->{$callback[0]}->{$callback[1]}($objPage, $objLayout, $this);
			}
		}

		$headBag = $this->responseContext->get(HtmlHeadBag::class);

		// Set the page title and description AFTER the modules have been generated
		$this->Template->mainTitle = $objPage->rootPageTitle;
		$this->Template->pageTitle = htmlspecialchars($headBag->getTitle());

		// Remove shy-entities (see #2709)
		$this->Template->mainTitle = str_replace('[-]', '', $this->Template->mainTitle);
		$this->Template->pageTitle = str_replace('[-]', '', $this->Template->pageTitle);

		// Meta robots tag
		$this->Template->robots = $headBag->getMetaRobots();

		// Canonical
		if ($objPage->enableCanonical)
		{
			$this->Template->canonical = $headBag->getCanonicalUriForRequest($request);
		}

		// Fall back to the default title tag
		if (!$objLayout->titleTag)
		{
			$objLayout->titleTag = '{{page::pageTitle}} - {{page::rootPageTitle}}';
		}

		// Assign the title and description
		$this->Template->title = strip_tags(System::getContainer()->get('contao.insert_tag.parser')->replaceInline($objLayout->titleTag));
		$this->Template->description = htmlspecialchars($headBag->getMetaDescription());

		// Body onload and body classes
		$this->Template->onload = trim($objLayout->onload);
		$this->Template->class = trim($objLayout->cssClass . ' ' . $objPage->cssClass);

		// Execute AFTER the modules have been generated and create footer scripts first
		$this->createFooterScripts($objLayout, $objPage);
		$this->createHeaderScripts($objPage, $objLayout);
	}


function searchName() { return gt('Webpage'); }


            Session::set(array('lang' => $lang ) );
        }


	public static function getSetting( $setting ) {
		return ( array_key_exists( $setting, self::$settings ) ? self::$settings[$setting] : null );
	}


    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();
        }
    }


	protected function init() {

		if (!($this->options['host'] || $this->options['socket'])
		||  !$this->options['user']
		||  !$this->options['pass']
		||  !$this->options['db']
		||  !$this->options['path']
		||  !$this->options['files_table']) {
			return false;
		}

		$this->db = new mysqli($this->options['host'], $this->options['user'], $this->options['pass'], $this->options['db'], $this->options['port'], $this->options['socket']);
		if ($this->db->connect_error || @mysqli_connect_error()) {
			return false;
		}

		$this->db->set_charset('utf8');

		if ($res = $this->db->query('SHOW TABLES')) {
			while ($row = $res->fetch_array()) {
				if ($row[0] == $this->options['files_table']) {
					$this->tbf = $this->options['files_table'];
					break;
				}
			}
		}

		if (!$this->tbf) {
			return false;
		}

		$this->updateCache($this->options['path'], $this->_stat($this->options['path']));

		return true;
	}


private function get_lines() {
    $data = "";
    $endtime = 0;
    /* If for some reason the fp is bad, don't inf loop */
    if (!is_resource($this->smtp_conn)) {
      return $data;
    }
    stream_set_timeout($this->smtp_conn, $this->Timeout);
    if ($this->Timelimit > 0) {
      $endtime = time() + $this->Timelimit;
    }
    while(is_resource($this->smtp_conn) && !feof($this->smtp_conn)) {
      $str = @fgets($this->smtp_conn,515);
      if($this->do_debug >= 4) {
        $this->edebug("SMTP -> get_lines(): \$data was \"$data\"" . $this->CRLF . '
');
        $this->edebug("SMTP -> get_lines(): \$str is \"$str\"" . $this->CRLF . '
');
      }
      $data .= $str;
      if($this->do_debug >= 4) {
        $this->edebug("SMTP -> get_lines(): \$data is \"$data\"" . $this->CRLF . '
');
      }
      // if 4th character is a space, we are done reading, break the loop
      if(substr($str,3,1) == " ") { break; }
      // Timed-out? Log and break
      $info = stream_get_meta_data($this->smtp_conn);
      if ($info['timed_out']) {
        if($this->do_debug >= 4) {
          $this->edebug("SMTP -> get_lines(): timed-out (" . $this->Timeout . " seconds)
");
        }
        break;
      }
      // Now check if reads took too long
      if ($endtime) {
        if (time() > $endtime) {
          if($this->do_debug >= 4) {
            $this->edebug("SMTP -> get_lines(): timelimit reached (" . $this->Timelimit . " seconds)
");
          }
          break;
        }
      }
    }
    return $data;
  }


                $banner->increaseImpressions();
            }
        }

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


    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'])));
    }


	static function convertUTF($string) {
		return $string = str_replace('?', '', htmlspecialchars($string, ENT_IGNORE, 'UTF-8'));
	}


    function &getAll(&$dbh, $proposalId)
    {
        $sql = "SELECT *, UNIX_TIMESTAMP(timestamp) AS timestamp FROM package_proposal_votes WHERE pkg_prop_id = ". $dbh->quoteSmart($proposalId) ." ORDER BY timestamp ASC";
        $res = $dbh->query($sql);
        if (DB::isError($res)) {
            return $res;
        }
        $votes = array();
        while ($set = $res->fetchRow(DB_FETCHMODE_ASSOC)) {
            $set['reviews'] = unserialize($set['reviews']);
            $votes[$set['user_handle']] = new ppVote($set);
        }
        return $votes;
    }


    function edit_order_item() {
        $oi = new orderitem($this->params['id'], true, true);
        if (empty($oi->id)) {
            flash('error', gt('Order item doesn\'t exist.'));
            expHistory::back();
        }
        $oi->user_input_fields = expUnserialize($oi->user_input_fields);
        $params['options'] = $oi->opts;
        $params['user_input_fields'] = $oi->user_input_fields;
        $oi->product           = new product($oi->product->id, true, true);
        if ($oi->product->parent_id != 0) {
            $parProd = new product($oi->product->parent_id);
            //$oi->product->optiongroup = $parProd->optiongroup;
            $oi->product = $parProd;
        }
        //FIXME we don't use selectedOpts?
//        $oi->selectedOpts = array();
//        if (!empty($oi->opts)) {
//            foreach ($oi->opts as $opt) {
//                $option = new option($opt[0]);
//                $og     = new optiongroup($option->optiongroup_id);
//                if (!isset($oi->selectedOpts[$og->id]) || !is_array($oi->selectedOpts[$og->id]))
//                    $oi->selectedOpts[$og->id] = array($option->id);
//                else
//                    array_push($oi->selectedOpts[$og->id], $option->id);
//            }
//        }
        //eDebug($oi->selectedOpts);

        assign_to_template(array(
            'oi' => $oi,
            'params' => $params
        ));
    }


    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,
        )));
    }


    public function update_discount() {
        $id = empty($this->params['id']) ? null : $this->params['id'];
        $discount = new discounts($id);
        // find required shipping method if needed
        if ($this->params['required_shipping_calculator_id'] > 0) {
            $this->params['required_shipping_method'] = $this->params['required_shipping_methods'][$this->params['required_shipping_calculator_id']];
        } else {
            $this->params['required_shipping_calculator_id'] = 0;
        }

        $discount->update($this->params);
        expHistory::back();
    }


    public function createFromBill(Request $request, Bill $bill)
    {
        $request->session()->flash('info', (string)trans('firefly.instructions_rule_from_bill', ['name' => $bill->name]));

        $this->createDefaultRuleGroup();
        $this->createDefaultRule();
        $preFilled = [
            'strict'      => true,
            'title'       => (string)trans('firefly.new_rule_for_bill_title', ['name' => $bill->name]),
            'description' => (string)trans('firefly.new_rule_for_bill_description', ['name' => $bill->name]),
        ];

        // make triggers and actions from the bill itself.

        // get triggers and actions for bill:
        $oldTriggers = $this->getTriggersForBill($bill);
        $oldActions  = $this->getActionsForBill($bill);

        $triggerCount = \count($oldTriggers);
        $actionCount  = \count($oldActions);
        $subTitleIcon = 'fa-clone';

        // title depends on whether or not there is a rule group:
        $subTitle = (string)trans('firefly.make_new_rule_no_group');

        // flash old data
        $request->session()->flash('preFilled', $preFilled);

        // put previous url in session if not redirect from store (not "create another").
        if (true !== session('rules.create.fromStore')) {
            $this->rememberPreviousUri('rules.create.uri');
        }
        session()->forget('rules.create.fromStore');

        return view(
            'rules.rule.create', compact('subTitleIcon', 'oldTriggers', 'preFilled', 'oldActions', 'triggerCount', 'actionCount', 'subTitle')
        );
    }


    public function showall() {
        expHistory::set('viewable', $this->params);
        // figure out if should limit the results
        if (isset($this->params['limit'])) {
            $limit = $this->params['limit'] == 'none' ? null : $this->params['limit'];
        } else {
            $limit = (isset($this->config['limit']) && $this->config['limit'] != '') ? $this->config['limit'] : 10;
        }
        $order = isset($this->config['order']) ? $this->config['order'] : 'publish DESC';

        // pull the news posts from the database
        $items = $this->news->find('all', $this->aggregateWhereClause(), $order);

        // merge in any RSS news and perform the sort and limit the number of posts we return to the configured amount.
        if (!empty($this->config['pull_rss'])) $items = $this->mergeRssData($items);

        // setup the pagination object to paginate the news stories.
        $page = new expPaginator(array(
            'records'=>$items,
            'limit'=>$limit,
            'order'=>$order,
            'page'=>(isset($this->params['page']) ? $this->params['page'] : 1),
            'controller'=>$this->params['controller'],
            'action'=>$this->params['action'],
            'src'=>$this->loc->src,
            'view'=>empty($this->params['view']) ? null : $this->params['view']
        ));

        assign_to_template(array(
            'page'=>$page,
            'items'=>$page->records,
            'rank'=>($order==='rank')?1:0,
            'params'=>$this->params,
        ));
    }


    function build_daterange_sql($timestamp, $endtimestamp=null, $field='date', $multiday=false) {
        if (empty($endtimestamp)) {
            $date_sql = "((".$field." >= " . expDateTime::startOfDayTimestamp($timestamp) . " AND ".$field." <= " . expDateTime::endOfDayTimestamp($timestamp) . ")";
        } else {
            $date_sql = "((".$field." >= " . expDateTime::startOfDayTimestamp($timestamp) . " AND ".$field." <= " . expDateTime::endOfDayTimestamp($endtimestamp) . ")";
        }
        if ($multiday)
            $date_sql .= " OR (" . expDateTime::startOfDayTimestamp($timestamp) . " BETWEEN ".$field." AND dateFinished)";
        $date_sql .= ")";
        return $date_sql;
    }


    private function configureDefaults(array $config)
    {
        $defaults = [
            'allow_redirects' => RedirectMiddleware::$defaultSettings,
            'http_errors'     => true,
            'decode_content'  => true,
            'verify'          => true,
            'cookies'         => false
        ];

        // Use the standard Linux HTTP_PROXY and HTTPS_PROXY if set
        if ($proxy = getenv('HTTP_PROXY')) {
            $defaults['proxy']['http'] = $proxy;
        }

        if ($proxy = getenv('HTTPS_PROXY')) {
            $defaults['proxy']['https'] = $proxy;
        }

        if ($noProxy = getenv('NO_PROXY')) {
            $cleanedNoProxy = str_replace(' ', '', $noProxy);
            $defaults['proxy']['no'] = explode(',', $cleanedNoProxy);
        }

        $this->config = $config + $defaults;

        if (!empty($config['cookies']) && $config['cookies'] === true) {
            $this->config['cookies'] = new CookieJar();
        }

        // Add the default user-agent header.
        if (!isset($this->config['headers'])) {
            $this->config['headers'] = ['User-Agent' => default_user_agent()];
        } else {
            // Add the User-Agent header if one was not already set.
            foreach (array_keys($this->config['headers']) as $name) {
                if (strtolower($name) === 'user-agent') {
                    return;
                }
            }
            $this->config['headers']['User-Agent'] = default_user_agent();
        }
    }


    public function actionSeoFileLink($url, $robots = '', $canonical = '', $inline = true, $fileName = '')
    {
        $url = base64_decode($url);
        $robots = base64_decode($robots);
        $canonical = base64_decode($canonical);
        $url = UrlHelper::absoluteUrlWithProtocol($url);
        $contents = file_get_contents($url);
        $response = Craft::$app->getResponse();
        if ($contents) {
            // Add the X-Robots-Tag header
            if (!empty($robots)) {
                $headerValue = $robots;
                $response->headers->add('X-Robots-Tag', $headerValue);
            }
            // Add the Link header
            if (!empty($canonical)) {
                $headerValue = '<'.$canonical.'>; rel="canonical"';
                $response->headers->add('Link', $headerValue);
            }
            // Ensure the file type is allowed
            // ref: https://craftcms.com/docs/3.x/config/config-settings.html#allowedfileextensions
            $allowedExtensions = Craft::$app->getConfig()->getGeneral()->allowedFileExtensions;
            if (($ext = pathinfo($fileName, PATHINFO_EXTENSION)) !== '') {
                $ext = strtolower($ext);
            }
            if ($ext === '' || !in_array($ext, $allowedExtensions, true)) {
                throw new ServerErrorHttpException(Craft::t('seomatic', 'File format not allowed.'));
            }
            // Send the file as a stream, so it can exist anywhere
            $response->sendContentAsFile(
                $contents,
                $fileName,
                [
                    'inline' => $inline,
                    'mimeType' => FileHelper::getMimeTypeByExtension($fileName)
                ]
            );
        } else {
            throw new NotFoundHttpException(Craft::t('seomatic', 'File not found.'));
        }

        return $response;
    }


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


	protected function _save($fp, $dir, $name, $stat) {
		$this->clearcache();

		$mime = $stat['mime'];
		$w = !empty($stat['width'])  ? $stat['width']  : 0;
		$h = !empty($stat['height']) ? $stat['height'] : 0;

		$id = $this->_joinPath($dir, $name);
		rewind($fp);
		$stat = fstat($fp);
		$size = $stat['size'];

		if (($tmpfile = tempnam($this->tmpPath, $this->id))) {
			if (($trgfp = fopen($tmpfile, 'wb')) == false) {
				unlink($tmpfile);
			} else {
				while (!feof($fp)) {
					fwrite($trgfp, fread($fp, 8192));
				}
				fclose($trgfp);
				chmod($tmpfile, 0644);

				$sql = $id > 0
					? 'REPLACE INTO %s (id, parent_id, name, content, size, mtime, mime, width, height) VALUES ('.$id.', %d, "%s", LOAD_FILE("%s"), %d, %d, "%s", %d, %d)'
					: 'INSERT INTO %s (parent_id, name, content, size, mtime, mime, width, height) VALUES (%d, "%s", LOAD_FILE("%s"), %d, %d, "%s", %d, %d)';
				$sql = sprintf($sql, $this->tbf, $dir, $this->db->real_escape_string($name), $this->loadFilePath($tmpfile), $size, time(), $mime, $w, $h);

				$res = $this->query($sql);
				unlink($tmpfile);

				if ($res) {
					return $id > 0 ? $id : $this->db->insert_id;
				}
			}
		}

		$content = '';
		rewind($fp);
		while (!feof($fp)) {
			$content .= fread($fp, 8192);
		}

		$sql = $id > 0
			? 'REPLACE INTO %s (id, parent_id, name, content, size, mtime, mime, width, height) VALUES ('.$id.', %d, "%s", "%s", %d, %d, "%s", %d, %d)'
			: 'INSERT INTO %s (parent_id, name, content, size, mtime, mime, width, height) VALUES (%d, "%s", "%s", %d, %d, "%s", %d, %d)';
		$sql = sprintf($sql, $this->tbf, $dir, $this->db->real_escape_string($name), $this->db->real_escape_string($content), $size, time(), $mime, $w, $h);

		unset($content);

		if ($this->query($sql)) {
			return $id > 0 ? $id : $this->db->insert_id;
		}

		return false;
	}


	public function getPurchaseOrderByJSON() {

		if(!empty($this->params['vendor'])) {
			$purchase_orders = $this->purchase_order->find('all', 'vendor_id=' . $this->params['vendor']);
		} else {
			$purchase_orders = $this->purchase_order->find('all');
		}

		echo json_encode($purchase_orders);
	}


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

        $this->response->html($this->helper->layout->project('column/remove', array(
            'column' => $this->columnModel->getById($this->request->getIntegerParam('column_id')),
            'project' => $project,
        )));
    }


    function delete_recurring() {
        $item = $this->event->find('first', 'id=' . $this->params['id']);
        if ($item->is_recurring == 1) { // need to give user options
            expHistory::set('editable', $this->params);
            assign_to_template(array(
                'checked_date' => $this->params['date_id'],
                'event'        => $item,
            ));
        } else { // Process a regular delete
            $item->delete();
        }
    }


    public static function cat($vars) {
        switch (SMART_URL) {
            case true:
                # code...
                $inFold = (Options::v('permalink_use_index_php') == "on")? "/index.php":"";
                $url = Site::$url.$inFold."/category/".$vars."/".Typo::slugify(Categories::name($vars));
                break;

            default:
                # code...
                $url = Site::$url."/?cat={$vars}";
                break;

        }

        return $url;
    }


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

        if ($this->categoryModel->remove($category['id'])) {
            $this->flash->success(t('Category removed successfully.'));
        } else {
            $this->flash->failure(t('Unable to remove this category.'));
        }

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


    public function getQuerySelect()
    {
        return "c.submitted_by AS `" . $this->name . "`";
    }


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

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


    protected function _renderVarInput_number($form, &$var, &$vars)
    {
        $value = $var->getValue($vars);
        if ($var->type->getProperty('fraction')) {
            $value = sprintf('%01.' . $var->type->getProperty('fraction') . 'f', $value);
        }
        $linfo = Horde_Nls::getLocaleInfo();
        /* Only if there is a mon_decimal_point do the
         * substitution. */
        if (!empty($linfo['mon_decimal_point'])) {
            $value = str_replace('.', $linfo['mon_decimal_point'], $value);
        }
        return sprintf('<input type="text" size="5" name="%s" id="%s" value="%s"%s />',
                       htmlspecialchars($var->getVarName()),
                       $this->_genID($var->getVarName(), false),
                       $value,
                       $this->_getActionScripts($form, $var)
               );
    }


    public function theme_switch() {
        if (!expUtil::isReallyWritable(BASE.'framework/conf/config.php')) {  // we can't write to the config.php file
            flash('error',gt('The file /framework/conf/config.php is NOT Writeable. You will be unable to change the theme.'));
        }
    	expSettings::change('DISPLAY_THEME_REAL', $this->params['theme']);
	    expSession::set('display_theme',$this->params['theme']);
	    $sv = isset($this->params['sv'])?$this->params['sv']:'';
	    if (strtolower($sv)=='default') {
	       $sv = '';
	    }
	    expSettings::change('THEME_STYLE_REAL',$sv);
	    expSession::set('theme_style',$sv);
	    expDatabase::install_dbtables();  // update tables to include any custom definitions in the new theme

        // $message = (MINIFY != 1) ? "Exponent is now minifying Javascript and CSS" : "Exponent is no longer minifying Javascript and CSS" ;
        // flash('message',$message);
	    $message = gt("You have selected the")." '".$this->params['theme']."' ".gt("theme");
	    if ($sv != '') {
		    $message .= ' '.gt('with').' '.$this->params['sv'].' '.gt('style variation');
	    }
	    flash('message',$message);
//        expSession::un_set('framework');
        expSession::set('force_less_compile', 1);
//        expTheme::removeSmartyCache();
        expSession::clearAllUsersSessionCache();
    	expHistory::returnTo('manageable');
    }


    protected function unserialize(string $data)
    {
        if (is_numeric($data)) {
            return $data;
        }

        $unserialize = $this->options['serialize'][1] ?? "unserialize";

        return $unserialize($data);
    }


    public function chmod() {
        if (!AuthUser::hasPermission('file_manager_chmod')) {
            Flash::set('error', __('You do not have sufficient permissions to change the permissions on a file or directory.'));
            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/chmod')) {
                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'];
        $data['name'] = str_replace('..', '', $data['name']);
        $file = FILES_DIR . '/' . $data['name'];

        if (file_exists($file)) {
            if (@!chmod($file, octdec($data['mode'])))
                Flash::set('error', __('Permission denied!'));
        }
        else {
            Flash::set('error', __('File or directory not found!'));
        }

        $path = substr($data['name'], 0, strrpos($data['name'], '/'));
        redirect(get_url('plugin/file_manager/browse/' . $path));
    }