	public static function dplParserFunction( &$parser ) {
		self::setLikeIntersection( false );

		$parser->addTrackingCategory( 'dpl-parserfunc-tracking-category' );

		// callback for the parser function {{#dpl:	  or   {{DynamicPageList::
		$input = "";

		$numargs = func_num_args();
		if ( $numargs < 2 ) {
			$input = "#dpl: no arguments specified";
			return str_replace( '§', '<', '§pre>§nowiki>' . $input . '§/nowiki>§/pre>' );
		}

		// fetch all user-provided arguments (skipping $parser)
		$arg_list = func_get_args();
		for ( $i = 1; $i < $numargs; $i++ ) {
			$p1 = $arg_list[$i];
			$input .= str_replace( "\n", "", $p1 ) . "\n";
		}

		$parse = new \DPL\Parse();
		$dplresult = $parse->parse( $input, $parser, $reset, $eliminate, false );
		return [ // parser needs to be coaxed to do further recursive processing
			$parser->getPreprocessor()->preprocessToObj( $dplresult, Parser::PTD_FOR_INCLUSION ),
			'isLocalObj' => true,
			'title' => $parser->getTitle()
		];
	}


    public function testNoAuthorityWithInvalidPath()
    {
        $input = 'urn://example:animal:ferret:nose';
        $uri = new Uri($input);
    }


    public function __construct () {
    }


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


public static function html() {
        new Xaptcha();
        $html = "

            ";
        if (self::isEnable()) {
            return $html;
        }else{
            return '';
        }
    }


$contents = ['form' => tep_draw_form('languages', 'languages.php', 'page=' . $_GET['page'] . '&lID=' . $lInfo->languages_id . '&action=save')];


    function send_feedback() {
        $success = false;
        if (isset($this->params['id'])) {
            $ed = new eventdate($this->params['id']);
//            $email_addrs = array();
            if ($ed->event->feedback_email != '') {
                $msgtemplate = expTemplate::get_template_for_action($this, 'email/_' . $this->params['formname'], $this->loc);
                $msgtemplate->assign('params', $this->params);
                $msgtemplate->assign('event', $ed);
                $email_addrs = explode(',', $ed->event->feedback_email);
                //This is an easy way to remove duplicates
                $email_addrs = array_flip(array_flip($email_addrs));
                $email_addrs = array_map('trim', $email_addrs);
                $mail = new expMail();
                $success += $mail->quickSend(array(
                    "text_message" => $msgtemplate->render(),
                    'to'           => $email_addrs,
                    'from'         => !empty($this->params['email']) ? $this->params['email'] : trim(SMTP_FROMADDRESS),
                    'subject'      => $this->params['subject'],
                ));
            }
        }

        if ($success) {
            flashAndFlow('message', gt('Your feedback was successfully sent.'));
        } else {
            flashAndFlow('error', gt('We could not send your feedback.  Please contact your administrator.'));
        }
    }


  public function Connect ($host, $port = false, $tval = 30) {
    //  Are we already connected?
    if ($this->connected) {
      return true;
    }

    /*
    On Windows this will raise a PHP Warning error if the hostname doesn't exist.
    Rather than supress it with @fsockopen, let's capture it cleanly instead
    */

    set_error_handler(array(&$this, 'catchWarning'));

    //  Connect to the POP3 server
    $this->pop_conn = fsockopen($host,    //  POP3 Host
                  $port,    //  Port #
                  $errno,   //  Error Number
                  $errstr,  //  Error Message
                  $tval);   //  Timeout (seconds)

    //  Restore the error handler
    restore_error_handler();

    //  Does the Error Log now contain anything?
    if ($this->error && $this->do_debug >= 1) {
      $this->displayErrors();
    }

    //  Did we connect?
    if ($this->pop_conn == false) {
      //  It would appear not...
      $this->error = array(
        'error' => "Failed to connect to server $host on port $port",
        'errno' => $errno,
        'errstr' => $errstr
      );

      if ($this->do_debug >= 1) {
        $this->displayErrors();
      }

      return false;
    }

    //  Increase the stream time-out

    //  Check for PHP 4.3.0 or later
    if (version_compare(phpversion(), '5.0.0', 'ge')) {
      stream_set_timeout($this->pop_conn, $tval, 0);
    } else {
      //  Does not work on Windows
      if (substr(PHP_OS, 0, 3) !== 'WIN') {
        socket_set_timeout($this->pop_conn, $tval, 0);
      }
    }

    //  Get the POP3 server response
    $pop3_response = $this->getResponse();

    //  Check for the +OK
    if ($this->checkResponse($pop3_response)) {
    //  The connection is established and the POP3 server is talking
    $this->connected = true;
      return true;
    }
    return false;
  }


    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 static function getParent($parent='', $menuid = ''){
        if(isset($menuid)){
            $where = " AND `menuid` = '{$menuid}'";
        }else{
            $where = '';
        }
        $sql = sprintf("SELECT * FROM `menus` WHERE `parent` = '%s' %s", $parent, $where);
        $menu = Db::result($sql);
        return $menu;
    }


