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

        //eDebug($this->category);

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

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


	public function delete() {
	    global $user;

        $count = $this->address->find('count', 'user_id=' . $user->id);
        if($count > 1)
        {
            $address = new address($this->params['id']);
	        if ($user->isAdmin() || ($user->id == $address->user_id)) {
                if ($address->is_billing)
                {
                    $billAddress = $this->address->find('first', 'user_id=' . $user->id . " AND id != " . $address->id);
                    $billAddress->is_billing = true;
                    $billAddress->save();
                }
                if ($address->is_shipping)
                {
                    $shipAddress = $this->address->find('first', 'user_id=' . $user->id . " AND id != " . $address->id);
                    $shipAddress->is_shipping = true;
                    $shipAddress->save();
                }
	            parent::delete();
	        }
        }
        else
        {
            flash("error", gt("You must have at least one address."));
        }
	    expHistory::back();
	}


      $values = [READ                => __('Read'),
                      CREATE              => __('Create'),


	public function save_comment( $comment_id = 0, $approval = '' ) {
		if ( !$comment_id || 'spam' === $approval || empty( $_POST['comment_location'] ) || !is_array( $_POST['comment_location'] ) ) {
			return false;
		}

		GeoMashupDB::set_object_location( 'comment', $comment_id, $_POST['comment_location'] );
	}


    protected function getRot13EnvVarProcessorService()
    {
        return $this->services['Symfony\Component\DependencyInjection\Tests\Dumper\Rot13EnvVarProcessor'] = new \Symfony\Component\DependencyInjection\Tests\Dumper\Rot13EnvVarProcessor();
    }


		    $controller = new $ctlname();
		    if (method_exists($controller,'isSearchable') && $controller->isSearchable()) {
//			    $mods[$controller->name()] = $controller->addContentToSearch();
                $mods[$controller->searchName()] = $controller->addContentToSearch();
		    }
	    }

	    uksort($mods,'strnatcasecmp');
	    assign_to_template(array(
            'mods'=>$mods
        ));
    }


    public function pinCommentAction(ProjectComment $comment)
    {
        $comment->setPinned(!$comment->isPinned());
        try {
            $this->repository->saveComment($comment);
        } catch (\Exception $ex) {
            $this->flashUpdateException($ex);
        }

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


function realCharForNumericEntities($matches)
{
	$newstringnumentity = $matches[1];

	if (preg_match('/^x/i', $newstringnumentity)) {
		$newstringnumentity = hexdec(preg_replace('/^x/i', '', $newstringnumentity));
	}

	// The numeric value we don't want as entities
	if (($newstringnumentity >= 65 && $newstringnumentity <= 90) || ($newstringnumentity >= 97 && $newstringnumentity <= 122)) {
		return chr((int) $newstringnumentity);
	}

	return '&#'.$matches[1];
}


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


    protected function _validateSecretKey()
    {
        if (is_array($this->_publicActions) && in_array($this->getRequest()->getActionName(), $this->_publicActions)) {
            return true;
        }

        if (!($secretKey = $this->getRequest()->getParam(Mage_Adminhtml_Model_Url::SECRET_KEY_PARAM_NAME, null))
            || $secretKey != Mage::getSingleton('adminhtml/url')->getSecretKey()) {
            return false;
        }
        return true;
    }


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

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


function phoromatic_system_id_to_name($system_id, $aid = false)
{
	return phoromatic_server::system_id_to_name($system_id, $aid);
}


    public static function ridOld($tokens) {
        $time = time();
        foreach ($tokens as $token => $value) {
            if ($time - $value['time'] > 3600) {
                unset($tokens[$token]);
            }
        }
        return $tokens;
    }


    public function delete() {
        global $db, $history;

        /* 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('Missing id for the comment you would like to delete'));
            $lastUrl = expHistory::getLast('editable');
        }

        // delete the note
        $simplenote = new expSimpleNote($this->params['id']);
        $rows = $simplenote->delete();

        // delete the assocication too
        $db->delete($simplenote->attachable_table, 'expsimplenote_id='.$this->params['id']);

        // send the user back where they came from.
        $lastUrl = expHistory::getLast('editable');
        if (!empty($this->params['tab']))
        {
            $lastUrl .= "#".$this->params['tab'];
        }
        redirect_to($lastUrl);
    }


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


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 getMissingAmount()
    {
        if (empty($this->_id)) {
            return (double)$this->amount;
        }

        try {
            $select = $this->zdb->select(Contribution::TABLE);
            $select->columns(
                array(
                    'sum' => new Expression('SUM(montant_cotis)')
                )
            )->where(self::PK . ' = ' . $this->_id);

            $results = $this->zdb->execute($select);
            $result = $results->current();
            $dispatched_amount = $result->sum;
            return (double)$this->_amount - (double)$dispatched_amount;
        } catch (Throwable $e) {
            Analog::log(
                'An error occurred retrieving missing amounts | ' .
                $e->getMessage(),
                Analog::ERROR
            );
            throw $e;
        }
    }


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

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


	public function update() {
        global $user;

        if (expSession::get('customer-signup')) expSession::set('customer-signup', false);
        if (isset($this->params['address_country_id'])) {
            $this->params['country'] = $this->params['address_country_id'];
            unset($this->params['address_country_id']);
        }
        if (isset($this->params['address_region_id'])) {
            $this->params['state'] = $this->params['address_region_id'];
            unset($this->params['address_region_id']);
        }
		if ($user->isLoggedIn()) {
			// check to see how many other addresses this user has already.
			$count = $this->address->find('count', 'user_id='.$user->id);
			// if this is first address save for this user we'll make this the default
			if ($count == 0)
            {
                $this->params['is_default'] = 1;
                $this->params['is_billing'] = 1;
                $this->params['is_shipping'] = 1;
            }
			// associate this address with the current user.
			$this->params['user_id'] = $user->id;
			// save the object
			$this->address->update($this->params);
		}
        else { //if (ecomconfig::getConfig('allow_anonymous_checkout')){
            //user is not logged in, but allow anonymous checkout is enabled so we'll check
            //a few things that we don't check in the parent 'stuff and create a user account.
            $this->params['is_default'] = 1;
            $this->params['is_billing'] = 1;
            $this->params['is_shipping'] = 1;
            $this->address->update($this->params);
        }
		expHistory::back();
	}


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

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


    public function update() {

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

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


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


	protected function LoadData()
	{
		$this->dataLoaded = true;

		$args = array();
		$args[] = $this->hash;
		$args[] = '--no-merges';

		$canSkip = true;
		if ($this->skip > 0)
			$canSkip = $this->exe->CanSkip();

		if ($canSkip) {
			if ($this->limit > 0) {
				$args[] = '--max-count=' . $this->limit;
			}
			if ($this->skip > 0) {
				$args[] = '--skip=' . $this->skip;
			}
		} else {
			if ($this->limit > 0) {
				$args[] = '--max-count=' . ($this->limit + $this->skip);
			}
		}


function _download_header($filename, $filesize = 0)
{
	$browser=id_browser();
	header('Content-Type: '.(($browser=='IE' || $browser=='OPERA')?
		'application/octetstream':'application/octet-stream'));


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


		foreach($return as $index => $value) {
			if(! is_string($value))
				$return[$index] = $defaultvalue;
			elseif($addslashes)
				$return[$index] = addslashes($value);
		}


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


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

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


    public static function start() {
        session_name('GeniXCMS');
        session_start();
        //unset($_SESSION);
        if (!isset($_SESSION['gxsess']) || $_SESSION['gxsess'] == "" ) {
            $_SESSION['gxsess'] = array (
                                    'key' => self::sesKey(),
                                    'time' => date("Y-m-d H:i:s"),
                                    'val' => array()
                                );
        }

        $GLOBALS['start_time'] = microtime(TRUE);

    }


    public static function updatePassword(Db $zdb, $id_adh, $pass)
    {
        try {
            $cpass = password_hash($pass, PASSWORD_BCRYPT);

            $update = $zdb->update(self::TABLE);
            $update->set(
                array('mdp_adh' => $cpass)
            )->where(self::PK . ' = ' . $id_adh);
            $zdb->execute($update);
            Analog::log(
                'Password for `' . $id_adh . '` has been updated.',
                Analog::DEBUG
            );
            return true;
        } catch (Throwable $e) {
            Analog::log(
                'An error occurred while updating password for `' . $id_adh .
                '` | ' . $e->getMessage(),
                Analog::ERROR
            );
            throw $e;
        }
    }


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

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

        return $swimlane;
    }


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

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


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


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

        return $this;
    }


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

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


  public function IsSMTP() {
    $this->Mailer = 'smtp';
  }


		public function transferPage()
		{
			//FIXME Put Import code in here.
		}


    public static function getTemplateHierarchyFlat($parent, $depth = 1) {
        global $db;

        $arr  = array();
        $kids = $db->selectObjects('section_template', 'parent=' . $parent, 'rank');
//		$kids = expSorter::sort(array('array'=>$kids,'sortby'=>'rank', 'order'=>'ASC'));
        for ($i = 0, $iMax = count($kids); $i < $iMax; $i++) {
            $page        = $kids[$i];
            $page->depth = $depth;
            $page->first = ($i == 0 ? 1 : 0);
            $page->last  = ($i == count($kids) - 1 ? 1 : 0);
            $arr[]       = $page;
            $arr         = array_merge($arr, self::getTemplateHierarchyFlat($page->id, $depth + 1));
        }
        return $arr;
    }


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


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

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


			$fontfile = self::_getfontpath().$file;
		} elseif (@file_exists($file)) {
			$fontfile = $file;
		}
		return $fontfile;
	}


    public static function isActive($mod){
        $json = Options::v('modules');
        $mods = json_decode($json, true);
        //print_r($mods);
        if (!is_array($mods) || $mods == "") {
            $mods = array();
        }

        if(in_array($mod, $mods)){
            return true;
        }else{
            return false;
        }
    }


			$rest  = $count - ( floor( $nsize ) * floor( $iGroup ) );
			if ( $rest > 0 ) {
				$nsize += 1;
			}
			$output .= "{|" . $rowColFormat . "\n|\n";
			for ( $g = 0; $g < $iGroup; $g++ ) {
				$output .= $lister->formatList( $articles, $nstart, $nsize );
				if ( $columns != 1 ) {
					$output .= "\n|valign=top|\n";
				} else {
					$output .= "\n|-\n|\n";
				}
				$nstart = $nstart + $nsize;
				// if ($rest != 0 && $g+1==$rest) $nsize -= 1;
				if ( $nstart + $nsize > $count ) {
					$nsize = $count - $nstart;
				}
			}
			$output .= "\n|}\n";
		} elseif ( $rowSize > 0 ) {


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

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


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

        return $q;
    }


        $rndString = function ($len = 10) {
            $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
            $randomString = '';
            for ($i = 0; $i < $len; $i++) {
                $randomString .= $characters[rand(0, strlen($characters) - 1)];
            }

            return $randomString;
        };


    protected function registerBackendPermissions()
    {
        BackendAuth::registerCallback(function ($manager) {
            $manager->registerPermissions('October.System', [
                'system.manage_updates' => [
                    'label' => 'system::lang.permissions.manage_software_updates',
                    'tab' => 'system::lang.permissions.name'
                ],
                'system.access_logs' => [
                    'label' => 'system::lang.permissions.access_logs',
                    'tab' => 'system::lang.permissions.name'
                ],
                'system.manage_mail_settings' => [
                    'label' => 'system::lang.permissions.manage_mail_settings',
                    'tab' => 'system::lang.permissions.name'
                ],
                'system.manage_mail_templates' => [
                    'label' => 'system::lang.permissions.manage_mail_templates',
                    'tab' => 'system::lang.permissions.name'
                ]
            ]);
        });
    }


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

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


    function manage() {
        expHistory::set('viewable', $this->params);
        //         $category = new storeCategory();
        //         $categories = $category->getFullTree();
        //
        //         // foreach($categories as $i=>$val){
        //         //  if (!empty($this->values) && in_array($val->id,$this->values)) {
        //         //      $this->tags[$i]->value = true;
        //         //  } else {
        //         //      $this->tags[$i]->value = false;
        //         //  }
        //         //  $this->tags[$i]->draggable = $this->draggable;
        //         //  $this->tags[$i]->checkable = $this->checkable;
        //         // }
        //
        // $obj = json_encode($categories);
    }


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


function prepareExchangedData($data, $type)
{
    global $SETTINGS;

    //load ClassLoader
    require_once $SETTINGS['cpassman_dir'].'/sources/SplClassLoader.php';
    //Load AES
    $aes = new SplClassLoader('Encryption\Crypt', '../includes/libraries');
    $aes->register();

    if ($type == "encode") {
        if (isset($SETTINGS['encryptClientServer'])
            && $SETTINGS['encryptClientServer'] === "0"
        ) {
            return json_encode(
                $data,
                JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP
            );
        } else {
            return Encryption\Crypt\aesctr::encrypt(
                json_encode(
                    $data,
                    JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP
                ),
                $_SESSION['key'],
                256
            );
        }
    } elseif ($type == "decode") {
        if (isset($SETTINGS['encryptClientServer'])
            && $SETTINGS['encryptClientServer'] === "0"
        ) {
            return json_decode(
                $data,
                true
            );
        } else {
            return json_decode(
                Encryption\Crypt\aesctr::decrypt(
                    $data,
                    $_SESSION['key'],
                    256
                ),
                true
            );
        }
    }
}


        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 setPassword($newPassword, $doHashing = true)
    {
        global $gSettingsManager, $gPasswordHashAlgorithm, $gChangeNotification;

        if (!$doHashing) {
            if (is_object($gChangeNotification)) {
                $gChangeNotification->logUserChange(
                    (int) $this->getValue('usr_id'),
                    'usr_password',
                    $this->getValue('usr_password'),
                    $newPassword,
                    $this
                );
            }
            return parent::setValue('usr_password', $newPassword, false);
        }

        // get the saved cost value that fits your server performance best and rehash your password
        $options = array('cost' => 10);
        if (isset($gSettingsManager) && $gSettingsManager->has('system_hashing_cost')) {
            $options['cost'] = $gSettingsManager->getInt('system_hashing_cost');
        }

        $newPasswordHash = PasswordUtils::hash($newPassword, $gPasswordHashAlgorithm, $options);

        if ($newPasswordHash === false) {
            return false;
        }

        if (is_object($gChangeNotification)) {
            $gChangeNotification->logUserChange(
                (int) $this->getValue('usr_id'),
                'usr_password',
                $this->getValue('usr_password'),
                $newPasswordHash,
                $this
            );
        }
        return parent::setValue('usr_password', $newPasswordHash, false);
    }


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


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

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


	public function __construct()
	{
		$this->headers = \App\Controller\Headers::getInstance();
		if (!self::$activatedLocale && \App\Config::performance('CHANGE_LOCALE')) {
			\App\Language::initLocale();
			self::$activatedLocale = true;
		}
		if (!self::$activatedCsrf) {
			if ($this->csrfActive && \App\Config::security('csrfActive')) {
				require_once 'config/csrf_config.php';
				\CsrfMagic\Csrf::init();
				$this->csrfActive = true;
			} else {
				$this->csrfActive = false;
			}
			self::$activatedCsrf = true;
		}
	}


					$args['name'][$i] = $this->normalize($name, $opts);
				}
			} else {
				$args['name'] = $this->normalize($args['name'], $opts);
			}
		}
		return true;
	}


    public static function getTemplateHierarchyFlat($parent, $depth = 1) {
        global $db;

        $arr  = array();
        $kids = $db->selectObjects('section_template', 'parent=' . $parent, 'rank');
//		$kids = expSorter::sort(array('array'=>$kids,'sortby'=>'rank', 'order'=>'ASC'));
        for ($i = 0, $iMax = count($kids); $i < $iMax; $i++) {
            $page        = $kids[$i];
            $page->depth = $depth;
            $page->first = ($i == 0 ? 1 : 0);
            $page->last  = ($i == count($kids) - 1 ? 1 : 0);
            $arr[]       = $page;
            $arr         = array_merge($arr, self::getTemplateHierarchyFlat($page->id, $depth + 1));
        }
        return $arr;
    }


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

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

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


    public function delete(){
        $login_user = $this->checkLogin();
        $uid = $login_user['uid'] ;

        $id = I("id/d")? I("id/d") : 0;
        $teamItemInfo = D("TeamItem")->where(" id = '$id'  ")->find();
        $item_id = $teamItemInfo['item_id'] ;
        $team_id = $teamItemInfo['team_id'] ;

        if(!$this->checkItemManage($uid , $item_id)){
            $this->sendError(10303);
            return ;
        }

        $ret = D("TeamItemMember")->where(" item_id = '$item_id' and team_id = '$team_id' ")->delete();
        $ret = D("TeamItem")->where(" id = '$id' ")->delete();

        if ($ret) {
           $this->sendResult($ret);
        }else{
            $return['error_code'] = 10103 ;
            $return['error_message'] = 'request  fail' ;
            $this->sendResult($return);
        }
    }


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


    public function store()
    {
        $title = $this->title;
        if ($title === null || trim($title) === '') {
            $title = new Expression('NULL');
        }

        $subtitle = $this->subtitle;
        if ($subtitle === null || trim($subtitle) === '') {
            $subtitle = new Expression('NULL');
        }

        $data = array(
            'model_header'      => $this->header,
            'model_footer'      => $this->footer,
            'model_type'        => $this->type,
            'model_title'       => $title,
            'model_subtitle'    => $subtitle,
            'model_body'        => $this->body,
            'model_styles'      => $this->styles
        );

        try {
            if ($this->id !== null) {
                $update = $this->zdb->update(self::TABLE);
                $update->set($data)->where(
                    self::PK . '=' . $this->id
                );
                $this->zdb->execute($update);
            } else {
                $data['model_name'] = $this->name;
                $insert = $this->zdb->insert(self::TABLE);
                $insert->values($data);
                $add = $this->zdb->execute($insert);
                if (!($add->count() > 0)) {
                    Analog::log('Not stored!', Analog::ERROR);
                    return false;
                }
            }
            return true;
        } catch (Throwable $e) {
            Analog::log(
                'An error occurred storing model: ' . $e->getMessage() .
                "\n" . print_r($data, true),
                Analog::ERROR
            );
            throw $e;
        }
    }


            foreach( $zones as $id => $zone )
            {
                //print_r($zone);
                /**
                 * Only get timezones explicitely not part of "Others".
                 * @see http://www.php.net/manual/en/timezones.others.php
                 */
                if ( preg_match( '/^(America|Antartica|Arctic|Asia|Atlantic|Europe|Indian|Pacific)\//', $zone['timezone_id'] )
                    && $zone['timezone_id']) {
                    $cities[$zone['timezone_id']][] = $key;
                }
            }


    public static function create() {
        $length = "80";
        $token = "";
        $codeAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        $codeAlphabet.= "abcdefghijklmnopqrstuvwxyz";
        $codeAlphabet.= "0123456789";
        // $codeAlphabet.= "!@#$%^&*()[]\/{}|:\<>";
        //$codeAlphabet.= SECURITY_KEY;
        for($i=0;$i<$length;$i++){
            $token .= $codeAlphabet[Typo::crypto_rand_secure(0,strlen($codeAlphabet))];
        }
        $url = $_SERVER['REQUEST_URI'];
        $url = htmlspecialchars($url, ENT_QUOTES, 'UTF-8');
        $ip = $_SERVER['REMOTE_ADDR'];
        $time = time();
        define('TOKEN', $token);
        define('TOKEN_URL', $url);
        define('TOKEN_IP', $ip);
        define('TOKEN_TIME', $time);
        $json = self::json();
        Options::update('tokens',$json);
        return $token;
    }


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


	private static function init() {
		\DPL\Config::init();

		if ( !isset( self::$createdLinks ) ) {
			self::$createdLinks = [
				'resetLinks' => false,
				'resetTemplates' => false,
				'resetCategories' => false,
				'resetImages' => false,
				'resetdone' => false,
				'elimdone' => false
			];
		}
	}


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

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

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

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

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

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

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


                $query->whereExists(function ($permissionQuery) use (&$tableDetails, $morphClass) {
                    /** @var Builder $permissionQuery */
                    $permissionQuery->select('id')->from('joint_permissions')
                        ->whereColumn('joint_permissions.entity_id', '=', $tableDetails['tableName'] . '.' . $tableDetails['entityIdColumn'])
                        ->where('entity_type', '=', $morphClass)
                        ->where('action', '=', 'view')
                        ->whereIn('role_id', $this->getCurrentUserRoles())
                        ->where(function (QueryBuilder $query) {
                            $this->addJointHasPermissionCheck($query, $this->currentUser()->id);
                        });
                });


	private function getTempDir($volumeTempPath = null) {
		$testDirs = array();
		if ($this->uploadTempPath) {
			$testDirs[] = rtrim(realpath($this->uploadTempPath), DIRECTORY_SEPARATOR);
		}
		if ($volumeTempPath) {
			$testDirs[] = rtrim(realpath($volumeTempPath), DIRECTORY_SEPARATOR);
		}
		if (function_exists('sys_get_temp_dir')) {
			$testDirs[] = sys_get_temp_dir();
		}
		$tempDir = '';
		foreach($testDirs as $testDir) {
			if (!$testDir || !is_dir($testDir)) continue;
			if (is_writable($testDir)) {
				$tempDir = $testDir;
				$gc = time() - 3600;
				foreach(glob($tempDir . DIRECTORY_SEPARATOR .'ELF*') as $cf) {
					if (filemtime($cf) < $gc) {
						@unlink($cf);
					}
				}
				break;
			}
		}
		return $tempDir;
	}


	static public function getStatusText($_lng, $_status = 0)
	{
		switch($_status)
		{
			case 0:
				return $_lng['ticket']['open'];
				break;
			case 1:
				return $_lng['ticket']['wait_reply'];
				break;
			case 2:
				return $_lng['ticket']['replied'];
				break;
			default:
				return $_lng['ticket']['closed'];
				break;
		}
	}


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

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


	protected function replaceTagCount( $tag, $nr ) {
		return str_replace( '%NR%', $nr, $tag );
	}


static function convertXMLFeedSafeChar($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 = str_replace("�", '"', $str);
        $str = str_replace("“",'"', $str);
        $str = str_replace("\r\n"," ",$str);
        $str = str_replace("�"," 1/4",$str);
        $str = str_replace("¼"," 1/4", $str);
        $str = str_replace("�"," 1/2",$str);
        $str = str_replace("½"," 1/2",$str);
        $str = str_replace("�"," 3/4",$str);
        $str = str_replace("¾"," 3/4",$str);
        $str = str_replace("�", "(TM)", $str);
        $str = str_replace("™","(TM)", $str);
        $str = str_replace("®","(R)", $str);
        $str = str_replace("�","(R)",$str);
        $str = str_replace("&","&",$str);
		$str = str_replace(">",">",$str);
        return trim($str);
	}


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

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


	protected function _rmdir($path) {
		$ret = @rmdir($path);
		$ret && clearstatcache();
		return $ret;
	}


$contents[] = ['class' => 'text-center', 'text' => tep_draw_bootstrap_button(IMAGE_SAVE, 'fas fa-save', null, 'primary', null, 'btn-success xxx text-white mr-2') . tep_draw_bootstrap_button(IMAGE_CANCEL, 'fas fa-times', tep_href_link('currencies.php', 'page=' . $_GET['page'] . '&cID=' . $cInfo->currencies_id), null, null, 'btn-light')];


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


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


    public function testQueryMustBeValid()
    {
        (new Uri(''))->withQuery(new \stdClass);
    }


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


    private function _new_password($user_id = 0, $password, $token)
    {
    	$auth = Auth::instance();
		$user = ORM::factory('user',$user_id);
		if ($user->loaded == true)
		{
			// Determine Method (RiverID or standard)

			if (kohana::config('riverid.enable') == TRUE AND ! empty($user->riverid))
			{
				// Use RiverID

				// We don't really have to save the password locally but if a deployer
				//   ever wants to switch back locally, it's nice to have the pw there
				$user->password = $password;
				$user->save();

				// Relay the password change back to the RiverID server
				$riverid = new RiverID;
				$riverid->email = $user->email;
				$riverid->token = $token;
				$riverid->new_password = $password;
				if ($riverid->setpassword() == FALSE)
				{
					// TODO: Something went wrong. Tell the user.
				}

			}
			else
			{
				// Use Standard

				if($auth->hash_password($user->email.$user->last_login, $auth->find_salt($token)) == $token)
				{
					$user->password = $password;
					$user->save();
				}
				else
				{
					// TODO: Something went wrong, tell the user.
				}
			}

			return TRUE;
		}

		// TODO: User doesn't exist, tell the user (meta, I know).

		return FALSE;
	}


				unset($k, $v);
			}
		}

		return self::$user;
	}


	private function _firstrevisionsince( $option ) {
		$this->addTable( 'revision_actor_temp', 'rev' );
		$this->addSelect(
			[
				'rev.revactor_rev',
				'rev.revactor_timestamp'
			]
		);
		// tell the query optimizer not to look at rows that the following subquery will filter out anyway
		$this->addWhere(
			[
				$this->tableNames['page'] . '.page_id = rev.revactor_page',
				'rev.revactor_timestamp >= ' . $this->DB->addQuotes( $option )
			]
		);
		$this->addWhere(
			[
				$this->tableNames['page'] . '.page_id = rev.revactor_page',
				'rev.revactor_timestamp = (SELECT MIN(rev_aux_snc.revactor_timestamp) FROM ' . $this->tableNames['revision_actor_temp'] . ' AS rev_aux_snc WHERE rev_aux_snc.revactor_page=rev.revactor_page AND rev_aux_snc.revactor_timestamp >= ' . $this->convertTimestamp( $option ) . ')'
			]
		);
	}


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

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


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

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

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

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


    public function getTestData()
    {
        return [
            [[], 'Kimai - ' . Constants::VERSION . ' ' . Constants::STATUS . ' (' . Constants::NAME . ') by Kevin Papst and contributors.'],
            [['--name' => true], Constants::NAME],
            [['--candidate' => true], Constants::STATUS],
            [['--short' => true], Constants::VERSION],
            [['--semver' => true], Constants::VERSION . '-' . Constants::STATUS],
        ];
    }


    public function activate_discount(){
        if (isset($this->params['id'])) {
            $discount = new discounts($this->params['id']);
            $discount->update($this->params);
            //if ($discount->discountulator->hasConfig() && empty($discount->config)) {
                //flash('messages', $discount->discountulator->name().' requires configuration. Please do so now.');
                //redirect_to(array('controller'=>'billing', 'action'=>'configure', 'id'=>$discount->id));
            //}
        }

        expHistory::back();
    }


    public static function error ($vars="", $val='') {
        if( isset($vars) && $vars != "" ) {

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

                include($file);

            }

        }else{

            include(GX_PATH.'/inc/lib/Control/Error/unknown.control.php');

        }
    }


	public static function simple($input)
	{
		return empty($str) ? '' : pts_strings::keep_in_string($input, pts_strings::CHAR_LETTER | pts_strings::CHAR_NUMERIC | pts_strings::CHAR_DASH | pts_strings::CHAR_DECIMAL | pts_strings::CHAR_SPACE | pts_strings::CHAR_UNDERSCORE | pts_strings::CHAR_COMMA | pts_strings::CHAR_AT | pts_strings::CHAR_COLON);
	}


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

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

	return $out;
}


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

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


    public function getQuerySelect()
    {
    }


	function delete_vendor() {
		global $db;

        if (!empty($this->params['id'])){
			$db->delete('vendor', 'id =' .$this->params['id']);
		}
        expHistory::back();
    }


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


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


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

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

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

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

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

        return new UserResource($user);
    }


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

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

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


    public function __construct(array $attributes = null)
    {
        $rootDir = realpath(__DIR__ . "/../");
        $this->setChroot(array($rootDir));
        $this->setRootDir($rootDir);
        $this->setTempDir(sys_get_temp_dir());
        $this->setFontDir($rootDir . "/lib/fonts");
        $this->setFontCache($this->getFontDir());

        $ver = "";
        $versionFile = realpath(__DIR__ . "/../VERSION");
        if (file_exists($versionFile) && ($version = trim(file_get_contents($versionFile))) !== false && $version !== '$Format:<%h>$') {
            $ver = "/$version";
        }
        $this->setHttpContext([
            "http" => [
                "follow_location" => false,
                "user_agent" => "Dompdf$ver https://github.com/dompdf/dompdf"
            ]
        ]);

        if (null !== $attributes) {
            $this->set($attributes);
        }
    }


    function __construct($uid, $folder = null, $is_safe = false)
    {
        // decode combined UID-folder identifier
        if (preg_match('/^\d+-.+/', $uid)) {
            list($uid, $folder) = explode('-', $uid, 2);
        }

        $this->uid     = $uid;
        $this->app     = rcube::get_instance();
        $this->storage = $this->app->get_storage();
        $this->folder  = strlen($folder) ? $folder : $this->storage->get_folder();

        // Set current folder
        $this->storage->set_folder($this->folder);
        $this->storage->set_options(array('all_headers' => true));

        $this->headers = $this->storage->get_message($uid);

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

        $this->mime    = new rcube_mime($this->headers->charset);
        $this->subject = $this->headers->get('subject');
        list(, $this->sender) = each($this->mime->decode_address_list($this->headers->from, 1));

        $this->set_safe($is_safe || $_SESSION['safe_messages'][$this->folder.':'.$uid]);
        $this->opt = array(
            'safe'        => $this->is_safe,
            'prefer_html' => $this->app->config->get('prefer_html'),
            'get_url'     => $this->app->url(array(
                    'action' => 'get',
                    'mbox'   => $this->folder,
                    'uid'    => $uid))
        );

        if (!empty($this->headers->structure)) {
            $this->get_mime_numbers($this->headers->structure);
            $this->parse_structure($this->headers->structure);
        }
        else {
            $this->body = $this->storage->get_body($uid);
        }

        // notify plugins and let them analyze this structured message object
        $this->app->plugins->exec_hook('message_load', array('object' => $this));
    }


    public static function recent($vars, $type = 'post') {
        $sql = "SELECT * FROM `posts` WHERE `type` = '{$type}' ORDER BY `date` DESC LIMIT {$vars}";
        $posts = Db::result($sql);
        if(isset($posts['error'])){
            $posts['error'] = "No Posts found.";
        }else{
            $posts = $posts;
        }
        return $posts;
    }


    public static function verify($gresponse) {
        new Xaptcha();
        $recaptcha = new \ReCaptcha\ReCaptcha(self::$secret);
        $resp = $recaptcha->verify($gresponse, $_SERVER['REMOTE_ADDR']);
        if ($resp->isSuccess()) {
            return true;
        }else{
            return false;
        }
    }


	public function admin_maintenance($mode = '')
	{
		$this->_checkReferer();
		switch($mode) {
			case 'backup':
				set_time_limit(0);
				$this->_backupDb($this->request->query['backup_encoding']);
				break;
			case 'restore':
				set_time_limit(0);
				$messages = [];
				if (!$this->request->data) {
					if ($this->Tool->isOverPostSize()) {
						$messages[] = __d('baser', '送信できるデータ量を超えています。合計で %s 以内のデータを送信してください。', ini_get('post_max_size'));
					} else {
						$this->notFound();
					}
				}
				if ($this->_restoreDb($this->request->data)) {
					$messages[] = __d('baser', 'データの復元が完了しました。');
					$error = false;
				} else {
					$messages[] = __d('baser', 'データの復元に失敗しました。ログの確認を行なって下さい。');
					$error = true;
				}
				// Pageモデルがレストア処理でAppModelで初期化されClassRegistryにセットされている為
				ClassRegistry::flush();
				BcSite::flash();
				if (!$error && !$this->Page->createAllPageTemplate()) {
					$messages[] = __d('baser', "ページテンプレートの生成に失敗しました。\n表示できないページはページ管理より更新処理を行ってください。");
				}
				if ($messages) {
					if ($error) {
						$this->BcMessage->setError(implode("\n", $messages));
					} else {
						$this->BcMessage->setInfo(implode("\n", $messages));
					}
				}
				clearAllCache();
				$this->redirect(['action' => 'maintenance']);
				break;
		}
		$this->pageTitle = __d('baser', 'データメンテナンス');
		$this->help = 'tools_maintenance';
	}


	public function __construct( \DPL\Parameters $parameters, \Parser $parser ) {
		parent::__construct( $parameters, $parser );
		$this->textSeparator = $parameters->getParameter( 'inlinetext' );
	}


	public function options($hash) {
		$create = $createext = array();
		if (isset($this->archivers['create']) && is_array($this->archivers['create'])) {
			foreach($this->archivers['create'] as $m => $v) {
				$create[] = $m;
				$createext[$m] = $v['ext'];
			}
		}
		return array(
			'path'            => $this->path($hash),
			'url'             => $this->URL,
			'tmbUrl'          => $this->tmbURL,
			'disabled'        => $this->disabled,
			'separator'       => $this->separator,
			'copyOverwrite'   => intval($this->options['copyOverwrite']),
			'uploadOverwrite' => intval($this->options['uploadOverwrite']),
			'uploadMaxSize'   => intval($this->uploadMaxSize),
			'dispInlineRegex' => $this->options['dispInlineRegex'],
			'jpgQuality'      => intval($this->options['jpgQuality']),
			'archivers'       => array(
				'create'    => $create,
				'extract'   => isset($this->archivers['extract']) && is_array($this->archivers['extract']) ? array_keys($this->archivers['extract']) : array(),
				'createext' => $createext
			),
			'uiCmdMap'        => (isset($this->options['uiCmdMap']) && is_array($this->options['uiCmdMap']))? $this->options['uiCmdMap'] : array(),
			'syncChkAsTs'     => intval($this->options['syncChkAsTs']),
			'syncMinMs'       => intval($this->options['syncMinMs'])
		);
	}


    public static function inc($vars, $data, $dir){
        $file = $dir."/".$vars.".php";
        if (file_exists($file)) {
            include($file);
        }
    }


