    public static function deactivate($mod){
        $mods = Options::v('modules');
        $mods = json_decode($mods, true);
        if (!is_array($mods) || $mods == "") {
            $mods = array();
        }
        //print_r($mods);
        $arr = "";
        for ($i=0;$i<count($mods);$i++) {
            # code...
            if ($mods[$i] == $mod) {
                //unset($mods[$i]);
            }else{
                $arr[] = $mods[$i];
            }

        }
        //print_r($arr);
        //asort($mods);
        $mods = json_encode($arr);
        $mods = Options::update('modules', $mods);
        if($mods){
            new Options();
            return true;
        }else{
            return false;
        }
    }


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

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

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


    private static function sesKey() {
        $ip = $_SERVER['REMOTE_ADDR'];
        $browser = $_SERVER['HTTP_USER_AGENT'];
        $dt = date("Y-m-d H");

        $key = md5($ip.$browser.$dt);
        return $key;
    }


	public static function isAnimationGif($path) {
		list($width, $height, $type, $attr) = getimagesize($path);
		switch ($type) {
			case IMAGETYPE_GIF:
				break;
			default:
				return false;
		}

		$imgcnt = 0;
		$fp = fopen($path, 'rb');
		@fread($fp, 4);
		$c = @fread($fp,1);
		if (ord($c) != 0x39) {  // GIF89a
			return false;
		}

		while (!feof($fp)) {
			do {
				$c = fread($fp, 1);
			} while(ord($c) != 0x21 && !feof($fp));

			if (feof($fp)) {
				break;
			}

			$c2 = fread($fp,2);
			if (bin2hex($c2) == "f904") {
				$imgcnt++;
			}

			if (feof($fp)) {
				break;
			}
		}

		if ($imgcnt > 1) {
			return true;
		} else {
			return false;
		}
	}


    protected function get_remote_contents(&$url, $timeout = 30, $redirect_max = 5, $ua = 'Mozilla/5.0', $fp = null)
    {
        if (preg_match('~^(?:ht|f)tps?://[-_.!\~*\'()a-z0-9;/?:\@&=+\$,%#\*\[\]]+~i', $url)) {
            $info = parse_url($url);
            $host = strtolower($info['host']);
            // do not support IPv6 address
            if (preg_match('/^\[.*\]$/', $host)) {
                return false;
            }
            // do not support non dot URL
            if (strpos($host, '.') === false) {
                return false;
            }
            // disallow including "localhost"
            if (strpos($host, 'localhost') !== false) {
                return false;
            }
            // check IPv4 local loopback
            if (preg_match('/^(?:127|0177|0x7f)\.[0-9a-fx.]+$/', $host)) {
                return false;
            }
            // check by URL upload filter
            if ($this->urlUploadFilter && is_callable($this->urlUploadFilter)) {
                if (!call_user_func_array($this->urlUploadFilter, array($url, $this))) {
                    return false;
                }
            }
            $method = (function_exists('curl_exec') && !ini_get('safe_mode') && !ini_get('open_basedir')) ? 'curl_get_contents' : 'fsock_get_contents';
            return $this->$method($url, $timeout, $redirect_max, $ua, $fp);
        }
        return false;
    }


                }elseif(!in_array($k, $arr) && $k != 'paging'){
                    //self::error('404');
                }else{

                    self::incFront('default');

                }

            }

        }else{


    public function onLoadRecord()
    {
        $scheduleCode = post('recordId');
        $scheduleItem = $this->getSchedule($scheduleCode);

        $formTitle = sprintf(lang($this->formTitle), lang('admin::lang.text_'.$scheduleCode));

        return $this->makePartial('recordeditor/form', [
            'formRecordId' => $scheduleCode,
            'formTitle' => $formTitle,
            'formWidget' => $this->makeScheduleFormWidget($scheduleItem),
        ]);
    }


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

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

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

        return $comment;
    }


  public function AddReplyTo($address, $name = '') {
    return $this->AddAnAddress('Reply-To', $address, $name);
  }


function db_start()
{
    global $DatabaseServer, $DatabaseUsername, $DatabasePassword, $DatabaseName, $DatabasePort, $DatabaseType;

    switch ($DatabaseType) {
        case 'mysqli':
            $connection = new mysqli($DatabaseServer, $DatabaseUsername, $DatabasePassword, $DatabaseName, $DatabasePort);
            break;
    }

    // Error code for both.
    if ($connection === false) {
        switch ($DatabaseType) {
            case 'mysqli':
                $errormessage = mysqli_error($connection);
                break;
        }
        db_show_error("", "" . _couldNotConnectToDatabase . ": $DatabaseServer", $errormessage);
    }
    return $connection;
}


