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


	public function test_valid_comment_allow_empty_content() {
		add_filter( 'allow_empty_comment', '__return_true' );
		$result = $this->myxmlrpcserver->wp_newComment(
			array(
				1,
				'administrator',
				'administrator',
				self::$post->ID,
				array(
					'content' => '   ',
				),
			)
		);

		$this->assertNotIXRError( $result );
	}


    public function testNoAuthority($input)
    {
        $uri = new Uri($input);

        $this->assertEquals($input, (string) $uri);
    }


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


    private function generateTempFileData()
    {
        return [
            'name' => md5(mt_rand()),
            'tmp_name' => tempnam(sys_get_temp_dir(), ''),
            'type' => 'image/jpeg',
            'size' => mt_rand(1000, 10000),
            'error' => '0',
        ];
    }


    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 setContainer($container, $type = 'ctText')
    {
        $this->container = $container;
        $container->setType($type);
    }


        foreach ($nodes as $node) {
            if ((($perm == 'view' && $node->public == 1) || expPermissions::check($perm, expCore::makeLocation('navigation', '', $node->id))) && !in_array($node->id, $ignore_ids)) {
                if ($node->active == 1) {
                    $text = str_pad('', ($depth + ($full ? 1 : 0)) * 3, '.', STR_PAD_LEFT) . $node->name;
                } else {
                    $text = str_pad('', ($depth + ($full ? 1 : 0)) * 3, '.', STR_PAD_LEFT) . '(' . $node->name . ')';
                }
                $ar[$node->id] = $text;
                foreach (self::levelDropdownControlArray($node->id, $depth + 1, $ignore_ids, $full, $perm, $addstandalones, $addinternalalias) as $id => $text) {
                    $ar[$id] = $text;
                }
            }
        }


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


	public function addTab($array)
	{
		if (!$array) {
			$this->setAPIResponse('error', 'no data was sent', 422);
			return null;
		}
		$array = $this->checkKeys($this->getTableColumnsFormatted('tabs'), $array);
		$array['group_id'] = ($array['group_id']) ?? $this->getDefaultGroupId();
		$array['category_id'] = ($array['category_id']) ?? $this->getDefaultCategoryId();
		$array['enabled'] = ($array['enabled']) ?? 0;
		$array['default'] = ($array['default']) ?? 0;
		$array['type'] = ($array['type']) ?? 1;
		$array['order'] = ($array['order']) ?? $this->getNextTabOrder() + 1;
		if (array_key_exists('name', $array)) {
			$array['name'] = htmlspecialchars($array['name']);
			if ($this->isTabNameTaken($array['name'])) {
				$this->setAPIResponse('error', 'Tab name: ' . $array['name'] . ' is already taken', 409);
				return false;
			}
		} else {
			$this->setAPIResponse('error', 'Tab name was not supplied', 422);
			return false;
		}
		if (!array_key_exists('url', $array) && !array_key_exists('url_local', $array)) {
			$this->setAPIResponse('error', 'Tab url or url_local was not supplied', 422);
			return false;
		}
		if (!array_key_exists('image', $array)) {
			$this->setAPIResponse('error', 'Tab image was not supplied', 422);
			return false;
		}
		$response = [
			array(
				'function' => 'query',
				'query' => array(
					'INSERT INTO [tabs]',
					$array
				)
			),
		];
		$this->setAPIResponse(null, 'Tab added');
		$this->setLoggerChannel('Tab Management');
		$this->logger->debug('Added Tab for [' . $array['name'] . ']');
		return $this->processQueries($response);
	}


    public function __construct($mongo, array $options)
    {
        if (!($mongo instanceof \MongoClient || $mongo instanceof \Mongo)) {
            throw new \InvalidArgumentException('MongoClient or Mongo instance required');
        }

        if (!isset($options['database']) || !isset($options['collection'])) {
            throw new \InvalidArgumentException('You must provide the "database" and "collection" option for MongoDBSessionHandler');
        }

        $this->mongo = $mongo;

        $this->options = array_merge(array(
            'id_field' => '_id',
            'data_field' => 'data',
            'time_field' => 'time',
            'expiry_field' => 'expires_at',
        ), $options);
    }


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

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

        return $subtask;
    }


    protected function getStatusCode($exception)
    {
        if ($exception instanceof HttpExceptionInterface) {
            $code = $exception->getStatusCode();
        }
        elseif ($exception instanceof AjaxException) {
            $code = 406;
        }
        else {
            $code = 500;
        }

        return $code;
    }


            $pos = strpos($line, $match);

            if ($pos !== false) {
                $var = getvarname(strtok($field, '#'));
                if ($var != '[]') eval('$r' . $var . '=$block;');
            }
        }
    }

    return $r;
}


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


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

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

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


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

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

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