Tine.Addressbook.ContactGridPanel.countryRenderer = function(data) {
    data = Locale.getTranslationData('CountryList', data);
    return data;
};


            qtip: Tine.Tinebase.common.doubleEncode(attr.name),
            leaf: !!attr.account_grants,
            allowDrop: !!attr.account_grants && attr.account_grants.addGrant
        });

        // copy 'real' data to container space
        attr.container = Ext.copyTo({}, attr, Tine.Tinebase.Model.Container.getFieldNames());
    },


    $scope.deleteNode = function(node) {
      bootbox.confirm('Are you sure you want to remove the node ' + node.nodeLabel + '?', function(ok) {
        if (ok) {
          RequisitionsService.startTiming();
          RequisitionsService.deleteNode(node).then(
            function() { // success
              var index = -1;
              for(var i = 0; i < $scope.filteredNodes.length; i++) {
                if ($scope.filteredNodes[i].foreignId === node.foreignId) {
                  index = i;
                }
              }
              if (index > -1) {
                $scope.filteredNodes.splice(index,1);
              }
              growl.success('The node ' + node.nodeLabel + ' has been deleted.');
            },
            $scope.errorHandler
          );
        }
      });
    };


            content: function() {
                return $(this).data('content');
            }


	add_options(id, values) {
		var select = this.selects[id];
		var selected_value = select.value;
		select.innerHTML = ""; // ensure uniqueness
		this.__add_options_to_select(select, values);
		select.value = selected_value;
	}


    $scope.add = function() {
      bootbox.prompt('Please enter the name for the new requisition', function(foreignSource) {
        if (foreignSource) {
          // Validate Requisition
          if (foreignSource.match(/[/\\?:&*'"]/)) {
            bootbox.alert('Cannot add the requisition ' + foreignSource + ' because the following characters are invalid:<br/>:, /, \\, ?, &, *, \', "');
            return;
          }
          var r = $scope.requisitionsData.getRequisition(foreignSource);
          if (r) {
            bootbox.alert('Cannot add the requisition ' + foreignSource+ ' because there is already a requisition with that name');
            return;
          }
          // Create Requisition
          RequisitionsService.addRequisition(foreignSource).then(
            function(r) { // success
              growl.success('The requisition ' + r.foreignSource + ' has been created.');
            },
            $scope.errorHandler
          );
        }
      });
    };


      function onError(err) {
        if (this === client) {
          assert(!cliError, makeMsg('Unexpected multiple client errors'));
          cliError = err;
        } else {
          assert(!srvError, makeMsg('Unexpected multiple server errors'));
          srvError = err;
        }
        assert.strictEqual(err.level, 'handshake');
        assert(/handshake failed/i.test(err.message),
               makeMsg('Wrong error message'));
      }


ServerStderr.prototype._write = function(data, encoding, cb) {
  var channel = this._channel;
  var sshstream = channel._client._sshstream;
  var outgoing = channel.outgoing;
  var packetSize = outgoing.packetSize;
  var id = outgoing.id;
  var window = outgoing.window;
  var len = data.length;
  var p = 0;
  var ret;
  var buf;
  var sliceLen;

  if (channel.outgoing.state !== 'open')
    return;

  while (len - p > 0 && window > 0) {
    sliceLen = len - p;
    if (sliceLen > window)
      sliceLen = window;
    if (sliceLen > packetSize)
      sliceLen = packetSize;

    ret = sshstream.channelExtData(id, data.slice(p, p + sliceLen), STDERR);

    p += sliceLen;
    window -= sliceLen;

    if (!ret) {
      channel._waitClientDrain = true;
      channel._chunkErr = undefined;
      channel._chunkcbErr = cb;
      break;
    }
  }

  outgoing.window = window;

  if (len - p > 0) {
    if (window === 0)
      channel._waitWindow = true;
    if (p > 0) {
      // partial
      buf = Buffer.allocUnsafe(len - p);
      data.copy(buf, 0, p);
      channel._chunkErr = buf;
    } else
      channel._chunkErr = data;
    channel._chunkcbErr = cb;
    return;
  }

  if (!channel._waitClientDrain)
    cb();
};


App.Actions.DB.update_db_username_hint = function(elm, hint) {
    if (hint.trim() == '') {
        $(elm).parent().find('.hint').html('');
    }
    $(elm).parent().find('.hint').text(GLOBAL.DB_USER_PREFIX + hint);
}


	this.init = function() {
		var o       = this.options,
			win     = this.window,
			preview = this.preview,
			i, p;

		width  = o.width  > 0 ? parseInt(o.width)  : 450;
		height = o.height > 0 ? parseInt(o.height) : 300;

		fm.one('load', function() {
			parent = fm.getUI();
			cwd    = fm.getUI('cwd');

			win.appendTo('body');

			// close window on escape
			$(document).keydown(function(e) {
				e.keyCode == 27 && self.opened() && win.trigger('close')
			})

			if ($.fn.resizable && !fm.UA.Touch) {
				win.resizable({
					handles   : 'se',
					minWidth  : 350,
					minHeight : 120,
					resize    : function() {
						// use another event to avoid recursion in fullscreen mode
						// may be there is clever solution, but i cant find it :(
						preview.trigger('changesize');
					}
				});
			}

			self.change(function() {
				if (self.opened()) {
					self.value ? preview.trigger($.Event('update', {file : self.value})) : win.trigger('close');
				}
			});

			$.each(fm.commands.quicklook.plugins || [], function(i, plugin) {
				if (typeof(plugin) == 'function') {
					new plugin(self)
				}
			});

			preview.bind('update', function() {
				self.info.show();
			});
		});

	}


setup: function () {
            var data = this.model.get('data') || {};

            this.entityType = this.model.get('relatedType') || data.entityType || null;
            this.entityId = this.model.get('relatedId') || data.entityId || null;
            this.entityName = this.model.get('relatedName') ||  data.entityName || null;

            this.messageData['relatedEntityType'] = this.translateEntityType(this.entityType);
            this.messageData['relatedEntity'] = '' + this.entityName +'';

            this.createMessage();
        }


  function mapTOC(suite, obj) {
    var ret = obj;
    obj = obj[suite.title] = obj[suite.title] || { suite: suite };
    suite.suites.forEach(function(suite){
      mapTOC(suite, obj);
    });
    return ret;
  }


function assertArg(arg, name, reason) {
  if (!arg) {
    throw ngMinErr('areq', 'Argument \'{0}\' is {1}', (name || '?'), (reason || 'required'));
  }
  return arg;
}


function tileLevel(inPath, outPath, zoom, tileSize, pattern, quality) {
    var dotExtension = pattern.replace(/.*(\.[^.]+)$/, '$1');
    var patternedFilename = pattern.replace(/\{z\}/, '' + zoom)
        .replace(/\{x\}/, '%[fx:page.x/' + tileSize + ']')
        .replace(/\{y\}/, '%[fx:page.y/' + tileSize + ']')
        .replace(/\.[^.]+$/, '');
    var patternedFilenameWithoutTheFilename = '';
    if (pattern.indexOf(path.sep) > 0) {
        patternedFilenameWithoutTheFilename = pattern.replace(new RegExp(path.sep+'[^'+path.sep+']*$'), '')
        .replace(/\{z\}/, '' + zoom);
    }
    return mkdirp(outPath + path.sep + patternedFilenameWithoutTheFilename)
    .then(()=>{
        var command = 'convert ' + inPath +
            ' -crop ' + tileSize + 'x' + tileSize +
            ' -set filename:tile "' + patternedFilename + '"' +
            ' -quality ' + quality + ' +repage +adjoin' +
            ' "' + outPath + '/%[filename:tile]' + dotExtension + '"' ;
        execSync(command);
    });
}


    function getObjects(callback) {
        main.socket.emit('getAllObjects', function (err, res) {
            if (err) {
                // following errors are possible
                // permissionError
                // Admin is not enabled in cloud settings!
                window.alert(_(err));
                return;
            }

            setTimeout(function () {
                var obj;
                main.objects = res;
                for (var id in main.objects) {
                    if (!main.objects.hasOwnProperty(id) || id.slice(0, 7) === '_design') continue;

                    obj = main.objects[id];

                    if (obj.type === 'instance') main.instances.push(id);
                    if (obj.type === 'enum')     tabs.enums.list.push(id);
                    if (obj.type === 'user')     tabs.users.list.push(id);
                    if (obj.type === 'group')    tabs.users.groups.push(id);
                    if (obj.type === 'adapter')  tabs.adapters.list.push(id);
                    if (obj.type === 'host')     tabs.hosts.addHost(obj);

                    // convert obj.history into obj.custom
                    if (obj.common && obj.common.history) {
                        obj.common.custom = JSON.parse(JSON.stringify(obj.common.history));
                        delete obj.common.history;
                    }
                }
                main.objectsLoaded = true;
                main.initHostsList(true);

                initTabs();
                // init dialogs
                for (var dialog in main.dialogs) {
                    if (main.dialogs.hasOwnProperty(dialog) && typeof main.dialogs[dialog].prepare === 'function') {
                        main.dialogs[dialog].prepare();
                    }
                }

                // Detect node.js version
                checkNodeJsVersions(tabs.hosts.list);

                main.getUser();

                if (typeof callback === 'function') callback();
            }, 0);
        });
    }


Runnable.prototype.resetTimeout = function(){
  var self = this;
  var ms = this.timeout() || 1e9;

  this.clearTimeout();
  this.timer = setTimeout(function(){
    self.callback(new Error('timeout of ' + ms + 'ms exceeded'));
    self.timedOut = true;
  }, ms);
};


  nextId: function(skip, init) {
    var id = 'v' + (this.state.nextId++);
    if (!skip) {
      this.current().vars.push(id + (init ? '=' + init : ''));
    }
    return id;
  },


function valueFn(value) {return function valueRef() {return value;};}


function merge(target, obj) {
  for (var key in obj) {
    if (key === '__proto__' || !hasOwn(obj, key)) {
      continue;
    }

    var oldVal = obj[key];
    var newVal = target[key];

    if (isObject(newVal) && isObject(oldVal)) {
      target[key] = merge(newVal, oldVal);
    } else if (Array.isArray(newVal)) {
      target[key] = union([], newVal, oldVal);
    } else {
      target[key] = clone(oldVal);
    }
  }
  return target;
}


function cellClicked(cell)
	{
		// Forces focusout in IE
		if (!ui.editor.isChromelessView())
		{
			graph.container.focus();
		}

		// Gets the selection cell
		if (cell == null)
		{
			highlight.highlight(null);
			div.innerHTML = '
' + mxResources.get('nothingIsSelected') + '
';
		}
		else
		{
			var attrs = (cell.value != null) ? cell.value.attributes : null;

			if (ui.editor.isChromelessView())
			{
				highlight.highlight(graph.view.getState(cell));
			}

			if (attrs != null)
			{
				var label = graph.sanitizeHtml(graph.getLabel(cell));

				if (label != null && label.length > 0)
				{
					div.innerHTML = '
' + label + '
';
				}
				else
				{
					div.innerHTML = '';
				}

				for (var i = 0; i < attrs.length; i++)
				{
					if (mxUtils.indexOf(ignored, attrs[i].nodeName) < 0 &&
						attrs[i].nodeValue.length > 0)
					{
						// TODO: Add click handler on h2 to output data
						var h2 = document.createElement('h2');
						mxUtils.write(h2, attrs[i].nodeName);
						div.appendChild(h2);
						var p = document.createElement('p');
						mxUtils.write(p, attrs[i].nodeValue);
						div.appendChild(p);
					}
				}
			}
			else
			{
				var label = graph.convertValueToString(cell);

				if (label != '')
				{
					div.innerHTML = '
' + graph.sanitizeHtml(label) + '
';
				}
				else
				{
					div.innerHTML = '
No data
';
				}
			}

			if (!ui.editor.isChromelessView())
			{
				var button = document.createElement('button');
				button.setAttribute('title', 'Click or Shift+Click to write data for all selected cells to the browser console');
				button.style['float'] = 'none';
				mxUtils.write(button, 'Write to Console');

				mxEvent.addListener(button, 'click', function(evt)
				{
					extractData(evt);
				});

				div.appendChild(button);
			}
		}
	};


wp.updates.showErrorInCredentialsForm = function( message ) {
		var $modal = $( '.notification-dialog' );

		// Remove any existing error.
		$modal.find( '.error' ).remove();

		$modal.find( 'h3' ).after( '
' + message + '
' );
	};


				over : function(e, ui) {
					var dst    = $(this),
						helper = ui.helper,
						ctr    = (e.shiftKey || e.ctrlKey || e.metaKey),
						hash, status, inParent;
					e.stopPropagation();
					helper.data('dropover', helper.data('dropover') + 1);
					dst.data('dropover', true);
					if (helper.data('namespace') !== fm.namespace) {
						dst.removeClass(clDropActive);
						return false;
					}
					if (dst.hasClass(fm.res(c, 'cwdfile'))) {
						hash = fm.cwdId2Hash(dst.attr('id'));
						dst.data('dropover', hash);
					} else {
						hash = fm.cwd().hash;
						fm.cwd().write && dst.data('dropover', hash);
					}
					inParent = (fm.file(helper.data('files')[0]).phash === hash);
					if (dst.data('dropover') === hash) {
						$.each(helper.data('files'), function(i, h) {
							if (h === hash || (inParent && !ctr && !helper.hasClass('elfinder-drag-helper-plus'))) {
								dst.removeClass(clDropActive);
								return false; // break $.each
							}
						});
					} else {
						dst.removeClass(clDropActive);
					}
					if (helper.data('locked') || inParent) {
						status = 'elfinder-drag-helper-plus';
					} else {
						status = 'elfinder-drag-helper-move';
						if (ctr) {
							status += ' elfinder-drag-helper-plus';
						}
					}
					dst.hasClass(clDropActive) && helper.addClass(status);
					setTimeout(function(){ dst.hasClass(clDropActive) && helper.addClass(status); }, 20);
				},


function makeMsg(what, msg) {
  return '[' + group + what + ']: ' + msg;
}


mocha.run = function(fn){
  var options = mocha.options;
  mocha.globals('location');

  var query = Mocha.utils.parseQuery(global.location.search || '');
  if (query.grep) mocha.grep(query.grep);
  if (query.invert) mocha.invert();

  return Mocha.prototype.run.call(mocha, function(){
    // The DOM Document is not available in Web Workers.
    if (global.document) {
      Mocha.utils.highlightTags('code');
    }
    if (fn) fn();
  });
};


Conf.prototype.save = function (where, cb) {
  var target = this.sources[where]
  if (!target || !(target.path || target.source) || !target.data) {
    var er
    if (where !== 'builtin') er = new Error('bad save target: ' + where)
    if (cb) {
      process.nextTick(cb.bind(null, er))
      return this
    }
    return this.emit('error', er)
  }

  if (target.source) {
    var pref = target.prefix || ''
    Object.keys(target.data).forEach(function (k) {
      target.source[pref + k] = target.data[k]
    })
    if (cb) process.nextTick(cb)
    return this
  }

  var data = ini.stringify(target.data)

  var then = function then (er) {
    if (er) return done(er)

    fs.chmod(target.path, mode, done)
  }

  var done = function done (er) {
    if (er) {
      if (cb) return cb(er)
      else return this.emit('error', er)
    }
    this._saving --
    if (this._saving === 0) {
      if (cb) cb()
      this.emit('save')
    }
  }

  then = then.bind(this)
  done = done.bind(this)
  this._saving ++

  var mode = where === 'user' ? '0600' : '0666'
  if (!data.trim()) {
    fs.unlink(target.path, function () {
      // ignore the possible error (e.g. the file doesn't exist)
      done(null)
    })
  } else {
    correctMkdir(path.dirname(target.path), function (er) {
      if (er) return then(er)
      fs.writeFile(target.path, data, 'utf8', function (er) {
        if (er) return then(er)
        if (where === 'user' && myUid && myGid) {
          fs.chown(target.path, +myUid, +myGid, then)
        } else {
          then()
        }
      })
    })
  }

  return this
}


exports.sync2 = function(fn, owner) {
	return (function() {

		var params;
		var callback;
		var executed = false;
		var self = owner || this;
		var args = [].slice.call(arguments);

		args.push(function() {
			params = arguments;
			if (!executed && callback) {
				executed = true;
				callback.apply(self, params);
			}
		});

		fn.apply(self, args);

		return function(cb) {
			callback = cb;
			if (!executed && params) {
				executed = true;
				callback.apply(self, params);
			}
		};
	})();
};


		var getExtTemplates = function(isSearch)
		{
			list.style.display = 'none';
			searchBox.style.display = 'none';
			div.style.left = '30px';

			setActiveTab(isSearch? -1 : 1); //deselect all of them if isSearch

			if (oldTemplates == null)
			{
				oldTemplates = templates;
			}

			div.scrollTop = 0;
			div.innerHTML = '';
			spinner.spin(div);

			var callback2 = function(docList, errorMsg, searchImportCats)
			{
				i0 = 0;
				spinner.stop();
				templates = docList;
				searchImportCats = searchImportCats || {};
				var importListsCount = 0;

				for (var cat in searchImportCats)
				{
					importListsCount += searchImportCats[cat].length;
				}

				if (errorMsg)
				{
					div.innerHTML = errorMsg;
				}
				else if (docList.length == 0 && importListsCount == 0)
				{
					div.innerHTML = mxUtils.htmlEntities(mxResources.get('noDiagrams', null, 'No Diagrams Found'));
				}
				else
				{
					div.innerHTML = '';

					if (importListsCount > 0)
					{
						list.style.display = '';
						div.style.left = '160px';
						list.innerHTML = '';

						customCatCount = 0;
						categories = {'draw.io': docList};

						for (var cat in searchImportCats)
						{
							categories[cat] = searchImportCats[cat];
						}

						initUi();
					}
					else
					{
						addTemplates(true);
					}
				}
			}

			if (isSearch)
			{
				searchDocsCallback(searchInput.value, callback2);
			}
			else
			{
				recentDocsCallback(callback2);
			}
		}


c,!c&&r[a]&&(d.extend(r[a]),q&&!q.date&&console.warn("This method of applying plugins is deprecated. See documentation for details.")))};d.locale(m,{});"object"===typeof module&&"object"===typeof module.exports?module.exports=d:"function"===typeof define&&define.amd?define([],function(){return d}):q.date=d})(this);