function deleteAllCustomDNSEntries()
{
    $handle = fopen($customDNSFile, "r");
    if ($handle)
    {
        try
        {
            while (($line = fgets($handle)) !== false) {
                $line = str_replace("\r","", $line);
                $line = str_replace("\n","", $line);
                $explodedLine = explode (" ", $line);

                if (count($explodedLine) != 2)
                    continue;

                $ip = $explodedLine[0];
                $domain = $explodedLine[1];

                pihole_execute("-a removecustomdns ".$ip." ".$domain);
            }
        }
        catch (\Exception $ex)
        {
            return errorJsonResponse($ex->getMessage());
        }

        fclose($handle);
    }

    return successJsonResponse();
}


            foreach ($allusers as $uid) {
                $u = user::getUserById($uid);
                expPermissions::grant($u, 'manage', $sloc);
            }


    public function saveLdapConfig(){
        $login_user = $this->checkLogin();
        $this->checkAdmin();
        $ldap_open = intval(I("ldap_open")) ;
        $ldap_form = I("ldap_form") ;

        if ($ldap_open) {
            if (!$ldap_form['user_field']) {
                $ldap_form['user_field'] = 'cn';
            }
            if( !extension_loaded( 'ldap' ) ) {
               $this->sendError(10011,"你尚未安装php-ldap扩展。如果是普通PHP环境，请手动安装之。如果是使用之前官方docker镜像，则需要重新安装镜像。方法是：备份 /showdoc_data 整个目录，然后全新安装showdoc，接着用备份覆盖/showdoc_data 。然后递归赋予777可写权限。");
               return ;
            }

            $ldap_conn = ldap_connect($ldap_form['host'], $ldap_form['port']);//建立与 LDAP 服务器的连接
            if (!$ldap_conn) {
               $this->sendError(10011,"Can't connect to LDAP server");
               return ;
            }
            ldap_set_option($ldap_conn, LDAP_OPT_PROTOCOL_VERSION, $ldap_form['version']);
            $rs=ldap_bind($ldap_conn, $ldap_form['bind_dn'], $ldap_form['bind_password']);//与服务器绑定 用户登录验证 成功返回1
            if (!$rs) {
               $this->sendError(10011,"Can't bind to LDAP server");
               return ;
            }

            $result = ldap_search($ldap_conn,$ldap_form['base_dn'],"(cn=*)");
            $data = ldap_get_entries($ldap_conn, $result);

            for ($i=0; $i<$data["count"]; $i++) {
                $ldap_user = $data[$i][$ldap_form['user_field']][0] ;
                if (!$ldap_user) {
                    continue ;
                }
                //如果该用户不在数据库里，则帮助其注册
                if(!D("User")->isExist($ldap_user)){
                    D("User")->register($ldap_user,$ldap_user.time());
                }
            }
            D("Options")->set("ldap_form" , json_encode( $ldap_form)) ;
        }
        D("Options")->set("ldap_open" ,$ldap_open) ;
        $this->sendResult(array());

    }


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


    static function displayname() {
        return gt("e-Commerce Category Manager");
    }


    private static function _aesEncrypt($data, $secret)
    {
        if (!is_string($data)) {
            throw new \InvalidArgumentException('Input parameter "$data" must be a string.');
        }

        if (!function_exists("openssl_encrypt")) {
            throw new \SimpleSAML_Error_Exception('The openssl PHP module is not loaded.');
        }

        $raw    = defined('OPENSSL_RAW_DATA') ? OPENSSL_RAW_DATA : true;
        $key    = openssl_digest($secret, 'sha256');
        $method = 'AES-256-CBC';
        $ivSize = 16;
        $iv     = substr($key, 0, $ivSize);

        return $iv.openssl_encrypt($data, $method, $key, $raw, $iv);
    }


                    foreach ($day as $extevent) {
                        $event_cache = new stdClass();
                        $event_cache->feed = $extgcalurl;
                        $event_cache->event_id = $extevent->event_id;
                        $event_cache->title = $extevent->title;
                        $event_cache->body = $extevent->body;
                        $event_cache->eventdate = $extevent->eventdate->date;
                        if (isset($extevent->dateFinished) && $extevent->dateFinished != -68400)
                            $event_cache->dateFinished = $extevent->dateFinished;
                        if (isset($extevent->eventstart))
                            $event_cache->eventstart = $extevent->eventstart;
                        if (isset($extevent->eventend))
                            $event_cache->eventend = $extevent->eventend;
                        if (isset($extevent->is_allday))
                            $event_cache->is_allday = $extevent->is_allday;
                        $found = false;
                        if ($extevent->eventdate->date < $start)   // prevent duplicating events crossing month boundaries
                            $found = $db->selectObject('event_cache','feed="'.$extgcalurl.'" AND event_id="'.$event_cache->event_id.'" AND eventdate='.$event_cache->eventdate);
                        if (!$found)
                            $db->insertObject($event_cache,'event_cache');
                    }


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

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


	public function isAllowedFilename($filename){
		$allow_array = array(
			'.jpg','.jpeg','.png','.bmp','.gif','.ico','.webp',
			'.mp3','.wav','.m4a','.ogg','.webma','.mp4','.flv',
			'.mov','.webmv','.m3u8a','.flac','.mkv',
			'.zip','.tar','.gz','.tgz','.ipa','.apk','.rar','.iso','.bz2','.epub',
			'.pdf','.ofd','.swf','.epub','.xps',
			'.doc','.docx','.odt','.rtf','.docm','.dotm','.dot','.dotx','.wps','.wpt',
			'.ppt','.pptx','.xls','.xlsx','.txt','.md','.psd','.csv',
			'.cer','.ppt','.pub','.properties','.json','.css',
			) ;

		$ext = strtolower(substr($filename,strripos($filename,'.')) ); //获取文件扩展名（转为小写后）
		if(in_array( $ext , $allow_array ) ){
			return true ;
		}
		return false;
	}


    public function get($id)
    {
        if (!is_numeric($id)) {
            $this->errors[] = _T("ID must be an integer!");
            return false;
        }

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

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

            if (!$result) {
                $this->errors[] = _T("Label does not exist");
                return false;
            }

            return $result;
        } catch (Throwable $e) {
            Analog::log(
                __METHOD__ . ' | ' . $e->getMessage(),
                Analog::WARNING
            );
            throw $e;
        }
    }


    public function getSelectorsBySpecificity($sSpecificitySearch = null) {
        if (is_numeric($sSpecificitySearch) || is_numeric($sSpecificitySearch[0])) {
            $sSpecificitySearch = "== $sSpecificitySearch";
        }
        $aResult = array();
        $this->allSelectors($aResult, $sSpecificitySearch);
        return $aResult;
    }


    public static function checkPermissions($permission,$location) {
        global $exponent_permissions_r, $router;

        // only applies to the 'manage' method
        if (empty($location->src) && empty($location->int) && (!empty($router->params['action']) && $router->params['action'] == 'manage') || strpos($router->current_url, 'action=manage') !== false) {
            if (!empty($exponent_permissions_r['navigation'])) foreach ($exponent_permissions_r['navigation'] as $page) {
                foreach ($page as $pageperm) {
                    if (!empty($pageperm['manage'])) return true;
                }
            }
        }
        return false;
    }


				$item = array();
				$item['id'] = $incident->id;
				$item['title'] = $incident->incident_title;
				$item['link'] = $site_url.'reports/view/'.$incident->id;
				$item['description'] = $incident->incident_description;
				$item['date'] = $incident->incident_date;
				$item['categories'] = $categories;

				if
				(
					$incident->location_id != 0 AND
					$incident->location->longitude AND
					$incident->location->latitude
				)
				{
					$item['point'] = array(
						$incident->location->latitude,
					    $incident->location->longitude
					);
					$items[] = $item;
				}
			}

			$cache->set($subdomain.'_feed_'.$limit.'_'.$page, $items, array('feed'), 3600); // 1 Hour
			$feed_items = $items;
		}

		$feedpath = $feedtype == 'atom' ? 'feed/atom/' : 'feed/';

		//header("Content-Type: text/xml; charset=utf-8");
		$view = new View('feed/'.$feedtype);
		$view->feed_title = htmlspecialchars(Kohana::config('settings.site_name'));
		$view->site_url = $site_url;
		$view->georss = 1; // this adds georss namespace in the feed
		$view->feed_url = $site_url.$feedpath;
		$view->feed_date = gmdate("D, d M Y H:i:s T", time());
		$view->feed_description = htmlspecialchars(Kohana::lang('ui_admin.incident_feed').' '.Kohana::config('settings.site_name'));
		$view->items = $feed_items;
		$view->render(TRUE);
	}


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

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

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

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


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


            PMA_sendHeaderLocation($GLOBALS['cfg']['Server']['LogoutURL']);
        } else {
            PMA_sendHeaderLocation($GLOBALS['cfg']['Server']['SignonURL']);
        }

        if (!defined('TESTSUITE')) {
            exit();
        } else {
            return false;
        }
    }


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

        $out = array();

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

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

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

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

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

        return $out;
    }


    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 function boot()
    {
        // Configure the debugbar
        Config::set('debugbar', Config::get('rainlab.debugbar::config'));

        // Service provider
        App::register('\Barryvdh\Debugbar\ServiceProvider');

        // Register alias
        $alias = AliasLoader::getInstance();
        $alias->alias('Debugbar', '\Barryvdh\Debugbar\Facade');

        // Register middleware
        if (Config::get('app.debugAjax', false)) {
            $this->app['Illuminate\Contracts\Http\Kernel']->pushMiddleware('\RainLab\Debugbar\Middleware\Debugbar');
        }

        Event::listen('cms.page.beforeDisplay', function ($controller, $url, $page) {
            // Only show for authenticated backend users
            if (!BackendAuth::check()) {
                Debugbar::disable();
            }

            // Twig extensions
            $twig = $controller->getTwig();
            if (!$twig->hasExtension(\Barryvdh\Debugbar\Twig\Extension\Debug::class)) {
                $twig->addExtension(new \Barryvdh\Debugbar\Twig\Extension\Debug($this->app));
                $twig->addExtension(new \Barryvdh\Debugbar\Twig\Extension\Stopwatch($this->app));
            }
        });
    }


                $newret = recyclebin::restoreFromRecycleBin($iLoc, $page_id);
                if (!empty($newret)) $ret .= $newret . '<br>';
                if ($iLoc->mod == 'container') {
                    $ret .= scan_container($container->internal, $page_id);
                }
            }
            return $ret;
        }


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

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


	public function testGetFilesWithBrokenSetup() {
		$location = '';
		$features = '';
		$etag = 1111222233334444;
		$mediatypes = 'image/png';
		$exceptionMessage = 'Aïe!';
		$this->searchFolderService->expects($this->once())
								  ->method('getCurrentFolder')
								  ->with(
									  $location,
									  [$features]
								  )
								  ->willThrowException(new ServiceException($exceptionMessage));
		// Default status code when something breaks
		$status = Http::STATUS_INTERNAL_SERVER_ERROR;
		$errorMessage = [
			'message' => $exceptionMessage . ' (' . $status . ')',
			'success' => false
		];
		/** @type JSONResponse $response */
		$response = $this->controller->getList($location, $features, $etag, $mediatypes);

		$this->assertEquals($errorMessage, $response->getData());
	}


    public function setScriptSrc(Response $response)
    {
        if (config('app.allow_content_scripts')) {
            return;
        }

        $parts = [
            'http:',
            'https:',
            '\'nonce-' . $this->nonce . '\'',
            '\'strict-dynamic\'',
        ];

        $value = 'script-src ' . implode(' ', $parts);
        $response->headers->set('Content-Security-Policy', $value, false);
    }


    public function gc($force = false, $expiredOnly = true)
    {
        if ($force || mt_rand(0, 1000000) < $this->gcProbability) {
            $this->gcRecursive($this->cachePath, $expiredOnly);
        }
    }


	public function execute()
	{
		parent::execute();

		// get parameters
		$term = SpoonFilter::getPostValue('term', null, '');

		// validate
		if($term == '') $this->output(self::BAD_REQUEST, null, 'term-parameter is missing.');

		// previous search result
		$previousTerm = SpoonSession::exists('searchTerm') ? SpoonSession::get('searchTerm') : '';
		SpoonSession::set('searchTerm', '');

		// save this term?
		if($previousTerm != $term)
		{
			// format data
			$this->statistics = array();
			$this->statistics['term'] = $term;
			$this->statistics['language'] = FRONTEND_LANGUAGE;
			$this->statistics['time'] = FrontendModel::getUTCDate();
			$this->statistics['data'] = serialize(array('server' => $_SERVER));
			$this->statistics['num_results'] = FrontendSearchModel::getTotal($term);

			// save data
			FrontendSearchModel::save($this->statistics);
		}

		// save current search term in cookie
		SpoonSession::set('searchTerm', $term);

		// output
		$this->output(self::OK);
	}


    public function delete($id)
    {
        if ($this->securityController->isWikiHibernated()) {
            throw new \Exception(_t('WIKI_IN_HIBERNATION'));
        }

        // tests of if $formId is int
        if (strval(intval($id)) != strval($id)) {
            return null ;
        }

        $this->clear($id);
        return $this->dbService->query('DELETE FROM ' . $this->dbService->prefixTable('nature') . 'WHERE bn_id_nature=' . $id);
    }


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

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

        return $link;
    }


    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 MAX_adRenderImageBeacon($logUrl, $beaconId = 'beacon', $userAgent = null)
{
    if (!isset($userAgent) && isset($_SERVER['HTTP_USER_AGENT'])) {
        $userAgent = $_SERVER['HTTP_USER_AGENT'];
    }
    $beaconId .= '_{random}';
    // Add beacon image for logging
    if (isset($userAgent) && preg_match("#Mozilla/(1|2|3|4)#", $userAgent)
        && !preg_match("#compatible#", $userAgent)) {
        $div = "<layer id='{$beaconId}' width='0' height='0' border='0' visibility='hide'>";
        $style = '';
        $divEnd = '</layer>';
    } else {
        $div = "
";
        $style = " style='width: 0px; height: 0px;'";
        $divEnd = '
';
    }
        $beacon = "$div{$divEnd}";
        return $beacon;
}


    public function __destruct()
    {
        if ($this->Mailer == 'smtp') { //close any open SMTP connection nicely
            $this->smtpClose();
        }
    }


    protected function getBodyTagAttributes()
    {
        $formEngineParameters = [];
        $parameters = parent::getBodyTagAttributes();

        $formEngineParameters['fieldChangeFunc'] = $this->parameters['fieldChangeFunc'];
        $formEngineParameters['fieldChangeFuncHash'] = GeneralUtility::hmac(serialize($this->parameters['fieldChangeFunc']));

        $parameters['data-add-on-params'] .= HttpUtility::buildQueryString(['P' => $formEngineParameters], '&');

        return $parameters;
    }


    public function deleteByName(){
        $item_id = I("item_id/d");
        $env_id = I("env_id/d");
        $var_name = I("var_name");
        $login_user = $this->checkLogin();
        $uid = $login_user['uid'] ;
        if(!$this->checkItemEdit($uid , $item_id)){
            $this->sendError(10303);
            return ;
        }
        $ret = D("ItemVariable")->where(" item_id = '%d' and env_id = '%d' and var_name = '%s'  ",array($item_id,$env_id,$var_name))->delete();
        if ($ret) {
           $this->sendResult($ret);
        }else{
            $this->sendError(10101);
        }
    }