function draw_vdef_preview($vdef_id) {
	?>

vdef=<?php print get_vdef($vdef_id, true);?>

	<?php
}


    public static function flag($vars) {
        switch (SMART_URL) {
            case true:
                $lang = '?lang=' . $vars;
                if (isset($_GET['lang'])) {

                    $uri = explode('?', $_SERVER['REQUEST_URI']);
                    $uri = $uri[0];
                }else{
                    $uri = $_SERVER['REQUEST_URI'];
                }
                $url = $uri . $lang;

                break;

            default:
                // print_r($_GET);
                if (!empty($_GET)) {

                    $val = '';
                    foreach ($_GET as $key => $value) {
                        if ($key == 'lang') {
                            $val .= '&lang='.$vars;
                        }else{
                            $val .= $key . '=' . $value;
                        }
                    }
                }else{
                    $val = "lang=".$vars;
                }
                $lang = !isset($_GET['lang'])? '&lang=' . $vars: $val;
                $url = Site::$url . '/?' . $lang;
                break;

        }

        return $url;
    }


    public function searchNew() {
        global $db, $user;
        //$this->params['query'] = str_ireplace('-','\-',$this->params['query']);
        $sql = "select DISTINCT(p.id) as id, p.title, model, sef_url, f.id as fileid, ";
        $sql .= "match (p.title,p.model,p.body) against ('" . $this->params['query'] . "*' IN BOOLEAN MODE) as relevance, ";
        $sql .= "CASE when p.model like '" . $this->params['query'] . "%' then 1 else 0 END as modelmatch, ";
        $sql .= "CASE when p.title like '%" . $this->params['query'] . "%' then 1 else 0 END as titlematch ";
        $sql .= "from " . $db->prefix . "product as p INNER JOIN " .
            $db->prefix . "content_expFiles as cef ON p.id=cef.content_id AND cef.content_type IN ('product','eventregistration','donation','giftcard') AND cef.subtype='mainimage'  INNER JOIN " . $db->prefix .
            "expFiles as f ON cef.expFiles_id = f.id WHERE ";
        if (!$user->isAdmin()) $sql .= '(p.active_type=0 OR p.active_type=1) AND ';
        $sql .= " match (p.title,p.model,p.body) against ('" . $this->params['query'] . "*' IN BOOLEAN MODE) AND p.parent_id=0 ";
        $sql .= " HAVING relevance > 0 ";
        //$sql .= "GROUP BY p.id ";
        $sql .= "order by modelmatch,titlematch,relevance desc LIMIT 10";

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


    public function update()
    {
        try {
            $_recipients = array();
            if ($this->recipients != null) {
                foreach ($this->recipients as $_r) {
                    $_recipients[$_r->id] = $_r->sname . ' <' . $_r->email . '>';
                }
            }

            $sender = ($this->sender === 0) ?
                new Expression('NULL') : $this->sender;
            $sender_name = ($this->sender_name === null) ?
                new Expression('NULL') : $this->sender_name;
            $sender_address = ($this->sender_address === null) ?
                new Expression('NULL') : $this->sender_address;

            $values = array(
                'mailing_sender'            => $sender,
                'mailing_sender_name'       => $sender_name,
                'mailing_sender_address'    => $sender_address,
                'mailing_subject'           => $this->subject,
                'mailing_body'              => $this->message,
                'mailing_date'              => $this->date,
                'mailing_recipients'        => serialize($_recipients),
                'mailing_sent'              => ($this->sent) ?
                    true :
                    ($this->zdb->isPostgres() ? 'false' : 0)
            );

            $update = $this->zdb->update(self::TABLE);
            $update->set($values);
            $update->where(self::PK . ' = ' . $this->mailing->history_id);
            $this->zdb->execute($update);
            return true;
        } catch (Throwable $e) {
            Analog::log(
                'An error occurend updating Mailing | ' . $e->getMessage(),
                Analog::ERROR
            );
            throw $e;
        }
    }


$link_text = wp_get_attachment_image( $_post->ID, $size, $icon, $attr );
	} else {
		$link_text = '';
	}

	if ( trim( $link_text ) == '' )
		$link_text = $_post->post_title;

	/**
	 * Filters a retrieved attachment page link.
	 *
	 * @since 2.7.0
	 *
	 * @param string       $link_html The page link HTML output.
	 * @param int          $id        Post ID.
	 * @param string|array $size      Size of the image. Image size or array of width and height values (in that order).
	 *                                Default 'thumbnail'.
	 * @param bool         $permalink Whether to add permalink to image. Default false.
	 * @param bool         $icon      Whether to include an icon. Default false.
	 * @param string|bool  $text      If string, will be link text. Default false.
	 */
	return apply_filters( 'wp_get_attachment_link', "$link_text", $id, $size, $permalink, $icon, $text );
}


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


    private function getSwimlane()
    {
        $swimlane = $this->swimlaneModel->getById($this->request->getIntegerParam('swimlane_id'));

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

        return $swimlane;
    }


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

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


                    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 static function is_email($vars){

        if(isset($_GET['act']) && $_GET['act'] == 'edit'){
            $id = Typo::int($_GET['id']);
            $where = "AND `id` != '{$id}' ";
        }else{
            $where = '';
        }
        $vars = sprintf('%s', Typo::cleanX($vars));
        $sql = sprintf("SELECT * FROM `user` WHERE `email` = '%s' %s", $vars, $where );
        $e = Db::result($sql);
        if(Db::$num_rows > 0){
            return false;
        }else{
            return true;
        }
    }


    public static function withoutQueryValue(UriInterface $uri, $key)
    {
        $current = $uri->getQuery();
        if (!$current) {
            return $uri;
        }

        $result = [];
        foreach (explode('&', $current) as $part) {
            if (explode('=', $part)[0] !== $key) {
                $result[] = $part;
            };
        }

        return $uri->withQuery(implode('&', $result));
    }


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


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

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

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


function fix_serialized_columns()
{
	global $smcFunc;

	$request = $smcFunc['db_query']('', '
		SELECT id_action, extra
		FROM {db_prefix}log_actions
		WHERE action IN ({string:remove}, {string:delete})',
		array(
			'remove' => 'remove',
			'delete' => 'delete',
		)
	);
	while ($row = $smcFunc['db_fetch_assoc']($request))
	{
		if (@unserialize($row['extra']) === false && preg_match('~^(a:3:{s:5:"topic";i:\d+;s:7:"subject";s:)(\d+):"(.+)"(;s:6:"member";s:5:"\d+";})$~', $row['extra'], $matches) === 1)
			$smcFunc['db_query']('', '
				UPDATE {db_prefix}log_actions
				SET extra = {string:extra}
				WHERE id_action = {int:current_action}',
				array(
					'current_action' => $row['id_action'],
					'extra' => $matches[1] . strlen($matches[3]) . ':"' . $matches[3] . '"' . $matches[4],
				)
			);
	}
	$smcFunc['db_free_result']($request);

	// Refresh some cached data.
	updateSettings(array(
		'memberlist_updated' => time(),
	));

}


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

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


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


    public function getDisplayName ($plural=true) {
        return Yii::t('calendar', 'Calendar');
    }


    public function __construct($message, $code = 0, Exception $previous = null)
    {
        parent::__construct($message, $code, $previous);
    }


    public function deleteUser(){
        $login_user = $this->checkLogin();
        $this->checkAdmin();
        $uid = I("uid/d");

        if (D("Item")->where("uid = '$uid' and is_del = 0 ")->find()) {
           $this->sendError(10101,"该用户名下还有项目，不允许删除。请先将其项目删除或者重新分配/转让");
           return ;
        }
        $return = D("User")->delete_user($uid);
        if (!$return) {
            $this->sendError(10101);
        }else{
            $this->sendResult($return);
        }
    }


	public static function newFromStyle( $style, \DPL\Parameters $parameters ) {
		$style = strtolower( $style );
		switch ( $style ) {
			case 'definition':
				$class = 'DefinitionHeading';
				break;
			case 'h1':
			case 'h2':
			case 'h3':
			case 'h4':
			case 'h5':
			case 'h6':
			case 'header':
				$class = 'TieredHeading';
				break;
			case 'ordered':
				$class = 'OrderedHeading';
				break;
			case 'unordered':
				$class = 'UnorderedHeading';
				break;
			default:
				return null;
				break;
		}
		$class = '\DPL\Heading\\' . $class;

		return new $class( $parameters );
	}


    public static function checkIp6($requestIp, $ip)
    {
        if (!((extension_loaded('sockets') && defined('AF_INET6')) || @inet_pton('::1'))) {
            throw new \RuntimeException('Unable to check Ipv6. Check that PHP was not compiled with option "disable-ipv6".');
        }

        if (false !== strpos($ip, '/')) {
            list($address, $netmask) = explode('/', $ip, 2);

            if ($netmask < 1 || $netmask > 128) {
                return false;
            }
        } else {
            $address = $ip;
            $netmask = 128;
        }

        $bytesAddr = unpack('n*', inet_pton($address));
        $bytesTest = unpack('n*', inet_pton($requestIp));

        for ($i = 1, $ceil = ceil($netmask / 16); $i <= $ceil; ++$i) {
            $left = $netmask - 16 * ($i - 1);
            $left = ($left <= 16) ? $left : 16;
            $mask = ~(0xffff >> $left) & 0xffff;
            if (($bytesAddr[$i] & $mask) != ($bytesTest[$i] & $mask)) {
                return false;
            }
        }

        return true;
    }