function getInputs(body) {
  if (body.length !== 1) return;
  var lastExpression = body[0].expression;
  var candidate = lastExpression.toWatch;
  if (candidate.length !== 1) return candidate;
  return candidate[0] !== lastExpression ? candidate : undefined;
}


Toolbar.prototype.setFontSize = function(value)
{
	if (this.sizeMenu != null)
	{
		this.sizeMenu.innerHTML = '';
		var div = document.createElement('div');
		div.style.display = 'inline-block';
		div.style.overflow = 'hidden';
		div.style.textOverflow = 'ellipsis';
		div.style.maxWidth = '24px';
		mxUtils.write(div, value);
		this.sizeMenu.appendChild(div);

		this.appendDropDownImageHtml(this.sizeMenu);
	}
};


    $scope.deleteNode = function(node) {
      bootbox.confirm('Are you sure you want to remove the node ' + node.nodeLabel + '?', function(ok) {
        if (ok) {
          RequisitionsService.startTiming();
          RequisitionsService.deleteNode(node).then(
            function() { // success
              var index = -1;
              for(var i = 0; i < $scope.filteredNodes.length; i++) {
                if ($scope.filteredNodes[i].foreignId === node.foreignId) {
                  index = i;
                }
              }
              if (index > -1) {
                $scope.filteredNodes.splice(index,1);
              }
              growl.success('The node ' + node.nodeLabel + ' has been deleted.');
            },
            $scope.errorHandler
          );
        }
      });
    };


    $scope.delete = function(foreignSource) {
      bootbox.confirm('Are you sure you want to remove the requisition ' + foreignSource + '?', function(ok) {
        if (ok) {
          RequisitionsService.startTiming();
          RequisitionsService.deleteRequisition(foreignSource).then(
            function() { // success
              growl.success('The requisition ' + foreignSource + ' has been deleted.');
            },
            $scope.errorHandler
          );
        }
      });
    };