function PMA_countLines($filename)
{
    global $LINE_COUNT;
    if (defined('LINE_COUNTS')) {
        return $LINE_COUNT[$filename];
    }

    // ensure that the file is inside the phpMyAdmin folder
    $depath = 1;
    foreach (explode('/', $filename) as $part) {
        if ($part == '..') {
            $depath--;
        } elseif ($part != '.') {
            $depath++;
        }
        if ($depath < 0) {
            return 0;
        }
    }

    $linecount = 0;
    $handle = fopen('./js/' . $filename, 'r');
    while (!feof($handle)) {
        $line = fgets($handle);
        if ($line === false) {
            break;
        }
        $linecount++;
    }
    fclose($handle);
    return $linecount;
}


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

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

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

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


    public static function incFront($vars, $param='') {
        $file = GX_PATH.'/inc/lib/Control/Frontend/'.$vars.'.control.php';
        if ( file_exists($file) ) {
            # code...
            include($file);
        }else{
            self::error('404');
        }

    }


   public function testGetDropdownValue($params, $expected, $session_params = []) {
      $this->login();

      $bkp_params = [];
      //set session params if any
      if (count($session_params)) {
         foreach ($session_params as $param => $value) {
            if (isset($_SESSION[$param])) {
               $bkp_params[$param] = $_SESSION[$param];
            }
            $_SESSION[$param] = $value;
         }
      }

      $params['_idor_token'] = \Session::getNewIDORToken($params['itemtype'] ?? '');

      $result = \Dropdown::getDropdownValue($params, false);

      //reset session params before executing test
      if (count($session_params)) {
         foreach ($session_params as $param => $value) {
            if (isset($bkp_params[$param])) {
               $_SESSION[$param] = $bkp_params[$param];
            } else {
               unset($_SESSION[$param]);
            }
         }
      }

      $this->array($result)->isIdenticalTo($expected);
   }


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


            $text = preg_replace($exp, '', $text);
        }

        // Primary expression to filter out tags
        $exp = '/(?:^|\s|\.)(#\w+[-\w]+\w+|#\w+)(?:$|[^\'"])/u';

        $matches = array();
        preg_match_all($exp, $text, $matches);

        return $matches;
    }


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

		//This will make sure that only the country or region that given a rate value will be saved in the db
		$upcharge = array();
		foreach($this->params['upcharge'] as $key => $item) {
			if(!empty($item)) {
				$upcharge[$key] = $item;
			}
		}
		$this->config['upcharge'] = $upcharge;

        $config->update(array('config'=>$this->config));
        flash('message', gt('Configuration updated'));
        expHistory::back();
    }


    static function description() {
        return gt("This module is for managing categories in your store.");
    }


    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 downloadfile() {
        if (empty($this->params['fileid'])) {
            flash('error', gt('There was an error while trying to download your file.  No File Specified.'));
            expHistory::back();
        }

        $fd = new filedownload($this->params['fileid']);
        if (empty($this->params['filenum'])) $this->params['filenum'] = 0;

        if (empty($fd->expFile['downloadable'][$this->params['filenum']]->id)) {
            flash('error', gt('There was an error while trying to download your file.  The file you were looking for could not be found.'));
            expHistory::back();
        }

        $fd->downloads++;
        $fd->save();

        // this will set the id to the id of the actual file..makes the download go right.
        $this->params['id'] = $fd->expFile['downloadable'][$this->params['filenum']]->id;
        parent::downloadfile();
    }


    protected function _mkfile($path, $name)
    {
        $path = $this->_joinPath($path, $name);
        return $this->connect->put($path, '') ? $path : false;
/*
        if ($this->tmp) {
            $path = $this->_joinPath($path, $name);
            $local = $this->getTempFile();
            $res = touch($local) && $this->connect->put($path, $local, NET_SFTP_LOCAL_FILE);
            unlink($local);
            return $res ? $path : false;
        }

        return false;
 */
    }


    static function isSearchable() {
        return true;
    }


function get_file($file) {
	$files['radiusd'] = FREERADIUS_RADDB . "/radiusd.conf";
	$files['eap'] = FREERADIUS_MODSENABLED . "/eap";
	$files['sql'] = FREERADIUS_MODSENABLED . "/sql";
	$files['clients'] = FREERADIUS_RADDB . "/clients.conf";
	$files['users'] = FREERADIUS_RADDB . "/users";
	$files['macs'] = FREERADIUS_RADDB . "/authorized_macs";
	$files['virtual-server-default'] = FREERADIUS_RADDB . "/sites-enabled/default";
	$files['ldap'] = FREERADIUS_MODSENABLED . "/ldap";

	if ($files[$file] != "" && file_exists($files[$file])) {
		print '<pre>';
		print $files[$file] . "\n" . file_get_contents($files[$file]);
		print '</pre>';
	}
}


    public function getPageData()
    {
        $data = parent::getPageData();
        $data['menu'] = 'admin';
        $data['showonmenu'] = false;
        $data['title'] = 'options';
        $data['icon'] = 'fas fa-wrench';
        return $data;
    }


    public function __toString()
    {
        return self::createUriString(
            $this->scheme,
            $this->getAuthority(),
            $this->getPath(),
            $this->query,
            $this->fragment
        );
    }


    function edit_internalalias() {
        $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(),
        ));
    }


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


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

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

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

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


            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 backup($type='json')
    {
        global $DB;
        global $website;

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

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

        return $out;
    }


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


    protected function getC3Service()
    {
        include_once $this->targetDirs[1].'/includes/HotPath/C3.php';

        return $this->services['Symfony\Component\DependencyInjection\Tests\Fixtures\includes\HotPath\C3'] = new \Symfony\Component\DependencyInjection\Tests\Fixtures\includes\HotPath\C3();
    }


$file_link = explode(" ", trim($row['file']))[0];
                // If the link has no "http://" in front, then add it
                if (substr(strtolower($file_link), 0, 4) !== 'http') {
                    $file_link = 'http://' . $file_link;
                }
                echo 'http://anonym.to/?' . $file_link . '	';
                echo 'Play	';
                echo 'Scan File	';
                echo '
';
                $counter++;
            }

            //Close tbody and table element, it's ready.
            echo '

';
            echo '

';
        }


$alt = __esc('Export');
	}

	if ($force_type != 'import' && $force_type != 'export' && $force_type != 'save' && $cancel_url != '') {
		$cancel_action = "<input type='button' onClick='cactiReturnTo(\"" . htmlspecialchars($cancel_url) . "\")' value='" . $calt . "'>";
	} else {
		$cancel_action = '';
	}

	?>

				<input type='hidden' name='action' value='save'>
				<?php print $cancel_action;?>
				<input class='<?php print $force_type;?>' id='submit' type='submit' value='<?php print $alt;?>'>

	<?php

	form_end($ajax);
}


    public function pending() {
//        global $db;

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

        // find the subscriber and their pending subscriptions
        $ealerts = expeAlerts::getPendingBySubscriber($this->params['id']);
        $subscriber = new subscribers($this->params['id']);

        // render the template
        assign_to_template(array(
            'subscriber'=>$subscriber,
            'ealerts'=>$ealerts
        ));
    }


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

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

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


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


	protected function _chmod($path, $mode) {
		$modeOct = is_string($mode) ? octdec($mode) : octdec(sprintf("%04o",$mode));
		return @ftp_chmod($this->connect, $modeOct, $path);
	}


    public static function loader(){
        $theme = Options::v('themes');
        define('THEME', $theme);
        self::incFunc($theme);
    }


public function getAdminViewItemLink($icmsObj, $onlyUrl=false, $withimage=false) {
		$ret = $this->handler->_moduleUrl . "admin/"
			. $this->handler->_page . "?op=view&"
			. $this->handler->keyName . "="
			. $icmsObj->getVar($this->handler->keyName);
		if ($onlyUrl) {
			return $ret;
		} elseif ($withimage) {
			return "
					";
		}

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


    public function testIdExceptionPhp54()
    {
        session_start();
        $this->proxy->setId('foo');
    }


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

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


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


                } elseif ($this->isValidOrderKey($o)) {
                    $this->orderKey[] = '`' . $o . '`';
                }
            }
        }


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

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