static function isSearchable() { return true; }


	public function uniqueName($dir, $name, $suffix = ' copy', $checkNum = true, $start = 1) {
		$ext  = '';

		if (preg_match('/\.((tar\.(gz|bz|bz2|z|lzo))|cpio\.gz|ps\.gz|xcf\.(gz|bz2)|[a-z0-9]{1,4})$/i', $name, $m)) {
			$ext  = '.'.$m[1];
			$name = substr($name, 0,  strlen($name)-strlen($m[0]));
		}

		if ($checkNum && preg_match('/('.preg_quote($suffix, '/').')(\d*)$/i', $name, $m)) {
			$i    = (int)$m[2];
			$name = substr($name, 0, strlen($name)-strlen($m[2]));
		} else {
			$i     = $start;
			$name .= $suffix;
		}
		$max = $i+100000;

		while ($i <= $max) {
			$n = $name.($i > 0 ? $i : '').$ext;

			if (!$this->stat($this->joinPathCE($dir, $n))) {
				$this->clearcache();
				return $n;
			}
			$i++;
		}


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

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

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

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

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


    public static function dropdown($vars){
        if(is_array($vars)){
            //print_r($vars);
            $name = $vars['name'];
            $where = "WHERE ";
            if(isset($vars['type'])) {
                $where .= " `type` = '{$vars['type']}' AND ";
            }else{
                $where .= " ";
            }
            $where .= " `status` = '1' ";
            $order_by = "ORDER BY ";
            if(isset($vars['order_by'])) {
                $order_by .= " {$vars['order_by']} ";
            }else{
                $order_by .= " `name` ";
            }
            if (isset($vars['sort'])) {
                $sort = " {$vars['sort']}";
            }else{
                $sort = 'ASC';
            }
        }
        $cat = Db::result("SELECT * FROM `posts` {$where} {$order_by} {$sort}");
        $num = Db::$num_rows;
        $drop = "<select name=\"{$name}\" class=\"form-control\"><option></option>";
        if($num > 0){
            foreach ($cat as $c) {
                # code...
                // if($c->parent == ''){
                    if(isset($vars['selected']) && $c->id == $vars['selected']) $sel = "SELECTED"; else $sel = "";
                    $drop .= "<option value=\"{$c->id}\" $sel style=\"padding-left: 10px;\">{$c->title}</option>";
                    // foreach ($cat as $c2) {
                    //     # code...
                    //     if($c2->parent == $c->id){
                    //         if(isset($vars['selected']) && $c2->id == $vars['selected']) $sel = "SELECTED"; else $sel = "";
                    //         $drop .= "<option value=\"{$c2->id}\" $sel style=\"padding-left: 10px;\">   {$c2->name}</option>";
                    //     }
                    // }
                // }

            }
        }
        $drop .= "</select>";

        return $drop;
    }


function mso_current_url($absolute = false, $explode = false, $delete_request = false)
{
	$url = getinfo('site_protocol') . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];

	if ($delete_request) {
		// отделим по «?»
		$url = explode('?', $url);
		$url = $url[0];
	}

	if ($absolute) return $url;

	$url = str_replace(getinfo('site_url'), '', $url);
	$url = trim(str_replace('/', ' ', $url));
	$url = str_replace(' ', '/', $url);
	$url = urldecode($url);

	if ($explode) $url = explode('/', $url);

	return $url;
}


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


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


    function showallSubcategories() {
//        global $db;

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


                $pfTaskJob->update($input);
                $tasks_id = $data['plugin_glpiinventory_tasks_id'];
            }
        } else {
           // case 2: if not exist, create a new task + taskjob
            $this->getFromDB($packages_id);

           //Add the new task
            $input = [
            'name'                    => '[deploy on demand] ' . $this->fields['name'],
            'entities_id'             => $computer->fields['entities_id'],
            'reprepare_if_successful' => 0,
            'is_deploy_on_demand'     => 1,
            'is_active'               => 1,
            ];
            $tasks_id = $pfTask->add($input);

           //Add a new job for the newly created task
           //and enable it
            $input = [
            'plugin_glpiinventory_tasks_id' => $tasks_id,
            'entities_id' => $computer->fields['entities_id'],
            'name'        => 'deploy',
            'method'      => 'deployinstall',
            'targets'     => '[{"PluginGlpiinventoryDeployPackage":"' . $packages_id . '"}]',
            'actors'      => exportArrayToDB([['Computer' => $computers_id]]),
            'enduser'     => exportArrayToDB([$users_id  => [$computers_id]]),
            ];
            $pfTaskJob->add($input);
        }

       //Prepare the task (and only this one)
        $pfTask->prepareTaskjobs(['deployinstall'], $tasks_id);
    }


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


function db_case($array)
{
    global $DatabaseType;

    $counter = 0;
    if ($DatabaseType == 'mysqli') {
        $array_count = count($array);
        $string = " CASE WHEN $array[0] =";
        $counter++;
        $arr_count = count($array);
        for ($i = 1; $i < $arr_count; $i++) {
            $value = $array[$i];

            if ($value == "''" && substr($string, -1) == '=') {
                $value = ' IS NULL';
                $string = substr($string, 0, -1);
            }

            $string .= "$value";
            if ($counter == ($array_count - 2) && $array_count % 2 == 0)
                $string .= " ELSE ";
            elseif ($counter == ($array_count - 1))
                $string .= " END ";
            elseif ($counter % 2 == 0)
                $string .= " WHEN $array[0]=";
            elseif ($counter % 2 == 1)
                $string .= " THEN ";

            $counter++;
        }
    }
    return $string;
}