function usercheck_init(i) {
    var obj = document.getElementById('ajax_output');
    obj.innerHTML = '';

    if (i.value.length < 1)
        return;

    var err = new Array();
    if (i.value.match(/[^A-Za-z0-9_]/))
        err[err.length] = 'Username can only contain letters, numbers and underscores';
    if (i.value.length < 3)
        err[err.length] = 'Username too short';
    if (err != '') {
        obj.style.color = '#ff0000';
        obj.innerHTML = err.join('<br />');
        return;
    }

    var pqr = i.value;

    ajax_call('Validator.php?u=' + i.value + 'user', usercheck_callback, usercheck_error);
}


	wp.updates.beforeunload = function() {
		if ( wp.updates.updateLock ) {
			return wp.updates.l10n.beforeunload;
		}
	};


    main.getHostIcon = function (obj, classes) {
        var icon     = '';
        var alt      = '';

        if (obj && obj.common && obj.common.icon) {
            var result = getIconHtml(obj);
            icon = result.icon;
            alt = result.alt;
        }
        icon = icon || 'img/no-image.png';
        alt  = alt  || '';

        return '<img class="' + (classes || 'treetable-icon') + '" src="' + icon + '" alt="' + alt + '" />';
    };


function hasCustomToString(obj) {
  return isFunction(obj.toString) && obj.toString !== toString;
}