function rsvpmaker_stripecharge( $atts ) {

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

		return;
	}

	global $current_user;

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

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

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

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

	if ( $paymentType == 'schedule' ) {

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

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

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

			if ( $index == 11 ) {

				$index = 0;

			} else {
				$index++;
			}
		}

		$month = $months[ $index ];

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

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

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

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

		return rsvpmaker_stripe_form( $vars, $show );

	}

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

	if ( $paymentType != 'once' ) {

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

	return rsvpmaker_stripe_form( $vars, $show );

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


function GETPOST($paramname,$check='',$method=0)
{
	if (empty($method)) $out = isset($_GET[$paramname])?$_GET[$paramname]:(isset($_POST[$paramname])?$_POST[$paramname]:'');
	elseif ($method==1) $out = isset($_GET[$paramname])?$_GET[$paramname]:'';
	elseif ($method==2) $out = isset($_POST[$paramname])?$_POST[$paramname]:'';
	elseif ($method==3) $out = isset($_POST[$paramname])?$_POST[$paramname]:(isset($_GET[$paramname])?$_GET[$paramname]:'');

	if (! empty($check))
	{
		// Check if numeric
		if ($check == 'int' && ! preg_match('/^[-\.,0-9]+$/i',trim($out))) $out='';
		// Check if alpha
		//if ($check == 'alpha' && ! preg_match('/^[ =:@#\/\\\(\)\-\._a-z0-9]+$/i',trim($out))) $out='';
		// '"' is dangerous because param in url can close the href= or src= and add javascript functions.
		if ($check == 'alpha' && preg_match('/"/',trim($out))) $out='';
	}

	return $out;
}


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


    private static function createUriString($scheme, $authority, $path, $query, $fragment)
    {
        $uri = '';

        if (!empty($scheme)) {
            $uri .= $scheme . ':';
        }

        $hierPart = '';

        if (!empty($authority)) {
            if (!empty($scheme)) {
                $hierPart .= '//';
            }
            $hierPart .= $authority;
        }

        if ($path != null) {
            // Add a leading slash if necessary.
            if ($hierPart && substr($path, 0, 1) !== '/') {
                $hierPart .= '/';
            }
            $hierPart .= $path;
        }

        $uri .= $hierPart;

        if ($query != null) {
            $uri .= '?' . $query;
        }

        if ($fragment != null) {
            $uri .= '#' . $fragment;
        }

        return $uri;
    }


	public function setLoggerChannel($channel = 'Organizr', $username = null)
	{
		if ($this->hasDB()) {
			$setLogger = false;
			if ($username) {
				$username = htmlspecialchars($username);
			}
			if ($this->logger) {
				if ($channel) {
					if (strtolower($this->logger->getChannel()) !== strtolower($channel)) {
						$setLogger = true;
					}
				}
				if ($username) {
					if (strtolower($this->logger->getTraceId()) !== strtolower($channel)) {
						$setLogger = true;
					}
				}
			} else {
				$setLogger = true;
			}
			if ($setLogger) {
				$channel = $channel ?: 'Organizr';
				return $this->setupLogger($channel, $username);
			} else {
				return $this->logger;
			}
		}
	}


function can_process() {

	$Auth_Result = hook_authenticate($_SESSION['wa_current_user']->username, $_POST['cur_password']);

	if (!isset($Auth_Result))	// if not used external login: standard method
		$Auth_Result = get_user_auth($_SESSION['wa_current_user']->username, md5($_POST['cur_password']));

	if (!$Auth_Result) {
		display_error( _('Invalid password entered.'));
		set_focus('cur_password');
		return false;
	}
	if (strlen($_POST['password']) < 4) {
		display_error( _('The password entered must be at least 4 characters long.'));
		set_focus('password');
		return false;
	}
	if (strstr($_POST['password'], $_SESSION['wa_current_user']->username) != false) {
		display_error( _('The password cannot contain the user login.'));
		set_focus('password');
		return false;
	}
	if ($_POST['password'] != $_POST['passwordConfirm']) {
		display_error( _('The passwords entered are not the same.'));
		set_focus('password');
		return false;
	}

	return true;
}


    public function withUri(UriInterface $uri, $preserveHost = false)
    {
        if ($uri === $this->uri) {
            return $this;
        }

        $new = clone $this;
        $new->uri = $uri;

        if (!$preserveHost) {
            if ($host = $uri->getHost()) {
                $new->updateHostFromUri($host);
            }
        }

        return $new;
    }


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


public function Connect($host, $port = 0, $tval = 30) {
    // set the error val to null so there is no confusion
    $this->error = null;

    // make sure we are __not__ connected
    if($this->connected()) {
      // already connected, generate error
      $this->error = array("error" => "Already connected to a server");
      return false;
    }

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

    // connect to the smtp server
    $this->smtp_conn = @fsockopen($host,    // the host of the server
                                 $port,    // the port to use
                                 $errno,   // error number if any
                                 $errstr,  // error message if any
                                 $tval);   // give up after ? secs
    // verify we connected properly
    if(empty($this->smtp_conn)) {
      $this->error = array("error" => "Failed to connect to server",
                           "errno" => $errno,
                           "errstr" => $errstr);
      if($this->do_debug >= 1) {
        $this->edebug("SMTP -> ERROR: " . $this->error["error"] . ": $errstr ($errno)" . $this->CRLF . '
');
      }
      return false;
    }

    // SMTP server can take longer to respond, give longer timeout for first read
    // Windows does not have support for this timeout function
    if(substr(PHP_OS, 0, 3) != "WIN") {
     $max = ini_get('max_execution_time');
     if ($max != 0 && $tval > $max) { // don't bother if unlimited
      @set_time_limit($tval);
     }
     stream_set_timeout($this->smtp_conn, $tval, 0);
    }

    // get any announcement
    $announce = $this->get_lines();

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

    return true;
  }


    public function whereFileName($fileName)
    {
        $this->selectSingle = $this->model->getFileNameParts($fileName);

        return $this;
    }


    public function __construct(PromotionGatewayInterface $gateway, PromotionItemBuilder $itemBuilder)
    {
        $this->gateway = $gateway;
        $this->itemBuilder = $itemBuilder;

        $this->requiredDalAssociations = [
            'personaRules',
            'personaCustomers',
            'cartRules',
            'orderRules',
            'discounts.discountRules',
            'discounts.promotionDiscountPrices',
            'setgroups',
            'setgroups.setGroupRules',
        ];
    }


  static function getParentGroup($group_id) {
    global $user;

    $mdb2 = getConnection();

    $sql = "select parent_id from tt_groups where id = $group_id and org_id = $user->org_id and status = 1";
    $res = $mdb2->query($sql);

    if (!is_a($res, 'PEAR_Error')) {
      $val = $res->fetchRow();
      return $val['parent_id'];
    }
    return false;
  }


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

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


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


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


    public function handle($request, Closure $next)
    {
        view()->share('cspNonce', $this->cspService->getNonce());
        if ($this->cspService->allowedIFrameHostsConfigured()) {
            config()->set('session.same_site', 'none');
        }

        $response = $next($request);

        $this->cspService->setFrameAncestors($response);
        $this->cspService->setScriptSrc($response);
        $this->cspService->setObjectSrc($response);
        $this->cspService->setBaseUri($response);

        return $response;
    }


        $module_views[$key]['name'] = gt($value['name']);
    }

    // look for a config form for this module's current view
//    $controller->loc->mod = expModules::getControllerClassName($controller->loc->mod);
    //check to see if hcview was passed along, indicating a hard-coded module
//    if (!empty($controller->params['hcview'])) {
//        $viewname = $controller->params['hcview'];
//    } else {
//        $viewname = $db->selectValue('container', 'view', "internal='".serialize($controller->loc)."'");
//    }
//    $viewconfig = $viewname.'.config';
//    foreach ($modpaths as $path) {
//        if (file_exists($path.'/'.$viewconfig)) {
//            $fileparts = explode('_', $viewname);
//            if ($fileparts[0]=='show'||$fileparts[0]=='showall') array_shift($fileparts);
//            $module_views[$viewname]['name'] = ucwords(implode(' ', $fileparts)).' '.gt('View Configuration');
//            $module_views[$viewname]['file'] =$path.'/'.$viewconfig;
//        }
//    }

    // sort the views highest to lowest by filename
    // we are reverse sorting now so our array merge
    // will overwrite property..we will run array_reverse
    // when we're finished to get them back in the right order
    krsort($common_views);
    krsort($module_views);

    if (!empty($moduleconfig)) $common_views = array_merge($common_views, $moduleconfig);
    $views = array_merge($common_views, $module_views);
    $views = array_reverse($views);

    return $views;
}


	function setParameter($a_name, $a_value)
	{
		$this->parameters[$a_name] = $a_value;
	}


	public function load_from_post()
	{
		if(intval($_REQUEST['parent'])!=$this->id)	// protection against selecting this same category as parent of itself
        {
            $this->parent 		= intval($_REQUEST['parent']);
        }

		$this->template 	= $_REQUEST['template'];
		$this->access		= intval($_REQUEST['access']);

        $this->groups	    = $_REQUEST['groups'];
        if($this->access < 3)
        {
            $this->groups = array();
        }

		$this->permission	= intval($_REQUEST['permission']);
		$this->visible		= intval($_REQUEST['visible']);

		$this->date_published	= (empty($_REQUEST['date_published'])? '' : core_date2ts($_REQUEST['date_published']));
		$this->date_unpublish	= (empty($_REQUEST['date_unpublish'])? '' : core_date2ts($_REQUEST['date_unpublish']));

		// language strings and options
		$this->dictionary = array();
		$this->paths = array();

		$fields = array('title', 'action-type', 'action-jump-item', 'action-jump-branch', 'action-new-window', 'action-masked-redirect'); //, 'path', 'visible');
		foreach($_REQUEST as $key => $value)
		{
			if(empty($value))
            {
                continue;
            }

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

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


	protected function _mkdir($path, $name) {
		$path = $this->_joinPath($path, $name);
		if (ftp_mkdir($this->connect, $path) === false) {
			return false;
		}

		$this->options['dirMode'] && @ftp_chmod($this->connect, $this->options['dirMode'], $path);
		return $path;
	}


                            $property->value[$lang] = theme::import_sample_translate_nv_urls($pvalue, $structure, $items);
                        }
                    }
                    else if(!is_string($property->value))  // ignore numeric values
                    {
                        $property->value = theme::import_sample_translate_nv_urls($property->value, $structure, $items);
                    }
            }

            $el_properties_associative[$property->id] = $property->value;
        }

        if(!empty($el_properties_associative))
        {
            if($el=='block_group_block')
            {
                $template = $real[$el_id]->code;
            }
            else if($el=='block')
            {
                $template = $real[$el_id]->type;
            }
            else
            {
                $template = $real[$el_id]->template;

                if(empty($template) && $el == 'item' && $real[$el_id]->embedding == 1)
                {
                    // we have to get the template set in the category of the item
                    $template = $DB->query_single(
                        'template',
                        'nv_structure',
                        ' id = '.protect($real[$el_id]->category).' AND
								  website = '.$ws->id
                    );
                }
            }

            property::save_properties_from_array($el, $real[$el_id]->id, $template, $el_properties_associative, $ws, $item_uid);
        }
    }


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

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

        return $link;
    }