fwrite(STDERR, sprintf("%2d %s ==> %s\n", $i + 1, $test, var_export($result, true)));


	protected function GetOrderedRefs($refList, $type, $order, $count = 0, $skip = 0)
	{
		if (!$refList)
			return;

		if (empty($type) || empty($order))
			return null;

		$args = array();
		$args[] = '--sort=' . $order;
		$args[] = '--format="%(refname)"';
		if ($count > 0) {
			if ($skip > 0) {
				$args[] = '--count=' . ($count + $skip);
			} else {
				$args[] = '--count=' . $count;
			}
		}


    protected function fixupImportedAttributes($modelName, X2Model &$model) {
        if ($modelName === 'Contacts' || $modelName === 'X2Leads')
            $this->fixupImportedContactName ($model);

        if ($modelName === 'Actions' && isset($model->associationType))
            $this->reconstructImportedActionAssoc($model);

        if ($model->hasAttribute('visibility')) {
            // Nobody every remembers to set visibility... set it for them
            if(empty($model->visibility) && ($model->visibility !== 0 && $model->visibility !== "0")
                    || $model->visibility == 'Public') {
                $model->visibility = 1;
            } elseif($model->visibility == 'Private')
                $model->visibility = 0;
        }
        // If date fields were provided, do not create new values for them
        if (!empty($model->createDate) || !empty($model->lastUpdated) ||
                !empty($model->lastActivity)) {
            $now = time();
            if (empty($model->createDate))
                $model->createDate = $now;
            if (empty($model->lastUpdated))
                $model->lastUpdated = $now;
            if ($model->hasAttribute('lastActivity') && empty($model->lastActivity))
                $model->lastActivity = $now;
        }
        if($_SESSION['leadRouting'] == 1){
            $assignee = $this->getNextAssignee();
            if($assignee == "Anyone")
                $assignee = "";
            $model->assignedTo = $assignee;
        }
        // Loop through our override and set the manual data
        foreach($_SESSION['override'] as $attr => $val){
            $model->$attr = $val;
        }
    }


    public function onRouteStartup(Enlight_Controller_EventArgs $args)
    {
        $request = $args->getRequest();

        if (strpos($request->getPathInfo(), '/backend') === 0
            || strpos($request->getPathInfo(), '/api/') === 0
        ) {
            return;
        }

        $shop = $this->getShopByRequest($request);

        if (!$shop->getHost()) {
            $shop->setHost($request->getHttpHost());
        }
        if (!$shop->getBaseUrl()) {
            $preferBasePath = $this->get(Shopware_Components_Config::class)->preferBasePath;
            $shop->setBaseUrl($preferBasePath ? $request->getBasePath() : $request->getBaseUrl());
        }
        if (!$shop->getBasePath()) {
            $shop->setBasePath($request->getBasePath());
        }

        // Read original base path for resources
        $request->getBasePath();
        $request->setBaseUrl($shop->getBaseUrl());

        // Update path info
        $request->setPathInfo(
            $this->createPathInfo($request, $shop)
        );

        if (($host = $request->getHeader('X_FORWARDED_HOST')) !== null
            && $host === $shop->getHost()
        ) {
            // If the base path is null, set it to empty string. Otherwise the request will try to assemble the base path. On a reverse proxy setup with varnish this will fail on virtual URLs like /en
            // The X-Forwarded-Host header is only set in such environments
            if ($shop->getBasePath() === null) {
                $shop->setBasePath('');
            }

            $request->setSecure();
            $request->setBasePath($shop->getBasePath());
            $request->setBaseUrl($shop->getBaseUrl());
            $request->setHttpHost($shop->getHost());
        }

        $this->validateShop($shop);
        $this->get(ShopRegistrationServiceInterface::class)->registerShop($shop);
    }


            $evs = $this->event->find('all', "id=" . $edate->event_id . $featuresql);
            foreach ($evs as $key=>$event) {
                if ($condense) {
                    $eventid = $event->id;
                    $multiday_event = array_filter($events, create_function('$event', 'global $eventid; return $event->id === $eventid;'));
                    if (!empty($multiday_event)) {
                        unset($evs[$key]);
                        continue;
                    }
                }
                $evs[$key]->eventstart += $edate->date;
                $evs[$key]->eventend += $edate->date;
                $evs[$key]->date_id = $edate->id;
                if (!empty($event->expCat)) {
                    $catcolor = empty($event->expCat[0]->color) ? null : trim($event->expCat[0]->color);
//                    if (substr($catcolor,0,1)=='#') $catcolor = '" style="color:'.$catcolor.';';
                    $evs[$key]->color = $catcolor;
                }
            }
            if (count($events) < 500) {  // magic number to not crash loop?
                $events = array_merge($events, $evs);
            } else {
//                $evs[$key]->title = gt('Too many events to list').', '.(count($edates)-count($events)).' '.gt('not displayed!');
//                $events = array_merge($events, $evs);
                flash('notice',gt('Too many events to list').', '.(count($edates)-count($events)).' '.gt('not displayed!'));
                break; // keep from breaking system by too much data
            }
        }


    public static function unsetTransactionPart(Db $zdb, Login $login, $trans_id, $contrib_id)
    {
        try {
            //first, we check if contribution is part of transaction
            $c = new Contribution($zdb, $login, (int)$contrib_id);
            if ($c->isTransactionPartOf($trans_id)) {
                $update = $zdb->update(self::TABLE);
                $update->set(
                    array(Transaction::PK => null)
                )->where(
                    self::PK . ' = ' . $contrib_id
                );
                $zdb->execute($update);
                return true;
            } else {
                Analog::log(
                    'Contribution #' . $contrib_id .
                    ' is not actually part of transaction #' . $trans_id,
                    Analog::WARNING
                );
                return false;
            }
        } catch (Throwable $e) {
            Analog::log(
                'Unable to detach contribution #' . $contrib_id .
                ' to transaction #' . $trans_id . ' | ' . $e->getMessage(),
                Analog::ERROR
            );
            throw $e;
        }
    }


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


            $sloc = expCore::makeLocation('navigation', null, $section->id);
            // remove any manage permissions for this page and it's children
            // $db->delete('userpermission', "module='navigationController' AND internal=".$section->id);
            // $db->delete('grouppermission', "module='navigationController' AND internal=".$section->id);
            foreach ($allusers as $uid) {
                $u = user::getUserById($uid);
                expPermissions::grant($u, 'manage', $sloc);
            }
            foreach ($allgroups as $gid) {
                $g = group::getGroupById($gid);
                expPermissions::grantGroup($g, 'manage', $sloc);
            }
        }
    }


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

		$vendor = new vendor();
		$vendors = $vendor->find('all');
		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');
		}

		assign_to_template(array(
            'purchase_orders'=>$purchase_orders,
            'vendors' => $vendors,
            'vendor_id' => @$this->params['vendor']
        ));
	}


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


			list($workgroup, $user) = explode('\\', $user);
		} else {
			$workgroup = null;
		}
		$this->state->init($workgroup, $user, $this->server->getPassword());
	}


    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 meta_box_subject() {

		$placeholder = __( 'What is your conversation about?', 'supportflow' );
		echo '
' . __( 'Subject', 'supportflow' ) . '
';
		echo '<input type="text" id="subject" name="post_title" class="sf_autosave" placeholder="' . $placeholder . '" value="' . get_the_title() . '" autocomplete="off" />';
		echo '
' . __( 'Please describe what this ticket is about in several words', 'supportflow' ) . '
';

	}