Manager.prototype.authorize = function (data, fn) {
  if (this.get('authorization')) {
    var self = this;

    this.get('authorization').call(this, data, function (err, authorized) {
      self.log.debug('client ' + authorized ? 'authorized' : 'unauthorized');
      fn(err, authorized);
    });
  } else {
    this.log.debug('client authorized');
    fn(null, true);
  }

  return this;
};


    $scope.initialize = function(customHandler) {
      var value = $cookies.get('requisitions_page_size');
      if (value) {
        $scope.pageSize = value;
      }
      growl.success('Retrieving requisition ' + $scope.foreignSource + '...');
      RequisitionsService.getRequisition($scope.foreignSource).then(
        function(requisition) { // success
          $scope.requisition = requisition;
          $scope.filteredNodes = requisition.nodes;
          $scope.updateFilteredNodes();
          if (customHandler) {
            customHandler();
          }
        },
        $scope.errorHandler
      );
    };


  'binary===': function(left, right, context) {
    return function(scope, locals, assign, inputs) {
      var arg = left(scope, locals, assign, inputs) === right(scope, locals, assign, inputs);
      return context ? {value: arg} : arg;
    };
  },


function HTMLCov(runner) {
  var jade = require('jade')
    , file = __dirname + '/templates/coverage.jade'
    , str = fs.readFileSync(file, 'utf8')
    , fn = jade.compile(str, { filename: file })
    , self = this;

  JSONCov.call(this, runner, false);

  runner.on('end', function(){
    process.stdout.write(fn({
        cov: self.cov
      , coverageClass: coverageClass
    }));
  });
}