function mso_url_get()
{
	$CI = &get_instance();
	if (isset($_SERVER['REQUEST_URI']) and $_SERVER['REQUEST_URI'] and (strpos($_SERVER['REQUEST_URI'], '?') !== FALSE)) {
		$url = getinfo('site_protocol') . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
		$url = str_replace($CI->config->config['base_url'], "", $url);
		$url = explode('?', $url);

		return $url[1];
	} else {
		return '';
	}
}


    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 link($target, $link)
    {
        if (! windows_os()) {
            return symlink($target, $link);
        }

        $mode = $this->isDirectory($target) ? 'J' : 'H';

        exec("mklink /{$mode} \"{$link}\" \"{$target}\"");
    }


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

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


    public function actionGetItems(){
        $model = X2Model::model ($this->modelClass);
        if (isset ($model)) {
            $tableName = $model->tableName ();
            $sql =
                'SELECT id, subject as value
                 FROM '.$tableName.' WHERE subject LIKE :qterm ORDER BY subject 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 confirm()
    {
        $project = $this->getProject();

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


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

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


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


            $this->subtaskTimeTrackingModel->logEndTime($subtaskId, $this->userSession->getId());
            $this->subtaskTimeTrackingModel->updateTaskTimeTracking($task['id']);
        }


    public function save($check_notify = false)
    {
        if (isset($_POST['email_recipients']) && is_array($_POST['email_recipients'])) {
            $this->email_recipients = base64_encode(serialize($_POST['email_recipients']));
        }

        return parent::save($check_notify);
    }


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

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


function SafeStripSlashes($string) {
	return (get_magic_quotes_gpc() ? stripslashes($string) : $string);
}


	public function duplicate($hash, $suffix='copy') {
		if ($this->commandDisabled('duplicate')) {
			return $this->setError(elFinder::ERROR_COPY, '#'.$hash, elFinder::ERROR_PERM_DENIED);
		}

		if (($file = $this->file($hash)) == false) {
			return $this->setError(elFinder::ERROR_COPY, elFinder::ERROR_FILE_NOT_FOUND);
		}

		$path = $this->decode($hash);
		$dir  = $this->dirnameCE($path);
		$name = $this->uniqueName($dir, $file['name'], ' '.$suffix.' ');

		if (!$this->allowCreate($dir, $name, ($file['mime'] === 'directory'))) {
			return $this->setError(elFinder::ERROR_PERM_DENIED);
		}

		return ($path = $this->copy($path, $dir, $name)) == false
			? false
			: $this->stat($path);
	}


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


    public static function load($mod) {
        $file = GX_MOD."/".$mod."/index.php";
        if(file_exists($file)){
            include ($file);
        }
    }


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


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

        $out = array();

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

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

        return $out;
    }


foreach ( $metric_group_members as $index => $metric_name ) {
	print "

	";
      }


function dashboard_panel_top_pages($params)
{
    global $DB;
    global $website;

    $stats = &$params['statistics'];
    $navibars = &$params['navibars'];

    /* TOP PAGES */
    $sql = '
	    SELECT i.views as page_views, i.id as id_item, i.category as id_category, p.views as path_views, p.path as path
          FROM nv_items i, nv_paths p
         WHERE i.website = '.protect($website->id).'
           AND i.template > 0
           AND i.embedding = 0
           AND p.website = '.protect($website->id).'
           AND p.type = "item"
           AND p.object_id = i.id

        UNION ALL

        SELECT s.views as page_views, NULL as id_item, s.id as id_category, p.views as path_views, p.path as path
          FROM nv_structure s, nv_paths p
         WHERE s.website = '.protect($website->id).'
           AND p.website = '.protect($website->id).'
           AND p.type = "structure"
           AND p.object_id = s.id

        ORDER BY path_views DESC
        LIMIT 10
    ';

    $DB->query($sql, 'array');
    $pages = $DB->result();

    $pages_html = '';

    $url = $website->protocol;

    if(!empty($website->subdomain))
        $url .= $website->subdomain.'.';
    $url .= $website->domain;
    $url .= $website->folder;

    for($e = 0; $e < 10; $e++)
    {
        if(!$pages[$e]) break;

        $pages_html .= '
'.
            ''.
            ''.$pages[$e]['path_views'].'  '.$pages[$e]['path'].
            ''.
            '
';
    }

    $navibars->add_tab_content_panel(
        ' '.t(296, 'Top pages'),
        $pages_html,
        'navigate-panel-top-pages',
        '100%',
        '314px'
    );
}


				$doRegist = (strpos($cmd, '*') !== false);
				if (! $doRegist) {
					$_getcmd = create_function('$cmd', 'list($ret) = explode(\'.\', $cmd);return trim($ret);');
					$doRegist = ($_reqCmd && in_array($_reqCmd, array_map($_getcmd, explode(' ', $cmd))));
				}
				if ($doRegist) {
					if (! is_array($handlers) || is_object($handlers[0])) {
						$handlers = array($handlers);
					}
					foreach($handlers as $handler) {
						if ($handler) {
							if (is_string($handler) && strpos($handler, '.')) {
								list($_domain, $_name, $_method) = array_pad(explode('.', $handler), 3, '');
								if (strcasecmp($_domain, 'plugin') === 0) {
									if ($plugin = $this->getPluginInstance($_name, isset($opts['plugin'][$_name])? $opts['plugin'][$_name] : array())
											and method_exists($plugin, $_method)) {
										$this->bind($cmd, array($plugin, $_method));
									}
								}
							} else {
								$this->bind($cmd, $handler);
							}
						}
					}
				}
			}
		}


    public static function latestVersion () {

        $check = json_decode(Options::v('system_check'), true);
        $now = strtotime(date("Y-m-d H:i:s"));

        if (isset($check['last_check']) ) {

            $limit = $now - $check['last_check'];

            if ($limit < 86400) {

                 $v = $check['version'];

            }else{

                $v = self::getLatestVersion($now);

            }

        }else{

            $v = self::getLatestVersion($now);

        }

        return $v;
    }