printf('
%s
%s %s
',$row->post_title,$row->meta_key,$row->meta_value);
	}
}


    public static function isPublic($s) {
        if ($s == null) {
            return false;
        }
        while ($s->public && $s->parent > 0) {
            $s = new section($s->parent);
        }
        $lineage = (($s->public) ? 1 : 0);
        return $lineage;
    }


    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 getQueryOrderby()
    {
        return $this->name;
    }


		$stmt->bindValue(":$field", $domain, SQLITE3_TEXT);
		if($bindcomment) {
			$stmt->bindValue(":comment", $comment, SQLITE3_TEXT);
		}

		if($stmt->execute() && $stmt->reset())
			$num++;
		else
		{
			$stmt->close();
			if($returnnum)
				return $num;
			else
			{
				if($num === 1)
					$plural = "";
				else
					$plural = "s";
				return "Error: ".$db->lastErrorMsg().", added ".$num." domain".$plural;
			}
		}
	}

	// Close prepared statement and return number of processed rows
	$stmt->close();
	$db->exec("COMMIT;");

	if($returnnum)
		return $num;
	else
	{
		$finalcount = intval($db->querySingle($countquery));
		$modified = $finalcount - $initialcount;

		// If we add less domains than the user specified, then they wanted to add duplicates
		if($modified !== $num)
		{
			$delta = $num - $modified;
			$extra = " (skipped ".$delta." duplicates)";
		}
		else
		{
			$extra = "";
		}

		if($num === 1)
			$plural = "";
		else
			$plural = "s";
		return "Success, added ".$modified." of ".$num." domain".$plural.$extra;
	}
}


            foreach ($val as $k => $v) {
                unset($process[$key][$k]);
                $stripTags = \in_array($k, $whiteList) ? false : $stripTagsConf;

                if (\is_string($k)) {
                    $filteredKey = self::filterValue($k, $regex, $stripTags);
                } else {
                    $filteredKey = $k;
                }

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

                if (\is_array($v)) {
                    $process[$key][$filteredKey] = self::filterArrayValue($v, $regex, $stripTags);
                    continue;
                }

                if (\is_string($v)) {
                    $process[$key][$filteredKey] = self::filterValue($v, $regex, $stripTags);
                    continue;
                }

                $process[$key][$filteredKey] = $v;
            }


	protected function filter($files) {
		foreach ($files as $i => $file) {
			if (!empty($file['hidden']) || !$this->default->mimeAccepted($file['mime'])) {
				unset($files[$i]);
			}
		}
		return array_merge($files, array());
	}


    public static function editor($mode = 'light'){
        $editor = Options::v('use_editor');
        if($editor == 'on'){
            $GLOBALS['editor'] = true;
        }else{
            $GLOBALS['editor'] = false;
        }
        if ($mode == 'light') {
            $GLOBALS['editor_mode'] = 'light';
        }else{
            $GLOBALS['editor_mode'] = 'full';
        }

        //return $editor;
    }


    function edit_section() {
        global $db, $user;

        $parent = new section($this->params['parent']);
        if (empty($parent->id)) $parent->id = 0;
        assign_to_template(array(
            'haveStandalone'  => ($db->countObjects('section', 'parent=-1') && $parent->id >= 0),
            'parent'          => $parent,
            'isAdministrator' => $user->isAdmin(),
        ));
    }


    public static function canImportData() {
        return true;
    }


                return $fa->nameGlyph($icons, 'icon-');
            }
        } else {
            return array();
        }
    }


	public static function filesByMedia($media, $offset=0, $limit=-1, $wid=NULL, $text="", $orderby="date_added DESC, name ASC")
	{
		global $DB;
		global $website;

		if(empty($wid))
			$wid = $website->id;

		if($limit < 1)
			$limit = 2147483647;

        if(!empty($text))
            $text = ' AND name LIKE '.protect('%'.$text.'%');

		$DB->query('  SELECT SQL_CALC_FOUND_ROWS * FROM nv_files
					   WHERE type = '.protect($media).'
					     AND enabled = 1
						 AND website = '.$wid.'
						 '.$text.'
					ORDER BY '.$orderby.'
					   LIMIT '.$limit.'
					  OFFSET '.$offset);

        $total = $DB->foundRows();
        $rows = $DB->result();

		return array($rows, $total);
	}


            foreach($image->expTag as $tag) {
                if (isset($used_tags[$tag->id])) {
                    $used_tags[$tag->id]->count++;
                } else {
                    $exptag = new expTag($tag->id);
                    $used_tags[$tag->id] = $exptag;
                    $used_tags[$tag->id]->count = 1;
                }

            }


    public function actionGetItems(){
        $sql = 'SELECT id, name as value FROM x2_opportunities 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);
        Yii::app()->end();
    }


    public function __viewIndex()
    {
        $this->setPageType('table');
        $this->setTitle(__('%1$s – %2$s', array(__('Pages'), __('Symphony'))));

        $nesting = Symphony::Configuration()->get('pages_table_nest_children', 'symphony') == 'yes';

        if ($nesting && isset($_GET['parent']) && is_numeric($_GET['parent'])) {
            $parent = PageManager::fetchPageByID((int)$_GET['parent'], array('title', 'id'));
        }

        $this->appendSubheading(isset($parent) ? $parent['title'] : __('Pages'), Widget::Anchor(
            __('Create New'), Administration::instance()->getCurrentPageURL() . 'new/' . ($nesting && isset($parent) ? "?parent={$parent['id']}" : null),
            __('Create a new page'), 'create button', null, array('accesskey' => 'c')
        ));


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

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


	public function __construct(string                   $appName,
								IRequest                 $request,
								ITimeFactory             $timeFactory,
								IInitialState            $initialState,
								BookingService           $bookingService,
								AppointmentConfigService $appointmentConfigService,
								URLGenerator             $urlGenerator,
								LoggerInterface $logger) {
		parent::__construct($appName, $request);

		$this->bookingService = $bookingService;
		$this->timeFactory = $timeFactory;
		$this->appointmentConfigService = $appointmentConfigService;
		$this->initialState = $initialState;
		$this->urlGenerator = $urlGenerator;
		$this->logger = $logger;
	}


    function comments_list($params)
    {

        if (!user_can_access('module.comments.index')) {
            return;
        }

        if (!isset($params['content_id'])) {

            if (isset($params['rel_id']) and isset($params['rel_type'])) {
                $data = array(
                    'rel_id' => $params['rel_id'],
                    'rel_type' => $params['rel_type'],

                );
            }

        } else {
            $data = array(
                'content_id' => $params['content_id']
            );

        }

        if (isset($params['search-keyword']) and $params['search-keyword']) {
            $kw = $data['keyword'] = $params['search-keyword'];
            $data['search_in_fields'] = 'comment_name,comment_body,comment_email,comment_website,from_url,comment_subject';
        }

        $data['order_by'] = 'created_at desc';

        $comments = $postComments = get_comments($data);
        if (isset($params['content_id'])) {
            $content = get_content_by_id($params['content_id']);
            $content_id = $params['content_id'];
        } else {
            $content = false;
            $content_id = false;
        }

        $moderation_is_required = get_option('require_moderation', 'comments') == 'y';

        $view_file = $this->views_dir . 'comments_list.php';
        $view = new View($view_file);
        $view->assign('params', $params);
        $view->assign('comments', $comments);
        $view->assign('content_id', $content_id);
        $view->assign('content', $content);
        $view->assign('moderation_is_required', $moderation_is_required);

        return $view->display();
    }


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

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


    public static function all()
    {
        global $DB;
        global $website;

        $DB->query('SELECT *
                    FROM nv_webuser_groups
                    WHERE website = '.protect($website->id));

        return $DB->result();
    }


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

        if ($this->swimlaneModel->remove($project['id'], $swimlane_id)) {
            $this->flash->success(t('Swimlane removed successfully.'));
        } else {
            $this->flash->failure(t('Unable to remove this swimlane.'));
        }

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


    public function configure() {
        $this->config['defaultbanner'] = array();
        if (!empty($this->config['defaultbanner_id'])) {
            $this->config['defaultbanner'][] = new expFile($this->config['defaultbanner_id']);
        }
	    parent::configure();
	    $banners = $this->banner->find('all', null, 'companies_id');
	    assign_to_template(array(
            'banners'=>$banners,
            'title'=>static::displayname()
        ));
	}


    public function safePath($filename = 'data.csv'){
        return implode(DIRECTORY_SEPARATOR, array(
                    Yii::app()->basePath,
                    'data',
                    $filename
                ));
    }


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

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

        return $link;
    }


    public function testRenderWithTrustedHeaderDisabled()
    {
        Request::setTrustedHeaderName(Request::HEADER_CLIENT_IP, '');

        $strategy = new InlineFragmentRenderer($this->getKernelExpectingRequest(Request::create('/')));
        $this->assertSame('foo', $strategy->render('/', Request::create('/'))->getContent());
    }


    public static function name($id) {
        $id = sprintf('%d', $id);
        if(isset($id)){
            $cat = Db::result("SELECT `name` FROM `cat`
                                WHERE `id` = '{$id}' LIMIT 1");
            //print_r($cat);
            if(isset($cat['error'])){
                return '';
            }else{
                return $cat[0]->name;
            }

        }else{
            echo "No ID Selected";
        }

        //print_r($cat);
    }


function PMA_getErrorReportForm()
{
    $html = "";
    $html .= '<form action="error_report.php" method="post" name="report_frm"'
            . ' id="report_frm" class="ajax">'
            . '<fieldset style="padding-top:0px">';

    $html .= '
' . __(
        'phpMyAdmin has encountered an error. We have collected data about'
        . ' this error as well as information about relevant configuration'
        . ' settings to send to the phpMyAdmin team to help us in'
        . ' debugging the problem.'
    ) . '
';

    $html .= '

'
            . __('You may examine the data in the error report:')
            . '

'
            . '
'
            . PMA_getReportData()
            . '
';

    $html .= '

'
            . __('Please explain the steps that lead to the error:')
            . '

'
            . '<textarea class="report-description" name="description"'
            . 'id="report_description"></textarea>';

    $html .= '<input type="checkbox" name="always_send"'
            . ' id="always_send_checkbox"/>'
            . ''
            . __('Automatically send report next time')
            . '';

    $html .= '</fieldset>';

    $html .= PMA_URL_getHiddenInputs();

    $reportData = PMA_getReportData(false);
    if (! empty($reportData)) {
        $html .= PMA_getHiddenFields($reportData);
    }

    $html .= '</form>';

    return $html;
}


    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 actionGetItems(){
		$sql = 'SELECT id, name as value FROM x2_docs 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;
	}


	public static function client()
	{
		if (is_null(self::$client)) new CertificateAuthenticate();
		return self::$client;
	}


    public static function rss() {
        switch (SMART_URL) {
            case true:
                # code...
                $inFold = (Options::v('permalink_use_index_php') == "on")? "/index.php":"";
                $url = Site::$url.$inFold."/rss".GX_URL_PREFIX;
                break;

            default:
                # code...
                $url = Site::$url."/index.php?rss";
                break;

        }

        return $url;
    }


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


    protected function setUp()
    {
        parent::setUp();

        $mongoClass = version_compare(phpversion('mongo'), '1.3.0', '<') ? 'Mongo' : 'MongoClient';

        $this->mongo = $this->getMockBuilder($mongoClass)
            ->disableOriginalConstructor()
            ->getMock();

        $this->options = array(
            'id_field' => '_id',
            'data_field' => 'data',
            'time_field' => 'time',
            'expiry_field' => 'expires_at',
            'database' => 'sf2-test',
            'collection' => 'session-test',
        );

        $this->storage = new MongoDbSessionHandler($this->mongo, $this->options);
    }


            $q = self::query($sql);
        }
        return true;

    }