public static function parseAndTrimExport($str, $isHTML = false) { //�Death from above�? �
        //echo "1
"; eDebug($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("�", "“", $str);
        $str = str_replace("\r\n", " ", $str);
        $str = str_replace("\t", " ", $str);
        $str = str_replace(",", "\,", $str);
        $str = str_replace("�", "¼", $str);
        $str = str_replace("�", "½", $str);
        $str = str_replace("�", "¾", $str);

        if (!$isHTML) {
            $str = str_replace('\"', """, $str);
            $str = str_replace('"', """, $str);
        } else {
            $str = str_replace('"', '""', $str);
        }

        //$str = htmlspecialchars($str);
        //$str = utf8_encode($str);
        $str = trim(str_replace("�", "™", $str));
        //echo "2
"; eDebug($str,die);
        return $str;
    }


		elseif ( $columns['TITLE'] )
		{
			$id_new = DBSeqNextID( 'school_marking_periods_marking_period_id_seq' );

			$sql = "INSERT INTO SCHOOL_MARKING_PERIODS ";

			$fields = "MARKING_PERIOD_ID,MP,SYEAR,SCHOOL_ID,";

			$values = "'" . $id_new . "','" . $_REQUEST['mp_term'] . "','" . UserSyear() . "','" . UserSchool() . "',";

			switch ( $_REQUEST['mp_term'] )
			{
				case 'SEM':
					$fields .= "PARENT_ID,";
					$values .= "'" . $_REQUEST['year_id'] . "',";
					break;

				case 'QTR':
					$fields .= "PARENT_ID,";
					$values .= "'" . $_REQUEST['semester_id'] . "',";
					break;

				case 'PRO':
					$fields .= "PARENT_ID,";
					$values .= "'" . $_REQUEST['quarter_id'] . "',";
					break;
			}

			$go = false;

			foreach ( (array) $columns as $column => $value )
			{
				if ( $column === 'START_DATE'
					|| $column === 'END_DATE'
					|| $column === 'POST_START_DATE'
					|| $column === 'POST_END_DATE' )
				{
					//FJ fix SQL bug START_DATE or END_DATE is null

					if ( ! VerifyDate( $value )
						&& $value !== ''
						|| ( ( $column === 'START_DATE'
							|| $column === 'END_DATE' )
							&& $value === '' ) )
					{
						$error[] = _( 'Not all of the dates were entered correctly.' );

						break 2;
					}

					//FJ verify END_DATE > START_DATE

					if (  ( $column === 'END_DATE'
						&& date_create( $value ) <= date_create( $columns['START_DATE'] ) )
						|| ( $column === 'POST_START_DATE'
							&& $columns['POST_END_DATE'] !== ''
							&& date_create( $value ) > date_create( $columns['POST_END_DATE'] ) ) )
					{
						$error[] = _( 'Start date must be anterior to end date.' );

						break 2;
					}
				}

				if ( ! empty( $value )
					|| $value === '0' )
				{
					$fields .= $column . ',';

					$values .= "'" . $value . "',";

					$go = true;
				}
			}

			$sql .= '(' . mb_substr( $fields, 0, -1 ) . ') values(' . mb_substr( $values, 0, -1 ) . ')';
		}


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


            $count += $db->dropTable($basename);
        }

        flash('message', gt('Deleted').' '.$count.' '.gt('unused tables').'.');
        expHistory::back();
    }


    public function getPath()
    {
        return $this->path == null ? '' : $this->path;
    }


    public function execute(&$params){
        $options = &$this->config['options'];
        $notif = new Notification;
        $notif->user = $this->parseOption('user', $params);
        $notif->createdBy = 'API';
        $notif->createDate = time();
        // file_put_contents('triggerLog.txt',"\n".$notif->user,FILE_APPEND);
        // if($this->parseOption('type',$params) == 'auto') {
        // if(!isset($params['model']))
        // return false;
        // $notif->modelType = get_class($params['model']);
        // $notif->modelId = $params['model']->id;
        // $notif->type = $this->getNotifType();
        // } else {
        $notif->type = 'custom';
        $notif->text = $this->parseOption('text', $params);
        // }

        if ($notif->save()) {
            return array (true, "");
        } else {
            return array(false, array_shift($notif->getErrors()));
        }

    }


				foreach ($aco_value_array as $aco_value) {
					$this->debug_text("shift_acl(): ACO Section Value: $aco_section_value ACO VALUE: $aco_value");
					$aco_key = array_search($aco_value, $acl_array['aco'][$aco_section_value]);

					if ($aco_key !== FALSE) {
						$this->debug_text("shift_acl(): Removing ACO. ($aco_key)");
						unset($acl_array['aco'][$aco_section_value][$aco_key]);
						$update = 1;
					} else {
						$this->debug_text("shift_acl(): ACO doesn't exist, can't remove it.");
					}
				}


    public function edit()
    {
        if((isset($this->params['id']))) $record = new address(intval($this->params['id']));
        else $record = null;
        $config = ecomconfig::getConfig('address_allow_admins_all');
        assign_to_template(array(
            'record'=>$record,
            'admin_config'=>$config
        ));
        if (expSession::get('customer-signup')) {
            assign_to_template(array(
                'checkout'=>true
            ));
        }
    }


    public function remove()
    {
        $this->checkCSRFParam();
        $project = $this->getProject();
        $action = $this->actionModel->getById($this->request->getIntegerParam('action_id'));

        if (! empty($action) && $this->actionModel->remove($action['id'])) {
            $this->flash->success(t('Action removed successfully.'));
        } else {
            $this->flash->failure(t('Unable to remove this action.'));
        }

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


    public function saveconfig() {
        global $db;

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


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


	function lockTable($table,$lockType="WRITE") {
        $sql = "LOCK TABLES `" . $this->prefix . "$table` $lockType";

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


  function get_plural_forms() {
    // lets assume message number 0 is header
    // this is true, right?
    $this->load_tables();

    // cache header field for plural forms
    if (! is_string($this->pluralheader)) {
      if ($this->enable_cache) {
        $header = $this->cache_translations[""];
      } else {
        $header = $this->get_translation_string(0);
      }
      $expr = $this->extract_plural_forms_header_from_po_header($header);
      $this->pluralheader = $this->sanitize_plural_expression($expr);
    }
    return $this->pluralheader;
  }


    public static function footer($vars=""){
        global $GLOBALS;
        if (isset($vars)) {
            # code...
            $GLOBALS['data'] = $vars;
            self::theme('footer', $vars);
        }else{
            self::theme('footer');
        }

    }


    public function testVersion()
    {
        $client = $this->getClientForAuthenticatedUser(User::ROLE_USER);
        $this->assertAccessIsGranted($client, '/api/version');
        $result = json_decode($client->getResponse()->getContent(), true);

        $this->assertIsArray($result);

        $this->assertArrayHasKey('version', $result);
        $this->assertArrayHasKey('versionId', $result);
        $this->assertArrayHasKey('candidate', $result);
        $this->assertArrayHasKey('semver', $result);
        $this->assertArrayHasKey('name', $result);
        $this->assertArrayHasKey('copyright', $result);

        $this->assertSame(Constants::VERSION, $result['version']);
        $this->assertSame(Constants::VERSION_ID, $result['versionId']);
        $this->assertEquals(Constants::STATUS, $result['candidate']);
        $this->assertEquals(Constants::VERSION . '-' . Constants::STATUS, $result['semver']);
        $this->assertEquals(Constants::NAME, $result['name']);
        $this->assertEquals(
            'Kimai - ' . Constants::VERSION . ' ' . Constants::STATUS . ' (' . Constants::NAME . ') by Kevin Papst and contributors.',
            $result['copyright']
        );
    }


   private function getCriterionValue($value) {
      if ($value instanceof \AbstractQuery) {
         return $value->getQuery();
      } else if ($value instanceof \QueryExpression) {
         return $value->getValue();
      } else if (DBmysql::isNameQuoted($value)) { //FIXME: database related
         return $value;
      } else if ($value instanceof \QueryParam) {
         return $value->getValue();
      } else {
         return $this->analyseCriterionValue($value);
      }
   }


function barcode_encode($code,$encoding)
{
    global $genbarcode_loc;

    if (
    ((preg_match("/^ean$/i", $encoding)
    && ( strlen($code)==12 || strlen($code)==13)))

    || (($encoding) && (preg_match("/^isbn$/i", $encoding))
    && (( strlen($code)==9 || strlen($code)==10) ||
    (((preg_match("/^978/", $code) && strlen($code)==12) ||
    (strlen($code)==13)))))

    || (( !isset($encoding) || !$encoding || (preg_match("/^ANY$/i", $encoding) ))
    && (preg_match("/^[0-9]{12,13}$/", $code)))
    )
    {
        /* use built-in EAN-Encoder */
        dol_syslog("barcode.lib.php::barcode_encode Use barcode_encode_ean");
        $bars=barcode_encode_ean($code, $encoding);
    }
    else if (file_exists($genbarcode_loc))
    {
        /* use genbarcode */
        dol_syslog("barcode.lib.php::barcode_encode Use genbarcode ".$genbarcode_loc." code=".$code." encoding=".$encoding);
        $bars=barcode_encode_genbarcode($code, $encoding);
    }
    else
    {
        print "barcode_encode needs an external programm for encodings other then EAN/ISBN
\n";
        print "
\n";
        print "
download gnu-barcode from www.gnu.org/software/barcode/\n";
        print "
compile and install them\n";
        print "
download genbarcode from www.ashberg.de/bar/\n";
        print "
compile and install them\n";
        print "
specify path the genbarcode in barcode module setup\n";
        print "
\n";
        print "
\n";
        return false;
    }
    return $bars;
}


	public function setMultiSectionSeparators( ?array $separators ) {
		$this->multiSectionSeparators = (array)$separators ?? [];
	}


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


            $masteroption->delete();
        }

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

        expHistory::back();
    }


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


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

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

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

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

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


        $confirm = pack('H*', gps('confirm'));
        $name    = substr($confirm, 5);
        $nonce   = safe_field("nonce", 'txp_users', "name = '".doSlash($name)."'");

        if ($nonce and $confirm === pack('H*', substr(md5($nonce), 0, 10)).$name) {
            include_once txpath.'/lib/txplib_admin.php';

            $message = reset_author_pass($name);
        }
    }


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

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


    public function getQuerySelect()
    {
        $R = 'R_' . $this->id;
        return "$R.value_id AS `" . $this->name . "`";
    }


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


    public function password()
    {
        $user = Auth::user();

        return view('account/change-password', compact('user'));
    }


    public static function validateServer($path, $values)
    {
        $result = array(
            'Server' => '',
            'Servers/1/user' => '',
            'Servers/1/SignonSession' => '',
            'Servers/1/SignonURL' => ''
        );
        $error = false;
        if ($values['Servers/1/auth_type'] == 'config'
            && empty($values['Servers/1/user'])
        ) {
            $result['Servers/1/user'] = __(
                'Empty username while using [kbd]config[/kbd] authentication method!'
            );
            $error = true;
        }
        if ($values['Servers/1/auth_type'] == 'signon'
            && empty($values['Servers/1/SignonSession'])
        ) {
            $result['Servers/1/SignonSession'] = __(
                'Empty signon session name '
                . 'while using [kbd]signon[/kbd] authentication method!'
            );
            $error = true;
        }
        if ($values['Servers/1/auth_type'] == 'signon'
            && empty($values['Servers/1/SignonURL'])
        ) {
            $result['Servers/1/SignonURL'] = __(
                'Empty signon URL while using [kbd]signon[/kbd] authentication '
                . 'method!'
            );
            $error = true;
        }

        if (! $error && $values['Servers/1/auth_type'] == 'config') {
            $password = $values['Servers/1/nopassword'] ? null
                : $values['Servers/1/password'];
            $test = static::testDBConnection(
                $values['Servers/1/connect_type'],
                $values['Servers/1/host'],
                $values['Servers/1/port'],
                $values['Servers/1/socket'],
                $values['Servers/1/user'],
                $password,
                'Server'
            );
            if ($test !== true) {
                $result = array_merge($result, $test);
            }
        }
        return $result;
    }


    function logon($username, $password, &$sessionId)
    {
        global $_POST, $_COOKIE;
        global $strUsernameOrPasswordWrong;

        /**
         * @todo Please check if the following statement is in correct place because
         * it seems illogical that user can get session ID from internal login with
         * a bad username or password.
         */

        if (!$this->_verifyUsernameAndPasswordLength($username, $password)) {
            return false;
        }

        $_POST['username'] = $username;
        $_POST['password'] = $password;

        $_POST['login'] = 'Login';

        $_COOKIE['sessionID'] = uniqid('phpads', 1);
        $_POST['phpAds_cookiecheck'] = $_COOKIE['sessionID'];

        $this->preInitSession();
        if ($this->_internalLogin($username, $password)) {
            // Check if the user has administrator access to Openads.
            if (OA_Permission::isUserLinkedToAdmin()) {

                $this->postInitSession();

                $sessionId = $_COOKIE['sessionID'];
                return true;
            } else {

                $this->raiseError('User must be OA installation admin');
                return false;
            }
        } else {

            $this->raiseError($strUsernameOrPasswordWrong);
            return false;
        }
    }


	function output( $p_format = 'dot', $p_headers = false ) {
		# Check if it is a recognized format.
		if( !isset( $this->formats[$p_format] ) ) {
			trigger_error( ERROR_GENERIC, ERROR );
		}

		$t_binary = $this->formats[$p_format]['binary'];
		$t_type = $this->formats[$p_format]['type'];
		$t_mime = $this->formats[$p_format]['mime'];

		# Send Content-Type header, if requested.
		if( $p_headers ) {
			header( 'Content-Type: ' . $t_mime );
		}
		# Retrieve the source dot document into a buffer
		ob_start();
		$this->generate();
		$t_dot_source = ob_get_contents();
		ob_end_clean();

		# Start dot process

		$t_command = $this->graphviz_tool . ' -T' . $p_format;
		$t_descriptors = array(
			0 => array( 'pipe', 'r', ),
			1 => array( 'pipe', 'w', ),
			2 => array( 'file', 'php://stderr', 'w', ),
			);

		$t_pipes = array();
		$t_process = proc_open( $t_command, $t_descriptors, $t_pipes );

		if( is_resource( $t_process ) ) {
			# Filter generated output through dot
			fwrite( $t_pipes[0], $t_dot_source );
			fclose( $t_pipes[0] );

			if( $p_headers ) {
				# Headers were requested, use another output buffer to
				# retrieve the size for Content-Length.
				ob_start();
				while( !feof( $t_pipes[1] ) ) {
					echo fgets( $t_pipes[1], 1024 );
				}
				header( 'Content-Length: ' . ob_get_length() );
				ob_end_flush();
			} else {
				# No need for headers, send output directly.
				while( !feof( $t_pipes[1] ) ) {
					print( fgets( $t_pipes[1], 1024 ) );
				}
			}

			fclose( $t_pipes[1] );
			proc_close( $t_process );
		}
	}


    public function testPinCommentAction()
    {
        $client = $this->getClientForAuthenticatedUser(User::ROLE_ADMIN);
        $this->assertAccessIsGranted($client, '/admin/project/1/details');
        $form = $client->getCrawler()->filter('form[name=project_comment_form]')->form();
        $client->submit($form, [
            'project_comment_form' => [
                'message' => 'Foo bar blub',
            ]
        ]);
        $this->assertIsRedirect($client, $this->createUrl('/admin/project/1/details'));
        $client->followRedirect();
        $node = $client->getCrawler()->filter('div.box#comments_box .direct-chat-text');
        self::assertStringContainsString('Foo bar blub', $node->html());
        $node = $client->getCrawler()->filter('div.box#comments_box .box-body a.btn.active');
        self::assertEquals(0, $node->count());

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

        $this->request($client, '/admin/project/' . $id . '/comment_pin');
        $this->assertIsRedirect($client, $this->createUrl('/admin/project/1/details'));
        $client->followRedirect();
        $node = $client->getCrawler()->filter('div.box#comments_box .box-body a.btn.active');
        self::assertEquals(1, $node->count());
        self::assertEquals($this->createUrl('/admin/project/' . $id . '/comment_pin'), $node->attr('href'));
    }


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


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

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

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

        return $out;
    }


    public function upload() {

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

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

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


    function __construct(Frame $frame, Dompdf $dompdf)
    {
        parent::__construct($frame, $dompdf);
        $url = $frame->get_node()->getAttribute("src");

        $debug_png = $dompdf->getOptions()->getDebugPng();
        if ($debug_png) {
            print '[__construct ' . $url . ']';
        }

        list($this->_image_url, /*$type*/, $this->_image_msg) = Cache::resolve_url(
            $url,
            $dompdf->getProtocol(),
            $dompdf->getBaseHost(),
            $dompdf->getBasePath(),
            $dompdf
        );

        if (Cache::is_broken($this->_image_url) &&
            $alt = $frame->get_node()->getAttribute("alt")
        ) {
            $fontMetrics = $dompdf->getFontMetrics();
            $style = $frame->get_style();
            $font = $style->font_family;
            $size = $style->font_size;
            $word_spacing = $style->word_spacing;
            $letter_spacing = $style->letter_spacing;

            $style->width = (4 / 3) * $fontMetrics->getTextWidth($alt, $font, $size, $word_spacing, $letter_spacing);
            $style->height = $fontMetrics->getFontHeight($font, $size);
        }
    }


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 function getPurchaseOrderByJSON() {

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

		echo json_encode($purchase_orders);
	}


					$_ret[$_k] = $this->convEnc($_v, $from, $to, '', false, $unknown = '_');
				}
				$var = $_ret;
			} else {
				$_var = false;
				if (is_string($var)) {
					$_var = $var;
					if (false !== ($_var = @iconv($from, $to.'//TRANSLIT', $_var))) {
						$_var = str_replace('?', $unknown, $_var);
					}
				}
				if  ($_var !== false) {
					$var = $_var;
				}
			}
			if ($restoreLocale) {
				setlocale(LC_ALL, elFinder::$locale);
			}
		}
		return $var;
	}