function details($selected_events, $queue)
{
	global $database_ged;

	// get all needed infos into variables
	$value_parts = explode(":", $selected_events);
	$id = $value_parts[0];
	$ged_type = $value_parts[1];

	$sql = "SELECT * FROM ".$ged_type."_queue_".$queue." WHERE id = $id";
	$result = sqlrequest($database_ged, $sql);
	$event = mysqli_fetch_assoc($result);

	// display event's details
	echo '
';
		echo '
';
			createDetailRow($event, "equipment", "label.host");
			createDetailRow($event, "host_alias", "label.host_alias");
			createDetailRow($event, "ip_address", "label.ip_address");
			createDetailRow($event, "service", "label.service");
			createDetailRow($event, "state", "label.state");
			createDetailRow($event, "description", "label.desc");
			createDetailRow($event, "occ", "label.occurence");
			createDetailRow($event, "o_sec", "label.o_time");
			createDetailRow($event, "l_sec", "label.l_time");
			createDetailRow($event, "a_sec", "label.a_time");
			createDetailRow($event, "hostgroups", "label.hostgroups");
			createDetailRow($event, "servicegroups", "label.servicegroups");
			createDetailRow($event, "src", "label.source");
			createDetailRow($event, "owner", "label.owner");
			createDetailRow($event, "comments", "label.comments");
		echo '
';
	echo '
';
}


    public function __construct(public Request $Request, public SessionInterface $Session, public Config $Config, public Logger $Log, public Csrf $Csrf)
    {
        $flashBag = $this->Session->getBag('flashes');
        // add type check because SessionBagInterface doesn't have get(), only FlashBag has it
        if ($flashBag instanceof FlashBag) {
            $this->ok = $flashBag->get('ok');
            $this->ko = $flashBag->get('ko');
            $this->warning = $flashBag->get('warning');
        }

        $this->Log->pushHandler(new ErrorLogHandler());
        $this->Users = new Users();
        $this->Db = Db::getConnection();
        // UPDATE SQL SCHEMA if necessary or show error message if version mismatch
        $Update = new Update($this->Config, new Sql());
        $Update->checkSchema();
    }


    public static function update($vars) {
        if(is_array($vars)){

            //print_r($vars);
            $u = $vars['user'];
            $sql = array(
                            'table' => 'user',
                            'id' => $vars['id'],
                            'key' => $u,
                        );
            Db::update($sql);
            if(isset($vars['detail']) && $vars['detail'] != ''){

                $u = $vars['detail'];
                $sql = array(
                                'table' => 'user_detail',
                                'id' => $vars['id'],
                                'key' => $u,
                            );
                Db::update($sql);
            }
            Hooks::run('user_sqledit_action', $vars);

        }
    }


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

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

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

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

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

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

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


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


  public function __construct() {
    $this->pop_conn  = 0;
    $this->connected = false;
    $this->error     = null;
  }


    public static function avatar($id){
        $usr = Db::result(
            sprintf("SELECT * FROM `user_detail` WHERE `id` = '%d' OR `userid` = '%s' LIMIT 1",
                Typo::int($id),
                Typo::cleanX($id)
                )
            );
        return $usr[0]->avatar;
    }


                   foreach($gc as $gcc=>$gcd)
                   {
                       if($gcd!='' && $gcc!='GRADE_LEVEL')
                       {
                       $sql_columns[]=$gcc;
                       $sql_values[]="'".$gcd."'";
                       }
                       if($gcd!='' && $gcc=='GRADE_LEVEL')
                       {
                           foreach($get_cs_grade as $gcsgi=>$gcsgd)
                           {
                            if($gcd==$gcsd['ID'])
                            {

                            $sql_columns[]='GRADE_LEVEL';
                            $sql_values[]="'".$get_ts_grade[$gcsgi]['ID']."'";

                            }
                           }
                       }
                   }


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


            $date->delete(); // event automatically deleted if all assoc eventdates are deleted
        }
        expHistory::back();
    }