function db_seq_nextval($seqname)
{
	global $DatabaseType;

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

	return $seq;
}


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


    public function read($sessionId)
    {
        $dbData = $this->getCollection()->findOne(array(
            $this->options['id_field'] => $sessionId,
            $this->options['expiry_field'] => array('$gte' => new \MongoDate()),
        ));

        return null === $dbData ? '' : $dbData[$this->options['data_field']]->bin;
    }


function load_gallery($auc_id)
{
    $UPLOADED_PICTURES = array();
    if (is_dir(UPLOAD_PATH . $auc_id)) {
        if ($dir = opendir(UPLOAD_PATH . $auc_id)) {
            while ($file = @readdir($dir)) {
                if ($file != '.' && $file != '..' && strpos($file, 'thumb-') === false) {
                    $UPLOADED_PICTURES[] = UPLOAD_FOLDER . $auc_id . '/' . $file;
                }
            }
            closedir($dir);
        }
    }
    return $UPLOADED_PICTURES;
}


			foreach($fields as $field)
			{
				if(substr($key, 0, strlen($field.'-'))==$field.'-')
                {
                    $this->dictionary[substr($key, strlen($field.'-'))][$field] = $value;
                }
			}


    public function searchAdmin(){
        $criteria = new CDbCriteria;
        return $this->searchBase($criteria);
    }


public function checkForReassign($operator)
    {
        $operator_name = ($this->locale == get_home_locale())
            ? $operator['vclocalename']
            : $operator['vccommonname'];

        $is_operator_correct = $this->nextAgent == $operator['operatorid']
            || $this->agentId == $operator['operatorid'];

        if ($this->state == self::STATE_WAITING && $is_operator_correct) {
            // Prepare message
            if ($this->nextAgent == $operator['operatorid']) {
                $message_to_post = getlocal(
                    "Operator {0} changed operator {1}",
                    array($operator_name, $this->agentName),
                    $this->locale,
                    true
                );
            } else {
                $message_to_post = getlocal(
                    "Operator {0} is back",
                    array($operator_name),
                    $this->locale,
                    true
                );
            }

            // Update thread info
            $this->state = self::STATE_CHATTING;
            $this->nextAgent = 0;
            $this->agentId = $operator['operatorid'];
            $this->agentName = $operator_name;
            $this->save();

            // Send messages
            $this->postMessage(self::KIND_EVENTS, $message_to_post);
        }
    }


    public function __construct()
    {
        parent::__construct();

        $this->middleware(
            static function ($request, $next) {
                app('view')->share('title', (string)trans('firefly.transactions'));
                app('view')->share('mainTitleIcon', 'fa-exchange');

                return $next($request);
            }
        );
    }


function GoodAuthDigestTestController($serverPort) {
  $args = array('Authorization' => 'Digest username="admin", ' .
    'realm="Restricted area", nonce="564a12611dae8", ' .
    'uri="/test_auth_digest.php", cnonce="MjIyMTg1", nc=00000001, ' .
    'qop="auth", response="e544aaed06917adea3e5c74dd49f0e32", ' .
    'opaque="cdce8a5c95a1427d74df7acbf41c9ce0"');
  var_dump(request(php_uname('n'), $serverPort, "test_auth_digest.php",
                  [], [], $args));
}


                $section = new section(intval($page));
                if ($section) {
//                    self::deleteLevel($section->id);
                    $section->delete();
                }
            }
        }


    protected function itemLock($hashes, $autoUnlock = true)
    {
        if (!elFinder::$commonTempPath) {
            return;
        }
        if (!is_array($hashes)) {
            $hashes = array($hashes);
        }
        foreach ($hashes as $hash) {
            $lock = elFinder::$commonTempPath . DIRECTORY_SEPARATOR . $hash . '.lock';
            if ($this->itemLocked($hash)) {
                $cnt = file_get_contents($lock) + 1;
            } else {
                $cnt = 1;
            }
            if (file_put_contents($lock, $cnt, LOCK_EX)) {
                if ($autoUnlock) {
                    $this->autoUnlocks[] = $hash;
                }
            }
        }
    }


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

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

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

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


    function updateObject($object, $table, $where=null, $identifier='id', $is_revisioned=false) {

        if ($is_revisioned) {
            $object->revision_id++;
            //if ($table=="text") eDebug($object);
            $res = $this->insertObject($object, $table);
            //if ($table=="text") eDebug($object,true);
            $this->trim_revisions($table, $object->$identifier, WORKFLOW_REVISION_LIMIT);
            return $res;
        }
        $sql = "UPDATE " . $this->prefix . "$table SET ";
        foreach (get_object_vars($object) as $var => $val) {
            //We do not want to save any fields that start with an '_'
            //if($is_revisioned && $var=='revision_id') $val++;
            if ($var{0} != '_') {
                if (is_array($val) || is_object($val)) {
                    $val = serialize($val);
                    $sql .= "`$var`='".$val."',";
                } else {
                    $sql .= "`$var`='" . $this->escapeString($val) . "',";
                }
            }
        }
        $sql = substr($sql, 0, -1) . " WHERE ";
        if ($where != null)
            $sql .= $this->injectProof($where);
        else
            $sql .= "`" . $identifier . "`=" . $object->$identifier;
        //if ($table == 'text') eDebug($sql,true);
        $res = (@mysqli_query($this->connection, $sql) != false);
        return $res;
    }


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

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


    public function write($template = '')
    {
        if (!empty($this->script_files)) {
            $this->set_env('request_token', $this->app->get_request_token());
        }

        $commands = $this->get_js_commands($framed);

        // if all js commands go to parent window we can ignore all
        // script files and skip rcube_webmail initialization (#1489792)
        if ($framed) {
            $this->scripts      = array();
            $this->script_files = array();
            $this->header       = '';
            $this->footer       = '';
        }

        // write all javascript commands
        $this->add_script($commands, 'head_top');

        // send clickjacking protection headers
        $iframe = $this->framed || $this->env['framed'];
        if (!headers_sent() && ($xframe = $this->app->config->get('x_frame_options', 'sameorigin'))) {
            header('X-Frame-Options: ' . ($iframe && $xframe == 'deny' ? 'sameorigin' : $xframe));
        }


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


$contents[] = ['class' => 'text-center', 'text' => tep_draw_bootstrap_button(IMAGE_DELETE, 'fas fa-trash', null, 'primary', null, 'btn-danger xxx text-white mr-2') . tep_draw_bootstrap_button(IMAGE_CANCEL, 'fas fa-times', tep_href_link('specials.php', 'page=' . $_GET['page'] . '&sID=' . $sInfo->specials_id), null, null, 'btn-light')];


    public function contactInformationSave(Request $request) {

        session_append_array('checkout_v2', [
            'first_name'=> $request->get('first_name'),
            'last_name'=> $request->get('last_name'),
            'email'=> $request->get('email'),
            'phone'=> $request->get('phone')
        ]);

        $validate = $this->_validateContactInformation($request->all());
        if ($validate['valid'] == false) {
            session_set('errors', $validate['errors']);
            return redirect(route('checkout.contact_information'));
        }

        // Success
        return redirect(route('checkout.shipping_method'));
    }


    public function __construct() {
        global $GLOBALS, $data;
        self::$editors =& $GLOBALS;
        self::$data =& $data;
        self::$url = Options::v('siteurl');
        self::$domain = Options::v('sitedomain');
        self::$name = Options::v('sitename');
        self::$key = Options::v('sitekeywords');
        self::$desc = Options::v('sitedesc');
        self::$email = Options::v('siteemail');
        self::$slogan = Options::v('siteslogan');
    }


$p = $vars['paging']-(ceil($maxpage/2)-1);
                    $limit = $curr+ceil($maxpage/2)-1;
                    // echo "more maxpage";
                }else{
                    $p = $vars['paging']-(ceil($maxpage/2)-1);
                    $limit = $curr + floor($maxpage/2);
                }

                for ($i=$p ; $i <= $limit /*ceil($total/$vars['max'])+1*/ ; $i++ ) {
                    # code...
                    if($smart == true){
                        $url = $vars['url']."/paging/".$i;
                    }else{
                        $url = $vars['url']."&paging=".$i;
                    }
                    if($vars['paging'] == $i){ $sel = "class=\"active\"";}else{$sel='';}
                    $r .= "
$i
";
                }
                $r .= "