$content = ($vars['excerpt'])? substr(
                    strip_tags(
                        Typo::Xclean($p->content)
                    ), 0, $excerptMax): "";

                echo "

id)."\">{$p->title}

".$content."

";
            }


    public function getFilePath($fileName = null)
    {
        if ($fileName === null) {
            $fileName = $this->fileName;
        }

        return $this->theme->getPath().'/'.$this->dirName.'/'.$fileName;
    }


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

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

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

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


function sell_media_ecommerce_enabled( $post_id ) {
	$status = true;
	$meta = get_post_meta( $post_id, 'sell_media_enable_ecommerce', true );
	if ( class_exists( 'VS_Platform' ) && 0 === $meta ) {
		$status = false;
	}
	return $status;
}


$link = str_replace(URL_FULL, '', makeLink(array('section' => $section->id)));


    public function getLatestRevisions()
    {
        if (! $this->latest_revisions) {
            $pm = ProjectManager::instance();
            $project = $pm->getProject($this->group_id);
            if ($project && $this->canBeUsedByProject($project)) {
                list($this->latest_revisions,) = svn_get_revisions($project, 0, 5, '', '', '', '', 0, false);
            }
        }
        return $this->latest_revisions;
    }


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

        $this->proxy->setActive(true);
        $this->proxy->setName('foo');
    }


	protected static function localScandir($dir) {
		// PHP function scandir() is not work well in specific environment. I dont know why.
		// ref. https://github.com/Studio-42/elFinder/issues/1248
		$files = array();
		if ($dh = opendir($dir)) {
			while (false !== ($file = readdir($dh))) {
				if ($file !== '.' && $file !== '..') {
					$files[] = $file;
				}
			}
			closedir($dh);
		} else {
			$this->setError('Can not open local directory.');
		}
		return $files;
	}


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

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

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


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

		if(isset($this->params['id'])) {
			$vendor = $vendor->find('first', 'id =' .$this->params['id']);
			$vendor_title = $vendor->title;
			$state = new geoRegion($vendor->state);
			$vendor->state = $state->name;
			//Removed unnecessary fields
			unset(
                $vendor->title,
                $vendor->table,
                $vendor->tablename,
                $vendor->classname,
                $vendor->identifier
            );

			assign_to_template(array(
                'vendor_title' => $vendor_title,
                'vendor'=>$vendor
            ));
		}
	}


    public static function getModelTypes($assoc = false) {
        $modelTypes = Yii::app()->db->createCommand()
                ->selectDistinct('modelName')
                ->from('x2_fields')
                ->where('modelName!="Calendar"')
                ->order('modelName ASC')
                ->queryColumn();

        if ($assoc === true) {
            return array_combine($modelTypes, array_map(function($term) {
                return Yii::t('app', X2Model::getModelTitle($term));
            }, $modelTypes));
        }
        $modelTypes = array_map(function($term) {
            return Yii::t('app', $term);
        }, $modelTypes);
        return $modelTypes;
    }


        $file = sprintf('%s/%s.class.php', $path, $class_name);
        if(is_file($file))
        {
            include_once $file;
        }

    }
}


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

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

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


    public function sdm_save_upload_meta_data($post_id) {  // Save File Upload metabox
	if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)
	    return;
	if (!isset($_POST['sdm_upload_box_nonce_check']) || !wp_verify_nonce($_POST['sdm_upload_box_nonce_check'], 'sdm_upload_box_nonce'))
	    return;

	if (isset($_POST['sdm_upload'])) {
	    update_post_meta($post_id, 'sdm_upload', $_POST['sdm_upload']);
	}
    }


            ->first(function (User $user) {
                return $user->getPreference('blocksPd', false);
            }) !== null;


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

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


    public static function getHelpVersionId($version) {
        global $db;

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


			form_selectable_cell(filter_value($vdef['name'], get_request_var('filter'), 'vdef.php?action=edit&id=' . $vdef['id']), $vdef['id']);
            form_selectable_cell($disabled ? __('No'):__('Yes'), $vdef['id'], '', 'text-align:right');
            form_selectable_cell(number_format_i18n($vdef['graphs'], '-1'), $vdef['id'], '', 'text-align:right');
            form_selectable_cell(number_format_i18n($vdef['templates'], '-1'), $vdef['id'], '', 'text-align:right');
            form_checkbox_cell($vdef['name'], $vdef['id'], $disabled);
            form_end_row();
        }


    public static function fixName($name) {
        $name = preg_replace('/[^A-Za-z0-9\.]/','_',$name);
        if ($name[0] == '.')
            $name[0] = '_';
        return $name;
//        return preg_replace('/[^A-Za-z0-9\.]/', '-', $name);
    }


    protected function fsock_get_contents(&$url, $timeout, $redirect_max, $ua, $outfp)
    {
        $connect_timeout = 3;
        $connect_try = 3;
        $method = 'GET';
        $readsize = 4096;
        $ssl = '';

        $getSize = null;
        $headers = '';

        $arr = parse_url($url);
        if (!$arr) {
            // Bad request
            return false;
        }
        if ($arr['scheme'] === 'https') {
            $ssl = 'ssl://';
        }

        // query
        $arr['query'] = isset($arr['query']) ? '?' . $arr['query'] : '';
        // port
        $port = isset($arr['port']) ? $arr['port'] : '';
        $arr['port'] = $port ? $port : ($ssl ? 443 : 80);

        $url_base = $arr['scheme'] . '://' . $arr['host'] . ($port ? (':' . $port) : '');


    public function testInfoWithoutUrl()
    {
        $this->assertRequestIsRedirect('info');
    }


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

        if (PHP_VERSION_ID >= 50400 && \PHP_SESSION_ACTIVE === session_status()) {
            throw new \RuntimeException('Failed to start the session: already started by PHP.');
        }

        if (PHP_VERSION_ID < 50400 && !$this->closed && isset($_SESSION) && session_id()) {
            // not 100% fool-proof, but is the most reliable way to determine if a session is active in PHP 5.3
            throw new \RuntimeException('Failed to start the session: already started by PHP ($_SESSION is set).');
        }

        if (ini_get('session.use_cookies') && headers_sent($file, $line)) {
            throw new \RuntimeException(sprintf('Failed to start the session because headers have already been sent by "%s" at line %d.', $file, $line));
        }

        // ok to try and start the session
        if (!session_start()) {
            throw new \RuntimeException('Failed to start the session');
        }

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

        return true;
    }


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


    public static function initializeNavigation() {
        $sections = section::levelTemplate(0, 0);
        return $sections;
    }


    function searchName() {
        return gt("Calendar Event");
    }


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

        $out = array();

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

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

        return $out;
    }