function wp_embed_handler_youtube( $matches, $attr, $url, $rawattr ) {
	global $wp_embed;
	$embed = $wp_embed->autoembed( "https://youtube.com/watch?v={$matches[2]}" );

	/**
	 * Filters the YoutTube embed output.
	 *
	 * @since 4.0.0
	 *
	 * @see wp_embed_handler_youtube()
	 *
	 * @param string $embed   YouTube embed output.
	 * @param array  $attr    An array of embed attributes.
	 * @param string $url     The original URL that was matched by the regex.
	 * @param array  $rawattr The original unmodified attributes.
	 */
	return apply_filters( 'wp_embed_handler_youtube', $embed, $attr, $url, $rawattr );
}


    public static function admin($var, $data='') {
        if (isset($data)) {
            # code...
            $GLOBALS['data'] = $data;
        }
        include(GX_PATH.'/gxadmin/themes/'.$var.'.php');
    }


				$row_rub = sql_fetsel("id_rubrique", "spip_rubriques",
					"lang='" . $GLOBALS['spip_lang'] . "' AND id_parent=$id_parent");
				if ($row_rub) {
					$row['id_rubrique'] = $row_rub['id_rubrique'];
				}
			}
		}
	}

	return $row;
}


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

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


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

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

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

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


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


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

        $out = array();

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

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

        return $out;
    }


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

		//This will make sure that only the country or region that given a rate value will be saved in the db
		$upcharge = array();
		foreach($this->params['upcharge'] as $key => $item) {
			if(!empty($item)) {
				$upcharge[$key] = $item;
			}
		}
		$this->config['upcharge'] = $upcharge;

        $config->update(array('config'=>$this->config));
        flash('message', gt('Configuration updated'));
        expHistory::back();
    }


            $navs[$i]->link = expCore::makeLink(array('section' => $navs[$i]->id), '', $navs[$i]->sef_name);
            if (!$view) {
//                unset($navs[$i]);  //FIXME this breaks jstree if we remove a parent and not the child
                $attr = new stdClass();
                $attr->class = 'hidden';  // bs3 class to hide elements
                $navs[$i]->li_attr = $attr;
            }
        }


	function manage() {
	    global $db;

	    expHistory::set('manageable', $this->params);
//	    $classes = array();
        $dir = BASE."framework/modules/ecommerce/billingcalculators";
        if (is_readable($dir)) {
            $dh = opendir($dir);
            while (($file = readdir($dh)) !== false) {
                if (is_file("$dir/$file") && substr("$dir/$file", -4) == ".php") {
                    include_once("$dir/$file");
                    $classname = substr($file, 0, -4);
                    $id = $db->selectValue('billingcalculator', 'id', 'calculator_name="'.$classname.'"');
                    if (empty($id)) {
//                        $calobj = null;
                        $calcobj = new $classname();
                        if ($calcobj->isSelectable() == true) {
                            $obj = new billingcalculator(array(
                                'title'=>$calcobj->name(),
//                                'user_title'=>$calcobj->title,
                                'body'=>$calcobj->description(),
                                'calculator_name'=>$classname,
                                'enabled'=>false));
                            $obj->save();
                        }
                    }
                }
            }
        }

        $bcalc = new billingcalculator();
        $calculators = $bcalc->find('all');
        assign_to_template(array(
            'calculators'=>$calculators
        ));
	}