function forEachSorted(obj, iterator, context) {
  var keys = Object.keys(obj).sort();
  for (var i = 0; i < keys.length; i++) {
    iterator.call(context, obj[keys[i]], keys[i]);
  }
  return keys;
}


this.spacing=0}function Ca(){mxArrowConnector.call(this);this.spacing=0}function Ra(){mxActor.call(this)}function ab(){mxRectangleShape.call(this)}function Ka(){mxActor.call(this)}function bb(){mxActor.call(this)}function Pa(){mxActor.call(this)}function Za(){mxActor.call(this)}function z(){mxActor.call(this)}function L(){mxActor.call(this)}function M(){mxActor.call(this)}function T(){mxActor.call(this)}function ca(){mxActor.call(this)}function ia(){mxActor.call(this)}function ma(){mxEllipse.call(this)}


    $scope.removeAllNodes = function(foreignSource) {
      bootbox.confirm('Are you sure you want to remove all the nodes from ' + foreignSource + '?', function(ok) {
        if (ok) {
          RequisitionsService.startTiming();
          RequisitionsService.removeAllNodesFromRequisition(foreignSource).then(
            function() { // success
              growl.success('All the nodes from ' + foreignSource + ' have been removed, and the requisition has been synchronized.');
              var req = $scope.requisitionsData.getRequisition(foreignSource);
              req.reset();
            },
            $scope.errorHandler
          );
        }
      });
    };


    $scope.save = function() {
      var form = this.nodeForm;
      RequisitionsService.startTiming();
      RequisitionsService.saveNode($scope.node).then(
        function() { // success
          growl.success('The node ' + $scope.node.nodeLabel + ' has been saved.');
          $scope.foreignId = $scope.node.foreignId;
          form.$dirty = false;
        },
        $scope.errorHandler
      );
    };