function db_case($array)
{
    global $DatabaseType;

    $counter = 0;
    if ($DatabaseType == 'mysqli') {
        $array_count = count($array);
        $string = " CASE WHEN $array[0] =";
        $counter++;
        $arr_count = count($array);
        for ($i = 1; $i < $arr_count; $i++) {
            $value = $array[$i];

            if ($value == "''" && substr($string, -1) == '=') {
                $value = ' IS NULL';
                $string = substr($string, 0, -1);
            }

            $string .= "$value";
            if ($counter == ($array_count - 2) && $array_count % 2 == 0)
                $string .= " ELSE ";
            elseif ($counter == ($array_count - 1))
                $string .= " END ";
            elseif ($counter % 2 == 0)
                $string .= " WHEN $array[0]=";
            elseif ($counter % 2 == 1)
                $string .= " THEN ";

            $counter++;
        }
    }
    return $string;
}


    public static function local($date, $format=''){
        setlocale(LC_TIME, Options::v('country_id'));
        (empty($format))? $format = "%#d %B %Y %H:%M %p" : $format = $format;
        $timezone = Options::v('timezone');
        $date = new DateTime($date);
        $date->setTimezone(new DateTimeZone($timezone));
        $newdate = $date->format("Y/m/j H:i:s");
        $newdate = strftime($format, strtotime($newdate));
        return $newdate." ".$date->format("T");
    }


    public function getFileContent($file, $identifier)
    {
        $resource = sprintf('hg cat -r %s %s', ProcessExecutor::escape($identifier), ProcessExecutor::escape($file));
        $this->process->execute($resource, $content, $this->repoDir);

        if (!trim($content)) {
            return null;
        }

        return $content;
    }


    public function getQueryOrderby()
    {
        return $this->getBind()->getQueryOrderby();
    }


    public function getQuerySelect()
    {
        return '';
    }


	public function rename($hash, $name) {
		if ($this->commandDisabled('rename')) {
			return $this->setError(elFinder::ERROR_PERM_DENIED);
		}

		if (!$this->nameAccepted($name)) {
			return $this->setError(elFinder::ERROR_INVALID_NAME, $name);
		}

		$mimeByName = elFinderVolumeDriver::mimetypeInternalDetect($name);
		if ($mimeByName && $mimeByName !== 'unknown' && !$this->allowPutMime($mimeByName)) {
			return $this->setError(elFinder::ERROR_INVALID_NAME, $name);
		}

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

		if ($name == $file['name']) {
			return $file;
		}

		if (!empty($file['locked'])) {
			return $this->setError(elFinder::ERROR_LOCKED, $file['name']);
		}

		$path = $this->decode($hash);
		$dir  = $this->dirnameCE($path);
		$stat = $this->stat($this->joinPathCE($dir, $name));
		if ($stat) {
			return $this->setError(elFinder::ERROR_EXISTS, $name);
		}

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

		$this->rmTmb($file); // remove old name tmbs, we cannot do this after dir move

		if ($path = $this->convEncOut($this->_move($this->convEncIn($path), $this->convEncIn($dir), $this->convEncIn($name)))) {
			$this->clearcache();
			return $this->stat($path);
		}
		return false;
	}


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


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


    protected function signDocument(\DOMDocument $document, $node)
    {
        $this->add509Cert($this->getCertificate()->getPublicKey()->getX509Certificate());
        $this->setCanonicalMethod(XMLSecurityDSig::EXC_C14N);
        $this->addReference($document->documentElement, XMLSecurityDSig::SHA1, array('http://www.w3.org/2000/09/xmldsig#enveloped-signature', XMLSecurityDSig::EXC_C14N), array('id_name' => 'ID'));

        $this->sign($this->getCertificate()->getPrivateKey());
        $this->insertSignature($document->firstChild, $node);
        $this->canonicalizeSignedInfo();
    }


  public function IsQmail() {
    if (stristr(ini_get('sendmail_path'), 'qmail')) {
      $this->Sendmail = '/var/qmail/bin/sendmail';
    }
    $this->Mailer = 'sendmail';
  }


    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 static function pathFile($path, $file=false)
	{
		if($file!==false){
			$fullPath = $path.$file;
		}
		else {
			$fullPath = $path;
		}

		// Fix for Windows on paths. eg: $path = c:\diego/page/subpage convert to c:\diego\page\subpages
		$fullPath = str_replace('/', DS, $fullPath);

		if(CHECK_SYMBOLIC_LINKS) {
			$real = realpath($fullPath);
		}
		else {
			$real = file_exists($fullPath)?$fullPath:false;
		}

		// If $real is FALSE the file does not exist.
		if($real===false) {
			return false;
		}

		// If the $real path does not start with the systemPath then this is Path Traversal.
		if(strpos($fullPath, $real)!==0) {
			return false;
		}

		return true;
	}


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

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

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

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

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


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


      print_r($single_error);
    }

    echo '</pre>';
  }


	public function addGroupBy( $groupBy ) {
		if ( empty( $groupBy ) ) {
			throw new \MWException( __METHOD__ . ': An empty group by clause was passed.' );
		}
		$this->groupBy[] = $groupBy;
		return true;
	}


    static function isSearchable() {
        return true;
    }


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

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

        $out = $DB->result();

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

        return $out;
    }


    public static function fixName($name) {
        $name = preg_replace('/[^A-Za-z0-9\.]/','_',$name);
        if ($name[0] == '.')
            $name[0] = '_';
        return $name;
//        return preg_replace('/[^A-Za-z0-9\.]/', '-', $name);
    }


    public function testCompilePathIsProperlyCreated()
    {
        $compiler = new BladeCompiler($this->getFiles(), __DIR__);
        $this->assertEquals(__DIR__.'/'.sha1('foo').'.php', $compiler->getCompiledPath('foo'));
    }


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


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


        foreach ($allowedFolders as $folder) {
            if ('/' . $folder === substr($uri, 0, 1 + strlen($folder))) {
                header('Content-Type: ' . $this->getMime($filePath));
                readfile($filePath);
                return true;
            }
        }


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

            $results = $zdb->execute($select);
            $this->loadFromRs($results->current());
        } catch (Throwable $e) {
            Analog::log(
                'An error occurred loading reminder #' . $id . "Message:\n" .
                $e->getMessage(),
                Analog::ERROR
            );
            throw $e;
        }
    }


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


            $count += $db->dropTable($basename);
        }

        flash('message', gt('Deleted').' '.$count.' '.gt('unused tables').'.');
        expHistory::back();
    }


    public function getMailingDetails($id)
    {
        trigger_error(sprintf('%s:%s is deprecated since Shopware 5.6 and will be private with 5.8.', __CLASS__, __METHOD__), E_USER_DEPRECATED);

        $details = Shopware()->Modules()->Marketing()->sMailCampaignsGetDetail((int) $id);

        foreach ($details['containers'] as $key => $container) {
            if ($container['type'] === 'ctVoucher') {
                if (!empty($container['value'])) {
                    $details['voucher'] = $container['value'];
                }
                $details['containers'][$key]['type'] = 'ctText';
            }
            if ($container['type'] === 'ctSuggest') {
                $details['suggest'] = true;
            }
        }

        return $details;
    }


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

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

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

        return $out;
    }


    public function testValidatesUriCanBeParsed()
    {
        new Uri('///');
    }