public static function parseAndTrimImport($str, $isHTML = false) { //�Death from above�? �
        //echo "1
"; eDebug($str);
//        global $db;

        $str = str_replace("�", "’", $str);
        $str = str_replace("�", "‘", $str);
        $str = str_replace("�", "®", $str);
        $str = str_replace("�", "-", $str);
        $str = str_replace("�", "—", $str);
        $str = str_replace("�", "”", $str);
        $str = str_replace("�", "“", $str);
        $str = str_replace("\r\n", " ", $str);
        $str = str_replace("\,", ",", $str);
        $str = str_replace('""', '"', $str); //do this no matter what...in case someone added a quote in a non HTML field
        if (!$isHTML) {
            //if HTML, then leave the single quotes alone, otheriwse replace w/ special Char
            $str = str_replace('"', """, $str);
        }
        $str = str_replace("�", "¼", $str);
        $str = str_replace("�", "½", $str);
        $str = str_replace("�", "¾", $str);
        //$str = htmlspecialchars($str);
        //$str = utf8_encode($str);
//        if (DB_ENGINE=='mysqli') {
//	        $str = @mysqli_real_escape_string($db->connection,trim(str_replace("�", "™", $str)));
//        } elseif(DB_ENGINE=='mysql') {
//            $str = @mysql_real_escape_string(trim(str_replace("�", "™", $str)),$db->connection);
//        } else {
//	        $str = trim(str_replace("�", "™", $str));
//        }
        $str = @expString::escape(trim(str_replace("�", "™", $str)));
        //echo "2
"; eDebug($str,die);
        return $str;
    }


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

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

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

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


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


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

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


    function reset_stats() {
//        global $db;

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

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


    public function attachLink(Request $request)
    {
        $pageId = $request->get('attachment_link_uploaded_to');

        try {
            $this->validate($request, [
                'attachment_link_uploaded_to' => 'required|integer|exists:pages,id',
                'attachment_link_name' => 'required|string|min:1|max:255',
                'attachment_link_url' =>  'required|string|min:1|max:255'
            ]);
        } catch (ValidationException $exception) {
            return response()->view('attachments.manager-link-form', array_merge($request->only(['attachment_link_name', 'attachment_link_url']), [
                'pageId' => $pageId,
                'errors' => new MessageBag($exception->errors()),
            ]), 422);
        }

        $page = $this->pageRepo->getById($pageId);

        $this->checkPermission('attachment-create-all');
        $this->checkOwnablePermission('page-update', $page);

        $attachmentName = $request->get('attachment_link_name');
        $link = $request->get('attachment_link_url');
        $attachment = $this->attachmentService->saveNewFromLink($attachmentName, $link, $pageId);

        return view('attachments.manager-link-form', [
            'pageId' => $pageId,
        ]);
    }


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

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

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


    public function isMethodSafe()
    {
        return in_array($this->getMethod(), array('GET', 'HEAD'));
    }


    public function approve_toggle() {
        global $history;

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

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

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

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


    public static function getSName($zdb, $id, $wid = false, $wnick = false)
    {
        try {
            $select = $zdb->select(self::TABLE);
            $select->where(self::PK . ' = ' . $id);

            $results = $zdb->execute($select);
            $row = $results->current();
            return self::getNameWithCase(
                $row->nom_adh,
                $row->prenom_adh,
                false,
                ($wid === true ? $row->id_adh : false),
                ($wnick === true ? $row->pseudo_adh : false)
            );
        } catch (Throwable $e) {
            Analog::log(
                'Cannot get formatted name for member form id `' . $id . '` | ' .
                $e->getMessage(),
                Analog::WARNING
            );
            throw $e;
        }
    }


    private function encloseForCSV($field)
    {
        return '"' .  cleanCSV($field) . '"';
    }


    public static function botlist() {
        $botlist = array(
                "Teoma",
                "alexa",
                "froogle",
                "inktomi",
                "looksmart",
                "URL_Spider_SQL",
                "Firefly",
                "NationalDirectory",
                "Ask Jeeves",
                "TECNOSEEK",
                "InfoSeek",
                "WebFindBot",
                "girafabot",
                "crawler",
                "www.galaxy.com",
                "Googlebot",
                "Scooter",
                "Slurp",
                "appie",
                "FAST",
                "WebBug",
                "Spade",
                "ZyBorg",
                "rabaz",
                "Twitterbot",
                "MJ12bot",
                "AhrefsBot",
                "bingbot",
                "YandexBot",
                "spbot"
                        );
        return $botlist;
    }


    public function __construct(?string $message = null)
    {
        if ($message === null) {
            $message = _('Invalid email/password combination.');
        }
        parent::__construct($message, 0);
    }


function html_operation_successful( $p_redirect_url, $p_message = '' ) {
	echo '
';

	if( !is_blank( $p_message ) ) {
		echo $p_message . '
';
	}

	echo lang_get( 'operation_successful' ).'
';
	print_bracket_link( $p_redirect_url, lang_get( 'proceed' ) );
	echo '
';
}


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

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

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

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

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

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


    public static function getId($id=''){
        if(isset($id)){
            $sql = sprintf("SELECT * FROM `menus` WHERE `id` = '%d' ORDER BY `order` ASC", $id);
            $menus = Db::result($sql);
            $n = Db::$num_rows;
        }else{
            $menus = '';
        }

        return $menus;
    }


    public function testGetEventsPublicProfile(){
        TestingAuxLib::loadX2NonWebUser ();
        TestingAuxLib::suLogin ('testuser');

        Yii::app()->settings->historyPrivacy = null;
        $lastEventId=0;
        $lastTimestamp=0;
        $myProfile = Profile::model()->findByAttributes(array('username' => 'testuser2'));
        $events=Events::getEvents(
            $lastEventId,$lastTimestamp,null,$myProfile, false);
        $this->assertEquals (
            array_map (
                function ($event) { return $event->id; },
                Events::model ()->findAllByAttributes (array (
                    'user' => 'testuser2',
                    'visibility' => 1
                ))
            ),
            array_map (function ($event) { return $event->id; }, $events['events']));

        TestingAuxLib::restoreX2WebUser ();
    }


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

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


    public function getQuerySelect()
    {
        return '';
    }


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

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

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


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


	function edit_vendor() {
		$vendor = new vendor();

		if(isset($this->params['id'])) {
			$vendor = $vendor->find('first', 'id =' .$this->params['id']);
			assign_to_template(array(
                'vendor'=>$vendor
            ));
		}
	}


    public function start()
    {
        if ($this->started) {
            return true;
        }

        $this->loadSession();
        if (!$this->saveHandler->isWrapper() && !$this->saveHandler->isSessionHandlerInterface()) {
            // This condition matches only PHP 5.3 + internal save handlers
            $this->saveHandler->setActive(true);
        }

        return true;
    }


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


    public function testGetEvents(){
        TestingAuxLib::loadX2NonWebUser ();
        TestingAuxLib::suLogin ('admin');

        Yii::app()->settings->historyPrivacy = null;
        $lastEventId = 0;
        $lastTimestamp = 0;
        $events = Events::getEvents ($lastEventId, $lastTimestamp, 4);
        $this->assertEquals (
            Yii::app()->db->createCommand (
                "select id from x2_events order by timestamp desc, id desc limit 4")
                ->queryColumn (),
            array_map(function ($event) { return $event->id; }, $events['events'])
        );
        TestingAuxLib::restoreX2WebUser ();
    }


public function testComments()
    {
        $antiXss = new \MicroweberPackages\Helper\HTMLClean();

        $string = 'test';
        $content = $antiXss->onlyTags($string);

       $this->assertEquals($string, $content);
    }


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


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


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


    public function downloadfile() {
        if (empty($this->params['fileid'])) {
            flash('error', gt('There was an error while trying to download your file.  No File Specified.'));
            expHistory::back();
        }

        $fd = new filedownload($this->params['fileid']);
        if (empty($this->params['filenum'])) $this->params['filenum'] = 0;

        if (empty($fd->expFile['downloadable'][$this->params['filenum']]->id)) {
            flash('error', gt('There was an error while trying to download your file.  The file you were looking for could not be found.'));
            expHistory::back();
        }

        $fd->downloads++;
        $fd->save();

        // this will set the id to the id of the actual file..makes the download go right.
        $this->params['id'] = $fd->expFile['downloadable'][$this->params['filenum']]->id;
        parent::downloadfile();
    }


    function update_optiongroup_master() {
        global $db;

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

        // if the title of the master changed we should update the option groups that are already using it.
        if ($oldtitle != $og->title) {
            $db->sql('UPDATE '.$db->prefix.'optiongroup SET title="'.$og->title.'" WHERE title="'.$oldtitle.'"');
        }

        expHistory::back();
    }


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

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

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


	function update_vendor() {
		$vendor = new vendor();

		$vendor->update($this->params['vendor']);
        expHistory::back();
    }


function verify(){
    echo $_GET['challenge'];
}


function info_application($bp_name, $bdd){
	$sql = "select * from bp where name = '" . $bp_name . "'";
	$req = $bdd->query($sql);
	$info = $req->fetch();
	echo json_encode($info);
}


    protected function _joinPath($dir, $name)
    {
        return rtrim($dir, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . $name;
    }


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


    public function setModel(Model $model)
    {
        $this->model = $model;

        $this->extensions = $this->model->getAllowedExtensions();

        $this->from($this->model->getObjectTypeDirName());

        return $this;
    }


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


            $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 function getQuerySelect()
    {
        // SubmittedOn is stored in the artifact
        return "a.submitted_by AS `" . $this->name . "`";
    }


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

		$main = $rs[0];

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

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

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


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

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


    public function withPath($path)
    {
        if (!is_string($path)) {
            throw new \InvalidArgumentException(
                'Invalid path provided; must be a string'
            );
        }

        $path = $this->filterPath($path);

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

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


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

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

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

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

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

		return trim($abbrevData[1]);
	}


	function json_decode($json, $assoc=null)
	{
		return array();
	}


                        $_fn[] = self::buildCondition($v, ' && ');
                    }

                    $fn[] = '('.\implode(' || ', $_fn).')';

                    break;

                case '$where':

                    if (\is_callable($value)) {

                        // need implementation
                    }

                    break;

                default:

                    $d = '$document';

                    if (\strpos($key, '.') !== false) {

                        $keys = \explode('.', $key);

                        foreach ($keys as $k) {
                            $d .= '[\''.$k.'\']';
                        }

                    } else {
                        $d .= '[\''.$key.'\']';
                    }

                    if (\is_array($value)) {
                        $fn[] = "\\MongoLite\\UtilArrayQuery::check((isset({$d}) ? {$d} : null), ".\var_export($value, true).')';
                    } else {

                        if (is_null($value)) {

                            $fn[] = "(!isset({$d}))";

                        } else {

                            $_value = \var_export($value, true);

                            $fn[] = "(isset({$d}) && (
                                is_array({$d}) && is_string({$_value})
                                    ? in_array({$_value}, {$d})
                                    : {$d}=={$_value}
                                )
                            )";
                        }
                    }
            }
        }

        return \count($fn) ? \trim(\implode($concat, $fn)) : 'true';
    }


$logo = "";
        }else{
            $logo = "";
        }
        return $logo;
    }


foreach($functions as $function)
		{
			if($function->id == $f)
			{
				if($function->enabled=='1')
					$sortable_assigned[] = '
id.'" category="'.$function->category.'">icon.'" align="absmiddle" /> '.t($function->lid, $function->lid).'
';
				else
					$sortable_assigned[] = '
id.'" category="'.$function->category.'">icon.'" align="absmiddle" /> '.t($function->lid, $function->lid).'
';
			}
		}


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 confirm()
    {
        $project = $this->getProject();
        $swimlane = $this->getSwimlane();

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


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


    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 setLoggerChannel($channel = 'Organizr', $username = null)
	{
		if ($this->hasDB()) {
			$setLogger = false;
			if ($username) {
				$username = htmlspecialchars($username);
			}
			if ($this->logger) {
				if ($channel) {
					if (strtolower($this->logger->getChannel()) !== strtolower($channel)) {
						$setLogger = true;
					}
				}
				if ($username) {
					if (strtolower($this->logger->getTraceId()) !== strtolower($channel)) {
						$setLogger = true;
					}
				}
			} else {
				$setLogger = true;
			}
			if ($setLogger) {
				$channel = $channel ?: 'Organizr';
				return $this->setupLogger($channel, $username);
			} else {
				return $this->logger;
			}
		}
	}


    protected function _joinPath($dir, $name)
    {
        return rtrim($dir, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . $name;
    }


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

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

		$DB->query('
            SELECT node_id, subtype, text
			  FROM nv_webdictionary
			 WHERE node_type = "structure"
			   AND lang = '.protect($current['lang']).'
			   AND subtype IN("action-type", "action-jump-item", "action-jump-branch", "action-new-window")
			   AND website = '.$website->id
        );

		$data = $DB->result();

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

		foreach($data as $row)
		{
			$structure['actions'][$row->node_id][$row->subtype] = $row->text;
		}
	}
}


        function scan_page($parent_id) {
            global $db;

            $sections = $db->selectObjects('section','parent=' . $parent_id);
            $ret = '';
            foreach ($sections as $page) {
                $cLoc = serialize(expCore::makeLocation('container','@section' . $page->id));
                $ret .= scan_container($cLoc, $page->id);
                $ret .= scan_page($page->id);
            }
            return $ret;
        }


    public function uploadAvatar(Request $request)
    {
        $user = auth()->user();

        if ($user && $request->hasFile('admin_avatar')) {
            $user->clearMediaCollection('admin_avatar');

            $user->addMediaFromRequest('admin_avatar')
                ->toMediaCollection('admin_avatar');
        }

        if ($user && $request->has('avatar')) {
            $data = json_decode($request->avatar);
            $user->clearMediaCollection('admin_avatar');

            $user->addMediaFromBase64($data->data)
                ->usingFileName($data->name)
                ->toMediaCollection('admin_avatar');
        }

        return new UserResource($user);
    }


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

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

        if ($this->tagModel->remove($tag_id)) {
            $this->flash->success(t('Tag removed successfully.'));
        } else {
            $this->flash->failure(t('Unable to remove this tag.'));
        }

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