";
            }elseif(isset($vars['type']) && $vars['type'] == 'pager'){ // PAGER


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

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

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

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


public function Recipient($to) {
    $this->error = null; // so no confusion is caused

    if(!$this->connected()) {
      $this->error = array(
              "error" => "Called Recipient() without being connected");
      return false;
    }

    fputs($this->smtp_conn,"RCPT TO:<" . $to . ">" . $this->CRLF);

    $rply = $this->get_lines();
    $code = substr($rply,0,3);

    if($this->do_debug >= 2) {
      $this->edebug("SMTP -> FROM SERVER:" . $rply . $this->CRLF . '
');
    }

    if($code != 250 && $code != 251) {
      $this->error =
        array("error" => "RCPT not accepted from server",
              "smtp_code" => $code,
              "smtp_msg" => substr($rply,4));
      if($this->do_debug >= 1) {
        $this->edebug("SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '
');
      }
      return false;
    }
    return true;
  }


    public function withPort($port)
    {
        $port = $this->filterPort($this->scheme, $this->host, $port);

        if ($this->port === $port) {
            return $this;
        }

        $new = clone $this;
        $new->port = $port;
        return $new;
    }


    function __construct()
    {
        # code...
        self::$smtphost    = Options::get('smtphost');
        self::$smtpuser    = Options::get('smtpuser');
        self::$smtppass    = Options::get('smtppass');
        self::$smtpssl     = Options::get('smtpssl');
        self::$siteemail   = Options::get('siteemail');
        self::$sitename    = Options::get('sitename');
    }


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


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


    protected function getSubtask()
    {
        $subtask = $this->subtaskModel->getById($this->request->getIntegerParam('subtask_id'));

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

        return $subtask;
    }


	static public function customerHasTickets($_cid = 0) {

		if ($_cid != 0) {
			$result_stmt = Database::prepare("
				SELECT `id` FROM `" . TABLE_PANEL_TICKETS . "` WHERE `customerid` = :cid"
			);
			Database::pexecute($result_stmt, array('cid' => $_cid));

			$tickets = array();
			while ($row = $result_stmt->fetch(PDO::FETCH_ASSOC)) {
				$tickets[] = $row['id'];
			}

			return $tickets;
		}

		return false;
	}


    public function approve_toggle() {
        global $history;

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

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

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

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


            $src = substr($ref->source, strlen($prefix)) . $section->id;
            if (call_user_func(array($ref->module, 'hasContent'))) {
                $oloc = expCore::makeLocation($ref->module, $ref->source);
                $nloc = expCore::makeLocation($ref->module, $src);
                if ($ref->module != "container") {
                    call_user_func(array($ref->module, 'copyContent'), $oloc, $nloc);
                } else {
                    call_user_func(array($ref->module, 'copyContent'), $oloc, $nloc, $section->id);
                }
            }
        }


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


    public function breadcrumb() {
        global $sectionObj;

        expHistory::set('viewable', $this->params);
        $id      = $sectionObj->id;
        $current = null;
        // Show not only the location of a page in the hierarchy but also the location of a standalone page
        $current = new section($id);
        if ($current->parent == -1) {  // standalone page
            $navsections = section::levelTemplate(-1, 0);
            foreach ($navsections as $section) {
                if ($section->id == $id) {
                    $current = $section;
                    break;
                }
            }
        } else {
            $navsections = section::levelTemplate(0, 0);
            foreach ($navsections as $section) {
                if ($section->id == $id) {
                    $current = $section;
                    break;
                }
            }
        }
        assign_to_template(array(
            'sections'     => $navsections,
            'current'      => $current,
        ));
    }


    public static function setTransactionPart(Db $zdb, $trans_id, $contrib_id)
    {
        try {
            $update = $zdb->update(self::TABLE);
            $update->set(
                array(Transaction::PK => $trans_id)
            )->where(self::PK . ' = ' . $contrib_id);

            $zdb->execute($update);
            return true;
        } catch (Throwable $e) {
            Analog::log(
                'Unable to attach contribution #' . $contrib_id .
                ' to transaction #' . $trans_id . ' | ' . $e->getMessage(),
                Analog::ERROR
            );
            throw $e;
        }
    }


	public function delete() {
	    global $db;

        /* 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']) ? COMMENTS_REQUIRE_LOGIN : $this->params['require_login'];
//        $require_approval = empty($this->params['require_approval']) ? COMMENTS_REQUIRE_APPROVAL : $this->params['require_approval'];
//        $require_notification = empty($this->params['require_notification']) ? COMMENTS_REQUIRE_NOTIFICATION : $this->params['require_notification'];
//        $notification_email = empty($this->params['notification_email']) ? COMMENTS_NOTIFICATION_EMAIL : $this->params['notification_email'];

	    if (empty($this->params['id'])) {
	        flash('error', gt('Missing id for the comment you would like to delete'));
	        expHistory::back();
	    }

	    // delete the comment
        $comment = new expComment($this->params['id']);
        $comment->delete();

        // delete the association too
        $db->delete($comment->attachable_table, 'expcomments_id='.$this->params['id']);

        // send the user back where they came from.
        expHistory::back();
	}


    function update_option_master() {
        global $db;

        $id = empty($this->params['id']) ? null : $this->params['id'];
        $opt = new option_master($id);
        $oldtitle = $opt->title;

        $opt->update($this->params);

        // if the title of the master changed we should update the option groups that are already using it.
        if ($oldtitle != $opt->title) {

        }$db->sql('UPDATE '.$db->prefix.'option SET title="'.$opt->title.'" WHERE option_master_id='.$opt->id);

        expHistory::back();
    }


	public function read($source) {
		$source = $this->escapePath($source);
		// close the single quote, open a double quote where we put the single quote...
		$source = str_replace('\'', '\'"\'"\'', $source);
		// since returned stream is closed by the caller we need to create a new instance
		// since we can't re-use the same file descriptor over multiple calls
		$command = sprintf('%s --authentication-file=/proc/self/fd/3 //%s/%s -c \'get %s /proc/self/fd/5\'',
			Server::CLIENT,
			$this->server->getHost(),
			$this->name,
			$source
		);
		$connection = new Connection($command);
		$connection->writeAuthentication($this->server->getUser(), $this->server->getPassword());
		$fh = $connection->getFileOutputStream();
		stream_context_set_option($fh, 'file', 'connection', $connection);
		return $fh;
	}


			$dplArg = $this->wgRequest->getVal( $arg, '' );
			if ( $dplArg == '' ) {
				$input = preg_replace( '/\{%' . $arg . ':(.*)%\}/U', '\1', $input );
				$input = str_replace( '{%' . $arg . '%}', '', $input );
			} else {
				$input = preg_replace( '/\{%' . $arg . ':.*%\}/U  ', $dplArg, $input );
				$input = str_replace( '{%' . $arg . '%}', $dplArg, $input );
			}
		}
		return $input;
	}


            $resultItem['qtip'] = $item->getDescription() ? $item->getDescription() : ' ';
            $result[] = $resultItem;
        }

        return $this->adminJson($result);
    }


	public function enqueue_scripts() {
		global $geo_mashup_options, $pagenow, $post;

		// The location editor works only on posts
		if ( empty( $post ) )
			return null;

		$load_location_editor = (
				is_admin() and
				preg_match( '/(post|page)(-new|).php/', $pagenow ) and
				in_array( $post->post_type, $geo_mashup_options->get( 'overall', 'located_post_types' ) )
				);
		$load_location_editor = apply_filters( 'geo_mashup_load_location_editor', $load_location_editor );

		// If we're on a post editing page, queue up the form interface elements
		if ( $load_location_editor ) {

			$this->enqueue_form_client_items();

		}
	}


function fm_get_size($file)
{
    static $iswin;
    static $isdarwin;
    if (!isset($iswin)) {
        $iswin = (strtoupper(substr(PHP_OS, 0, 3)) == 'WIN');
    }
    if (!isset($isdarwin)) {
        $isdarwin = (strtoupper(substr(PHP_OS, 0)) == "DARWIN");
    }

    static $exec_works;
    if (!isset($exec_works)) {
        $exec_works = (function_exists('exec') && !ini_get('safe_mode') && @exec('echo EXEC') == 'EXEC');
    }

    // try a shell command
    if ($exec_works) {
        $cmd = ($iswin) ? "for %F in (\"$file\") do @echo %~zF" : ($isdarwin ? "stat -f%z \"$file\"" : "stat -c%s \"$file\"");
        @exec($cmd, $output);
        if (is_array($output) && ctype_digit($size = trim(implode("\n", $output)))) {
            return $size;
        }
    }

    // try the Windows COM interface
    if ($iswin && class_exists("COM")) {
        try {
            $fsobj = new COM('Scripting.FileSystemObject');
            $f = $fsobj->GetFile( realpath($file) );
            $size = $f->Size;
        } catch (Exception $e) {
            $size = null;
        }
        if (ctype_digit($size)) {
            return $size;
        }
    }

    // if all else fails
    return filesize($file);
}


    public static function go($input, $path, $allowed='', $uniq=false, $size='', $width = '', $height = ''){
        $filename = Typo::cleanX($_FILES[$input]['name']);
        $filename = str_replace(' ', '_', $filename);
        if(isset($_FILES[$input]) && $_FILES[$input]['error'] == 0){
            if($uniq == true){
                $uniqfile = sha1(microtime().$filename);
            }else{
                $uniqfile = '';
            }

            $extension = pathinfo($_FILES[$input]['name'], PATHINFO_EXTENSION);
            $filetmp = $_FILES[$input]['tmp_name'];
            $filepath = GX_PATH.$path.$uniqfile.$filename;

            if(!in_array(strtolower($extension), $allowed)){
                $result['error'] = 'File not allowed';
            }else{
                if(move_uploaded_file(
                    $filetmp,
                    $filepath)
                ){
                    $result['filesize'] = filesize($filepath);
                    $result['filename'] = $uniqfile.$filename;
                    $result['path'] = $path.$uniqfile.$filename;
                    $result['filepath'] = $filepath;
                    $result['fileurl'] = Options::get('siteurl').$path.$uniqfile.$filename;

                }else{
                    $result['error'] = 'Cannot upload to directory, please check
                    if directory is exist or You had permission to write it.';
                }
            }

        }else{
            //$result['error'] = $_FILES[$input]['error'];
             $result['error'] = '';
        }

        return $result;

    }


				$this->paths[substr($key, strlen('path-'))] = $value;
		}


	public function getList($location, $features, $etag, $mediatypes) {
		$featuresArray = explode(';', $features);
		$mediaTypesArray = explode(';', $mediatypes);
		try {
			return $this->getFilesAndAlbums($location, $featuresArray, $etag, $mediaTypesArray);
		} catch (\Exception $exception) {
			return $this->jsonError($exception);
		}
	}


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

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

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


    public static function ajax ($vars="", $val='') {

        if( isset($vars) && $vars != "" ) {

            $file = GX_PATH.'/inc/lib/Control/Ajax/'.$vars.'-ajax.control.php';
            if (file_exists($file)) {

                include($file);

            }else {
                self::error('404');
            }

        }

    }


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


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


                    $method = $this->request->get('_method', $this->query->get('_method', 'POST'));
                    if (\is_string($method)) {
                        $this->method = strtoupper($method);
                    }
                }
            }
        }


	protected function GetRefs($refList, $type)
	{
		if (!$refList)
			return;

		if (empty($type))
			return;

		$args = array();
		$args[] = '--' . $type;
		$args[] = '--dereference';
		$ret = $this->exe->Execute($refList->GetProject()->GetPath(), GIT_SHOW_REF, $args);

		$lines = explode("\n", $ret);

		$refs = array();
		$commits = array();

		foreach ($lines as $line) {
			if (preg_match('/^([0-9a-fA-F]{40}) refs\/' . $type . '\/([^^]+)(\^{})?$/', $line, $regs)) {
				if (!empty($regs[3]) && ($regs[3] == '^{}')) {
					$commits[$regs[2]] = $regs[1];
				} else {
					$refs[$regs[2]] = $regs[1];
				}
			}
		}

		return array($refs, $commits);
	}


                        $product = X2Model::model('Products')->findByAttributes(array('name'=>$lineItem->name));
                        if (isset($product))
                            $lineItem->productId = $product->id;
            if(empty($lineItem->currency))
				$lineItem->currency = $defaultCurrency;
			if($lineItem->isPercentAdjustment) {
				$lineItem->adjustment = Fields::strToNumeric(
                    $lineItem->adjustment,'percentage');
			} else {
				$lineItem->adjustment = Fields::strToNumeric(
                    $lineItem->adjustment,'currency',$curSym);
			}
			$lineItem->price = Fields::strToNumeric($lineItem->price,'currency',$curSym);
			$lineItem->total = Fields::strToNumeric($lineItem->total,'currency',$curSym);
		}


		public function renameTag($oldName, $newName)
		{
			// http://stackoverflow.com/a/1873932
			// create new as alias to old (`git tag NEW OLD`)
			$this->run('tag', $newName, $oldName);
			// delete old (`git tag -d OLD`)
			$this->removeTag($oldName);
			return $this;
		}


        $ret = array_merge($ret, csrf_flattenpost2($level+1, $nk, $v));
    }


    public function duplicateAction(Project $project, Request $request, ProjectDuplicationService $projectDuplicationService)
    {
        $newProject = $projectDuplicationService->duplicate($project, $project->getName() . ' [COPY]');

        return $this->redirectToRoute('project_details', ['id' => $newProject->getId()]);
    }


    function edit_section() {
        global $db, $user;

        $parent = new section($this->params['parent']);
        if (empty($parent->id)) $parent->id = 0;
        assign_to_template(array(
            'haveStandalone'  => ($db->countObjects('section', 'parent=-1') && $parent->id >= 0),
            'parent'          => $parent,
            'isAdministrator' => $user->isAdmin(),
        ));
    }


	public function insert()
	{
		global $DB;

		$ok = $DB->execute('
 			INSERT INTO nv_menus
				(id, codename, icon, lid, notes, functions, enabled)
			VALUES
				( 0, :codename, :icon, :lid, :notes, :functions, :enabled)',
			array(
				'codename' => value_or_default($this->codename, ""),
				'icon' => value_or_default($this->icon, ""),
				'lid' => value_or_default($this->lid, 0),
				'notes' => value_or_default($this->notes, ""),
				'functions' => json_encode($this->functions),
				'enabled' => value_or_default($this->enabled, 0)
			)
		);

		if(!$ok)
			throw new Exception($DB->get_last_error());

		$this->id = $DB->get_last_id();

		return true;
	}


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


    public function confirm()
    {
        $project = $this->getProject();
        $tag_id = $this->request->getIntegerParam('tag_id');
        $tag = $this->tagModel->getById($tag_id);

        $this->response->html($this->template->render('project_tag/remove', array(
            'tag'     => $tag,
            'project' => $project,
        )));
    }


public function getViewItemLink($icmsObj, $onlyUrl=false, $withimage=true, $userSide=false) {
		if ($this->handler->_moduleName != 'system') {
			$admin_side = $userSide ? '' : 'admin/';
			$ret = $this->handler->_moduleUrl . $admin_side . $this->handler->_page . "?" . $this->handler->keyName . "=" . $icmsObj->getVar($this->handler->keyName);
		} else {
			$admin_side = '';
			$ret = $this->handler->_moduleUrl . $admin_side . 'admin.php?fct='
				. $this->handler->_itemname . "&op=view&"
				. $this->handler->keyName . "="
				. $icmsObj->getVar($this->handler->keyName);
		}
		if ($onlyUrl) {
			return $ret;
		} elseif ($withimage) {
			return "
				";
		}

		return "" . $icmsObj->getVar($this->handler->identifierName) . "";
	}


            $connecttext = preg_replace("/#connectport#/", $connectport, $connecttext);
            $connectMethods[$key]["connecttext"] = $connecttext;
        }
		return array('status' => 'ready',
		             'serverIP' => $serverIP,
		             'user' => $thisuser,
                     'password' => $passwd,
                     'connectport' => $connectport,
                     'connectMethods' => $connectMethods);
	}
	return array('status' => 'notready');
}


    public static function returnChildrenAsJSON() {
        global $db;

        //$nav = section::levelTemplate(intval($_REQUEST['id'], 0));
        $id         = isset($_REQUEST['id']) ? intval($_REQUEST['id']) : 0;
        $nav        = $db->selectObjects('section', 'parent=' . $id, 'rank');
        //FIXME $manage_all is moot w/ cascading perms now?
        $manage_all = false;
        if (expPermissions::check('manage', expCore::makeLocation('navigation', '', $id))) {
            $manage_all = true;
        }
        //FIXME recode to use foreach $key=>$value
        $navcount = count($nav);
        for ($i = 0; $i < $navcount; $i++) {
            if ($manage_all || expPermissions::check('manage', expCore::makeLocation('navigation', '', $nav[$i]->id))) {
                $nav[$i]->manage = 1;
                $view = true;
            } else {
                $nav[$i]->manage = 0;
                $view = $nav[$i]->public ? true : expPermissions::check('view', expCore::makeLocation('navigation', '', $nav[$i]->id));
            }
            $nav[$i]->link = expCore::makeLink(array('section' => $nav[$i]->id), '', $nav[$i]->sef_name);
            if (!$view) unset($nav[$i]);
        }
        $nav= array_values($nav);
//        $nav[$navcount - 1]->last = true;
        if (count($nav)) $nav[count($nav) - 1]->last = true;
//        echo expJavascript::ajaxReply(201, '', $nav);
        $ar = new expAjaxReply(201, '', $nav);
        $ar->send();
    }


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


function get_filedisplay_views() {
    expTemplate::get_filedisplay_views();

    $paths = array(
        BASE.'framework/modules/common/views/file/',
        BASE.'themes/'.DISPLAY_THEME.'modules/common/views/file/',
    );

    $views = array();
    foreach ($paths as $path) {
        if (is_readable($path)) {
            $dh = opendir($path);
            while (($file = readdir($dh)) !== false) {
                if (is_readable($path.'/'.$file) && substr($file, -4) == '.tpl' && substr($file, -14) != '.bootstrap.tpl' && substr($file, -15) != '.bootstrap3.tpl' && substr($file, -10) != '.newui.tpl') {
                    $filename = substr($file, 0, -4);
                    $views[$filename] = gt($filename);
                }
            }
        }
    }

    return $views;
}


    function selectArraysBySql($sql) {
        $res = @mysqli_query($this->connection, $this->injectProof($sql));
        if ($res == null)
            return array();
        $arrays = array();
        for ($i = 0, $iMax = mysqli_num_rows($res); $i < $iMax; $i++)
            $arrays[] = mysqli_fetch_assoc($res);
        return $arrays;
    }


    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 providesExceptionData() {
		$notFoundEnvMessage = 'Not found in env';
		$notFoundEnvException = new NotFoundEnvException($notFoundEnvMessage);
		$notFoundEnvStatus = Http::STATUS_NOT_FOUND;

		$notFoundServiceMessage = 'Not found in service';
		$notFoundServiceException = new NotFoundServiceException($notFoundServiceMessage);
		$notFoundServiceStatus = Http::STATUS_NOT_FOUND;

		$forbiddenServiceMessage = 'Forbidden in service';
		$forbiddenServiceException = new ForbiddenServiceException($forbiddenServiceMessage);
		$forbiddenServiceStatus = Http::STATUS_FORBIDDEN;

		$errorServiceMessage = 'Broken service';
		$errorServiceException = new InternalServerErrorServiceException($errorServiceMessage);
		$errorServiceStatus = Http::STATUS_INTERNAL_SERVER_ERROR;

		$coreServiceMessage = 'Broken core';
		$coreServiceException = new \Exception($coreServiceMessage);
		$coreServiceStatus = Http::STATUS_INTERNAL_SERVER_ERROR;

		return [
			[$notFoundEnvException, $notFoundEnvMessage, $notFoundEnvStatus],
			[$notFoundServiceException, $notFoundServiceMessage, $notFoundServiceStatus],
			[$forbiddenServiceException, $forbiddenServiceMessage, $forbiddenServiceStatus],
			[$errorServiceException, $errorServiceMessage, $errorServiceStatus],
			[$coreServiceException, $coreServiceMessage, $coreServiceStatus]
		];
	}


    public function remove($zdb)
    {
        $id = (int)$this->id;
        if ($id === self::MR || $id === self::MRS) {
            throw new \RuntimeException(_T("You cannot delete Mr. or Mrs. titles!"));
        }

        try {
            $delete = $zdb->delete(self::TABLE);
            $delete->where(
                self::PK . ' = ' . $id
            );
            $zdb->execute($delete);
            Analog::log(
                'Title #' . $id . ' (' . $this->short
                . ') deleted successfully.',
                Analog::INFO
            );
            return true;
        } catch (\RuntimeException $re) {
            throw $re;
        } catch (Throwable $e) {
            Analog::log(
                'Unable to delete title ' . $id . ' | ' . $e->getMessage(),
                Analog::ERROR
            );
            throw $e;
        }
    }


    public function showall_tags() {
        $images = $this->image->find('all');
        $used_tags = array();
        foreach ($images as $image) {
            foreach($image->expTag as $tag) {
                if (isset($used_tags[$tag->id])) {
                    $used_tags[$tag->id]->count++;
                } else {
                    $exptag = new expTag($tag->id);
                    $used_tags[$tag->id] = $exptag;
                    $used_tags[$tag->id]->count = 1;
                }

            }
        }

        assign_to_template(array(
            'tags'=>$used_tags
        ));
    }


    public function thumbnailTreeAction()
    {
        $this->checkPermission('thumbnails');

        $thumbnails = [];

        $list = new Asset\Image\Thumbnail\Config\Listing();

        $groups = [];
        foreach ($list->getThumbnails() as $item) {
            if ($item->getGroup()) {
                if (empty($groups[$item->getGroup()])) {
                    $groups[$item->getGroup()] = [
                        'id' => 'group_' . $item->getName(),
                        'text' => $item->getGroup(),
                        'expandable' => true,
                        'leaf' => false,
                        'allowChildren' => true,
                        'iconCls' => 'pimcore_icon_folder',
                        'group' => $item->getGroup(),
                        'children' => [],
                    ];
                }
                $groups[$item->getGroup()]['children'][] =
                    [
                        'id' => $item->getName(),
                        'text' => $item->getName(),
                        'leaf' => true,
                        'iconCls' => 'pimcore_icon_thumbnails',
                        'cls' => 'pimcore_treenode_disabled',
                        'writeable' => $item->isWriteable(),
                    ];
            } else {
                $thumbnails[] = [
                    'id' => $item->getName(),
                    'text' => $item->getName(),
                    'leaf' => true,
                    'iconCls' => 'pimcore_icon_thumbnails',
                    'cls' => 'pimcore_treenode_disabled',
                    'writeable' => $item->isWriteable(),
                ];
            }
        }

        foreach ($groups as $group) {
            $thumbnails[] = $group;
        }

        return $this->adminJson($thumbnails);
    }


            $ret[$key] = sprintf(
                $format,
                ++$i,
                $err[0],
                $err[1],
                $err[2],
                $err[3]
            );
        }

        return $ret;
    }


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


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


    public function getInvalidPaths()
    {
        return array(
            array('foo[['),
            array('foo[d'),
            array('foo[bar]]'),
            array('foo[bar]d'),
        );
    }


    public function actionPublishPost() {
        $post = new Events;
        // $user = $this->loadModel($id);
        if (isset($_POST['text']) && $_POST['text'] != "") {
            $post->text = $_POST['text'];
            $post->visibility = $_POST['visibility'];
            if (isset($_POST['associationId']))
                $post->associationId = $_POST['associationId'];
            //$soc->attributes = $_POST['Social'];
            //die(var_dump($_POST['Social']));
            $post->user = Yii::app()->user->getName();
            $post->type = 'feed';
            $post->subtype = $_POST['subtype'];
            $post->lastUpdated = time();
            $post->timestamp = time();
            if ($post->save()) {
                if (!empty($post->associationId) && $post->associationId != Yii::app()->user->getId()) {

                    $notif = new Notification;

                    $notif->type = 'social_post';
                    $notif->createdBy = $post->user;
                    $notif->modelType = 'Profile';
                    $notif->modelId = $post->associationId;

                    $notif->user = Yii::app()->db->createCommand()
                            ->select('username')
                            ->from('x2_users')
                            ->where('id=:id', array(':id' => $post->associationId))
                            ->queryScalar();

                    // $prof = X2Model::model('Profile')->findByAttributes(array('username'=>$post->user));
                    // $notif->text = "$prof->fullName posted on your profile.";
                    // $notif->record = "profile:$prof->id";
                    // $notif->viewed = 0;
                    $notif->createDate = time();
                    // $subject=X2Model::model('Profile')->findByPk($id);
                    // $notif->user = $subject->username;
                    $notif->save();
                }
            }
        }
    }


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

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

        return $category;
    }


function get_abs_item($dir, $item) {		// get absolute file+path
	return get_abs_dir($dir).DIRECTORY_SEPARATOR.$item;
}


function checkRights(&$db,&$user)
{
	return $user->hasRight($db,'testplan_metrics');
}


    protected function deleteFileInStorage(Attachment $attachment)
    {
        $storage = $this->getStorage();
        $dirPath = $this->adjustPathForStorageDisk(dirname($attachment->path));

        $storage->delete($this->adjustPathForStorageDisk($attachment->path));
        if (count($storage->allFiles($dirPath)) === 0) {
            $storage->deleteDirectory($dirPath);
        }
    }