$rst[$key] = self::parseAndTrim($st, $unescape);
            }
            return $rst;
        }

        $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);
        $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("¼","¼",$str);
        $str = str_replace("½","½",$str);
        $str = str_replace("¾","¾",$str);
		$str = str_replace("™","™", $str);
		$str = trim($str);

        if ($unescape) {
			$str = stripcslashes($str);
		} else {
	        $str = addslashes($str);
        }

        return $str;
    }


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

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


                self::assertSame($shouldBePresent, $request->hasHeader('Authorization'));
                self::assertSame($shouldBePresent, $request->hasHeader('Cookie'));

                return new Response(200);
            }
        ]);


	private function normalize($str, $opts) {
		if ($opts['nfc'] || $opts['nfkc']) {
			if (class_exists('Normalizer', false)) {
				if ($opts['nfc'] && ! Normalizer::isNormalized($str, Normalizer::FORM_C))
					$str = Normalizer::normalize($str, Normalizer::FORM_C);
				if ($opts['nfkc'] && ! Normalizer::isNormalized($str, Normalizer::FORM_KC))
					$str = Normalizer::normalize($str, Normalizer::FORM_KC);
			} else {
				if (! class_exists('I18N_UnicodeNormalizer', false)) {
					@ include_once 'I18N/UnicodeNormalizer.php';
				}
				if (class_exists('I18N_UnicodeNormalizer', false)) {
					$normalizer = new I18N_UnicodeNormalizer();
					if ($opts['nfc'])
						$str = $normalizer->normalize($str, 'NFC');
					if ($opts['nfkc'])
						$str = $normalizer->normalize($str, 'NFKC');
				}
			}
		}
		if ($opts['lowercase']) {
			$str = strtolower($str);
		}
		if ($opts['convmap'] && is_array($opts['convmap'])) {
			$str = strtr($str, $opts['convmap']);
		}
		return $str;
	}


	public function update()
	{
		global $DB;
		global $events;

		if(!is_array($this->categories))
			$this->categories = array();

		$ok = $DB->execute('
 			UPDATE nv_feeds
			  SET categories = :categories, format = :format, image = :image, entries = :entries,
			  	  content = :content, views = :views, permission = :permission, enabled = :enabled
			WHERE id = :id	AND	website = :website',
			array(
				'id' => $this->id,
				'website' => $this->website,
				'categories' => implode(',', $this->categories),
				'format' => $this->format,
				'image' => value_or_default($this->image, 0),
				'entries' => value_or_default($this->entries, 10),
				'content' => $this->content,
				'views' => value_or_default($this->views, 0),
				'permission' => value_or_default($this->permission, 0),
				'enabled' => value_or_default($this->enabled, 0)
			)
		);

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

		webdictionary::save_element_strings('feed', $this->id, $this->dictionary);
		path::saveElementPaths('feed', $this->id, $this->paths);

        if(method_exists($events, 'trigger'))
        {
            $events->trigger(
                'feed',
                'save',
                array(
                    'feed' => $this
                )
            );
        }

		return true;
	}


	private function deleteDir($dirPath)
	{
		if (!is_dir($dirPath)) {
			$success = unlink($dirPath);
		} else {
			$success = true;
			foreach (array_reverse(elFinderVolumeFTP::listFilesInDirectory($dirPath, false)) as $path) {
				$path = $dirPath . DIRECTORY_SEPARATOR . $path;
				if(is_link($path)) {
					unlink($path);
				} else if (is_dir($path)) {
					$success = rmdir($path);
				} else {
					$success = unlink($path);
				}
				if (!$success) {
					break;
				}
			}
			if($success) {
				$success = rmdir($dirPath);
			}
		}
		if(!$success) {
			$this->setError(elFinder::ERROR_RM, $dirPath);
			return false;
		}
		return $success;
	}


	private function initData() {

		$this->Set('customer', 0, true, true);
		$this->Set('admin', 1, true, true);
		$this->Set('subject', '', true, true);
		$this->Set('category', '0', true, true);
		$this->Set('priority', '2', true, true);
		$this->Set('message', '', true, true);
		$this->Set('dt', 0, true, true);
		$this->Set('lastchange', 0, true, true);
		$this->Set('ip', '', true, true);
		$this->Set('status', '0', true, true);
		$this->Set('lastreplier', '0', true, true);
		$this->Set('by', '0', true, true);
		$this->Set('answerto', '0', true, true);
		$this->Set('archived', '0', true, true);
	}


    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 draw_cdef_preview($cdef_id) {
	?>

cdef=<?php print get_cdef($cdef_id, true);?>

	<?php
}


	public function testGetConfigWithBrokenSystem() {
		$slideshow = true;
		$exceptionMessage = 'Aïe!';
		$this->configService->expects($this->any())
							->method('getFeaturesList')
							->willThrowException(new ServiceException($exceptionMessage));
		// Default status code when something breaks
		$status = Http::STATUS_INTERNAL_SERVER_ERROR;
		$errorMessage = [
			'message' => $exceptionMessage  . ' (' . $status . ')',
			'success' => false
		];
		/** @type JSONResponse $response */
		$response = $this->controller->get($slideshow);

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


    private static function isNonStandardPort($scheme, $host, $port)
    {
        if (!$scheme && $port) {
            return true;
        }

        if (!$host || !$port) {
            return false;
        }

        return !isset(static::$schemes[$scheme]) || $port !== static::$schemes[$scheme];
    }


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


    function render($mode, &$renderer, $data) {
        if($mode == 'xhtml') {
            global $conf;
            $id = $data[0];
            $name = $data[1];

            //prepare for formating
            $link['target'] = $conf['target']['wiki'];
            $link['style']  = '';
            $link['pre']    = '';
            $link['suf']    = '';
            $link['more']   = '';
            $link['class']  = 'internallink';
            $link['url']    = DOKU_INTERNAL_LINK . $id;
            $link['name']   = ($name) ? $name : $id;
            $link['title']  = ($name) ? $name : $id;
            //add search string
            if($search){
                ($conf['userewrite']) ? $link['url'].='?s=' : $link['url'].='&s=';
                $link['url'] .= urlencode($search);
            }

            //output formatted
            $renderer->doc .= $renderer->_formatLink($link);
        }
        return true;
    }


    public function getItems2 (
        $prefix='', $page=0, $limit=20, $valueAttr='name', $nameAttr='name') {

        $modelClass = get_class ($this->owner);
        $model = CActiveRecord::model ($modelClass);
        $table = $model->tableName ();
        $offset = intval ($page) * intval ($limit);

        AuxLib::coerceToArray ($valueAttr);
        $modelClass::checkThrowAttrError (array_merge ($valueAttr, array ($nameAttr)));
        $params = array ();
        if ($prefix !== '') {
            $params[':prefix'] = $prefix . '%';
        }
        $offset = abs ((int) $offset);
        $limit = abs ((int) $limit);
        $command = Yii::app()->db->createCommand ("
            SELECT " . implode (',', $valueAttr) . ", $nameAttr as __name
            FROM $table
            WHERE " . ($prefix === '' ?
               '1=1' : ($nameAttr . ' LIKE :prefix')
            ) . "
            ORDER BY __name
            LIMIT $offset, $limit
        ");


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


            recyclebin::sendToRecycleBin($loc, $parent);
            //FIXME if we delete the module & sectionref the module completely disappears
//            if (class_exists($secref->module)) {
//                $modclass = $secref->module;
//                //FIXME: more module/controller glue code
//                if (expModules::controllerExists($modclass)) {
//                    $modclass = expModules::getControllerClassName($modclass);
//                    $mod = new $modclass($loc->src);
//                    $mod->delete_instance();
//                } else {
//                    $mod = new $modclass();
//                    $mod->deleteIn($loc);
//                }
//            }
        }
//        $db->delete('sectionref', 'section=' . $parent);
        $db->delete('section', 'parent=' . $parent);
    }


                    $modelNames[ucfirst($module->name)] = self::getModelTitle($modelName);
            }
            asort ($modelNames);
            if ($criteria !== null) {
                return $modelNames;
            } else {
                self::$_modelNames = $modelNames;
            }
        }
        return self::$_modelNames;
    }


    public function sdm_save_thumbnail_meta_data($post_id) {  // Save Thumbnail Upload metabox
	if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)
	    return;
	if (!isset($_POST['sdm_thumbnail_box_nonce_check']) || !wp_verify_nonce($_POST['sdm_thumbnail_box_nonce_check'], 'sdm_thumbnail_box_nonce'))
	    return;

	if (isset($_POST['sdm_upload_thumbnail'])) {
	    update_post_meta($post_id, 'sdm_upload_thumbnail', $_POST['sdm_upload_thumbnail']);
	}
    }


    public static function add() {

    }


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


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

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


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


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