function checkSettings (ctx, next) {

    console.log('Executing checkSettings');

    ctx.bootErrors = ctx.bootErrors || [];

    console.log('Checking settings');

    if (!env.storageURI) {
      ctx.bootErrors.push({'desc': 'Mandatory setting missing',
      err: 'MONGODB_URI setting is missing, cannot connect to database'});
    }

    if (!env.enclave.isApiKeySet()) {
      ctx.bootErrors.push({'desc': 'Mandatory setting missing',
      err: 'API_SECRET setting is missing, cannot enable REST API'});
    }

    if (env.settings.authDefaultRoles == 'readable') {
      const message = {
        title: "Nightscout readable by world"
        ,message: "Your Nightscout installation is readable by anyone who knows the web page URL. Please consider closing access to the site by following the instructions in the Nightscout documentation."
        ,persistent: true
      };
      ctx.adminnotifies.addNotify(message);
    }

    next();
  }


setup: function () {
            var data = this.model.get('data') || {};

            this.userId = data.userId;

            this.messageData['entityType'] = Espo.Utils.upperCaseFirst((this.translate(data.entityType, 'scopeNames') || '').toLowerCase());
            if (data.personEntityId) {
                this.messageData['from'] = '' + data.personEntityName + '';
            } else {
                this.messageData['from'] = data.fromString || this.translate('empty address');
            }

            this.emailId = data.emailId;
            this.emailName = data.emailName;

            this.createMessage();
        }


                filters.push({'condition': 'AND', 'filters': this.filterPanels[id].getValue(), 'id': id, label: this.filterPanels[id].title});
            }
        }

        // NOTE: always trigger a OR condition, otherwise we sould loose inactive FilterPanles
        //return filters.length == 1 ? filters[0].filters : [{'condition': 'OR', 'filters': filters}];
        return [{'condition': 'OR', 'filters': filters}];
    },


    var filter = function(data) {
        if (data) {
            data = data.replace(new RegExp('<!--(.*?)-->', 'gsi'), '');
        }
        var span = document.createElement('span');
        span.innerHTML = data;
        parse(span);
        return span;
    }


_addFiles: function(files) {
		var self = this, file_html, html = '';

		file_html = '
' +
			'
' +
				'
{ext}
' +
			'
' +
			'
' +
				'

' +
				'{percent} ' +
			'
' +
			'
' +
				'{name} ' +
			'
' +
			'
' +
				'

' +
			'
' +
			'
{size}
' +
			'

' +
		'
';

		if (plupload.typeOf(files) !== 'array') {
			files = [files];
		}

		$.each(files, function(i, file) {
			var ext = o.core.utils.Mime.getFileExtension(file.name) || 'none';

			html += file_html.replace(/\{(\w+)\}/g, function($0, $1) {
				switch ($1) {
					case 'thumb_width':
					case 'thumb_height':
						return self.options[$1];

					case 'size':
						return plupload.formatSize(file.size);

					case 'ext':
						return ext;

					default:
						return file[$1] || '';
				}
			});
		});

		self.filelist.append(html);
	},


				doScan = function(items, isEntry) {
					var dirReader, entry;
					entries = [];
					var length = items.length;
					for (var i = 0; i < length; i++) {
						if (! isEntry) {
							entry = !!items[i].getAsEntry? items[i].getAsEntry() : items[i].webkitGetAsEntry();
						} else {
							entry = items[i];
						}
						if (entry) {
							if (entry.isFile) {
								processing++;
								entry.file(function (file) {
									paths.push('');
									files.push(file);
									processing--;
								});
							} else if (entry.isDirectory) {
								if (fm.api >= 2.1) {
									if (processing > 0) {
										dirctorys.push(entry);
									} else {
										processing = 0;
										dirReader = entry.createReader();
										processing++;
										readEntries(dirReader);
									}
								}
							}
						}
					}
				};


	window.open = async function(url)
	{
		if (url != null && url.startsWith('http'))
		{
			await requestSync({action: 'openExternal', url: url});
		}
		else
		{
			return oldWindowOpen(url);
		}
	}


      appendMultiValue = function(label, value, defaultValue) {
        var isPreselected, rowTemplate;

        isPreselected = false;
        rowTemplate = $($(multiValueTemplateContent).clone());

        for (var defaultValueKey in defaultValue) {
          if (!defaultValue.hasOwnProperty(defaultValueKey)) {
            continue;
          }
          if (defaultValue[defaultValueKey] === value) {
            isPreselected = true;
            break;
          }
        }

        getHelper().getTemplatePropertyDomElement('_label', rowTemplate).append(label);

        if (isPreselected) {
          getHelper().getTemplatePropertyDomElement('_label', rowTemplate).addClass(
            getHelper().getDomElementClassName('selected')
          );
        }

        $(getHelper().getDomElementDataIdentifierSelector('multiValueContainer'), $(template))
          .append(rowTemplate.html());
      };


                  labels: templateInstance.topTasks.get().map((task) => task._id),
                  datasets: [{
                    values: templateInstance.topTasks.get().map((task) => task.count),
                  }],
                },
                tooltipOptions: {
                },
              })
            }
          })
        })
      }


DriveFile&&c.isEditable()||c.constructor==DropboxFile)};EditorUi.prototype.getServiceName=function(){return"draw.io"};EditorUi.prototype.addRemoteServiceSecurityCheck=function(c){c.setRequestHeader("Content-Language","da, mi, en, de-DE")};EditorUi.prototype.loadUrl=function(c,e,g,k,m,q,v,x){EditorUi.logEvent("SHOULD NOT BE CALLED: loadUrl");return this.editor.loadUrl(c,e,g,k,m,q,v,x)};EditorUi.prototype.loadFonts=function(c){EditorUi.logEvent("SHOULD NOT BE CALLED: loadFonts");return this.editor.loadFonts(c)};


    var parse = function(element) {
       // Remove attributes
       if (element.attributes && element.attributes.length) {
           var image = null;
           var style = null;
           // Process style attribute
           var elementStyle = element.getAttribute('style');
           if (elementStyle) {
               style = [];
               var t = elementStyle.split(';');
               for (var j = 0; j < t.length; j++) {
                   var v = t[j].trim().split(':');
                   if (validStyle.indexOf(v[0].trim()) >= 0) {
                       var k = v.shift();
                       var v = v.join(':');
                       style.push(k + ':' + v);
                   }
               }
           }
           // Process image
           if (element.tagName == 'IMG') {
               if (! obj.options.acceptImages) {
                   element.remove();
               } else {
                   // Check if is data
                   element.setAttribute('tabindex', '900');
                   // Check attributes for persistance
                   obj.addImage(element.src);
               }
           } else {
               // Remove attributes
               var numAttributes = element.attributes.length - 1;
               for (var i = numAttributes; i >= 0 ; i--) {
                   element.removeAttribute(element.attributes[i].name);
               }
           }
           element.style = '';
           // Add valid style
           if (style && style.length) {
               element.setAttribute('style', style.join(';'));
           }
       }
       // Parse children
       if (element.children.length) {
           for (var i = 0; i < element.children.length; i++) {
               parse(element.children[i]);
           }
       }

       if (remove.indexOf(element.constructor) >= 0) {
           element.remove();
       }
    }


  'readYAML': function(test) {
    test.expect(4);
    var obj;
    obj = grunt.file.readYAML('test/fixtures/utf8.yaml');
    test.deepEqual(obj, this.object, 'file should be read as utf8 by default and parsed correctly.');

    obj = grunt.file.readYAML('test/fixtures/iso-8859-1.yaml', {encoding: 'iso-8859-1'});
    test.deepEqual(obj, this.object, 'file should be read using the specified encoding.');

    test.throws(function() {
      obj = grunt.file.readYAML('test/fixtures/error.yaml');
    }, function(err) {
      return err.message.indexOf('undefined') === -1;
    }, 'error thrown should not contain undefined.');

    grunt.file.defaultEncoding = 'iso-8859-1';
    obj = grunt.file.readYAML('test/fixtures/iso-8859-1.yaml');
    test.deepEqual(obj, this.object, 'changing the default encoding should work.');
    test.done();
  },


    this.disableNewChatSoundAdmin = function(inst)
    {
        if (inst.prop('tagName') != 'I') {
            inst = inst.find('> i.material-icons');
        }

    	if (inst.text() == 'volume_off'){
    		$.get(this.wwwDir+  'user/setsettingajax/new_chat_sound/1');
    		confLH.new_chat_sound_enabled = 1;
    		inst.text('volume_up');
    	} else {
    		$.get(this.wwwDir+  'user/setsettingajax/new_chat_sound/0');
    		confLH.new_chat_sound_enabled = 0;
    		inst.text('volume_off');
    	}
    	return false;
    };


setTemplates: function() {
            var iconHTML = '';
            if (this.options.suggestionIcon !== '') {
                iconHTML = '';
            }

            // suggestions
            if (this.options.fields.length) {
                this.suggestionTpl = this.sandbox.util.template('' +
                    '<div class="' + this.options.suggestionClass + '" data-id="<%= context[\'id \']%>">' +
                    '
' +
                    '
' +
                    '           <% _.each(fields, function(field, idx) { %>' +
                    '           <div class="suggestion-column" style="width: <%= field.width %>;"><%= context[field.id] %>
' +
                    '           <% }) %>' +
                    '
' +
                    '
' +
                    '
');
            } else {
                this.suggestionTpl = this.sandbox.util.template('' +
                    '<div class="' + this.options.suggestionClass + '" data-id="<%= context[\'id \']%>">' +
                    '
' +
                            iconHTML +
                    '
<%= context[this.options.valueKey] %>
' +
                    '
' +
                    '
');
            }

            if (!!this.options.footerContent) {
                this.footerTpl = this.sandbox.util.template(
                    '
' +
                        this.options.footerContent +
                    '
'
                );
            }
        },


    obj.select = function(o) {
        var menu = el.querySelectorAll('nav a');
        for (var i = 0; i < menu.length; i++) {
            menu[i].classList.remove('selected');
        }
        o.classList.add('selected');

        // Better navigation
        if (options && options.collapse == true) {
            if (o.classList.contains('show')) {
                menu = el.querySelectorAll('nav');
                for (var i = 0; i < menu.length; i++) {
                    menu[i].style.display = '';
                }
                o.style.display = 'none';
            } else {
                menu = el.querySelectorAll('nav');
                for (var i = 0; i < menu.length; i++) {
                    menu[i].style.display = 'none';
                }

                menu = el.querySelector('.show');
                if (menu) {
                    menu.style.display = 'block';
                }

                menu = jSuites.findElement(o.parentNode, 'selected');
                if (menu) {
                    menu.style.display = '';
                }
            }
        }

        // Close menu if is oped
        if (jSuites.getWindowWidth() < 800) {
            setTimeout(function() {
                obj.hide();
            }, 0);
        }
    }


    value: function __isInt(value) {
      return /^(\-|\+)?([1-9]+[0-9]*)$/.test(value);
    }


    $scope.delete = function(foreignSource) {
      bootbox.confirm('Are you sure you want to remove the requisition ' + foreignSource + '?', function(ok) {
        if (ok) {
          RequisitionsService.startTiming();
          RequisitionsService.deleteRequisition(foreignSource).then(
            function() { // success
              growl.success('The requisition ' + foreignSource + ' has been deleted.');
            },
            $scope.errorHandler
          );
        }
      });
    };


	wp.updates.requestForCredentialsModalCancel = function() {
		// no updateLock and no updateQueue means we already have cleared things up
		var data, $message;

		if( wp.updates.updateLock === false && wp.updates.updateQueue.length === 0 ){
			return;
		}

		data = wp.updates.updateQueue[0].data;

		// remove the lock, and clear the queue
		wp.updates.updateLock = false;
		wp.updates.updateQueue = [];

		wp.updates.requestForCredentialsModalClose();
		if ( 'plugins' === pagenow || 'plugins-network' === pagenow ) {
			$message = $( '[data-plugin="' + data.plugin + '"]' ).next().find( '.update-message' );
		} else if ( 'plugin-install' === pagenow ) {
			$message = $( '.plugin-card-' + data.slug ).find( '.update-now' );
		}

		$message.removeClass( 'updating-message' );
		$message.html( $message.data( 'originaltext' ) );
		wp.a11y.speak( wp.updates.l10n.updateCancel );
	};


elFinder.prototype.commands.cut = function() {

	this.shortcuts = [{
		pattern     : 'ctrl+x shift+insert'
	}];

	this.getstate = function(sel) {
		var sel = this.files(sel),
			cnt = sel.length;

		return !this._disabled && cnt && $.map(sel, function(f) { return f.phash && f.read && !f.locked ? f : null  }).length == cnt ? 0 : -1;
	}

	this.exec = function(hashes) {
		var fm     = this.fm,
			dfrd   = $.Deferred()
				.fail(function(error) {
					fm.error(error);
				});

		$.each(this.files(hashes), function(i, file) {
			if (!(file.read && file.phash) ) {
				return !dfrd.reject(['errCopy', file.name, 'errPerm']);
			}
			if (file.locked) {
				return !dfrd.reject(['errLocked', file.name]);
			}
		});

		return dfrd.state() == 'rejected' ? dfrd : dfrd.resolve(fm.clipboard(this.hashes(hashes), true));
	}

}


  computedMember: function(left, right, context, create) {
    return function(scope, locals, assign, inputs) {
      var lhs = left(scope, locals, assign, inputs);
      var rhs;
      var value;
      if (lhs != null) {
        rhs = right(scope, locals, assign, inputs);
        rhs = getStringValue(rhs);
        if (create && create !== 1) {
          if (lhs && !(lhs[rhs])) {
            lhs[rhs] = {};
          }
        }
        value = lhs[rhs];
      }
      if (context) {
        return {context: lhs, name: rhs, value: value};
      } else {
        return value;
      }
    };
  },