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

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


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

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


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

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


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


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


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

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


function shibboleth_login_form() {
	$login_url = add_query_arg('action', 'shibboleth');
	$login_url = remove_query_arg('reauth', $login_url);
	echo '
' . __('Login with Shibboleth', 'shibboleth') . '
';
}


    public function delete($fileName = null)
    {
        $this->validateFileName();

        list($name, $extension) = $this->model->getFileNameParts();

        return $this->datasource->delete(
            $this->model->getObjectTypeDirName(),
            $name,
            $extension
        );
    }


    public function get($columns = ['*'])
    {
        if (!is_null($this->cacheMinutes)) {
            $results = $this->getCached($columns);
        }
        else {
            $results = $this->getFresh($columns);
        }

        $models = $this->getModels($results ?: []);

        return $this->model->newCollection($models);
    }


function sqlrequest($database,$sql,$id=false){

	// Get the global value
	global $database_host;
	global $database_username;
	global $database_password;

	$connexion = mysqli_connect($database_host, $database_username, $database_password, $database);
	if (!$connexion) {
		echo "
";
		echo "
Alert EyesOfNetwork - Message EON-database connect
";
		echo "
 Could not connect to database : $database ($database_host)
";
		echo "
";
		exit(1);
	}

	if ( $database == "eonweb" ) {
		// Force UTF-8
		mysqli_query($connexion, "SET NAMES 'utf8'");
	}
	$result=mysqli_query($connexion, "$sql");

	if($id==true)
		$result=mysqli_insert_id($connexion);

	mysqli_close($connexion);
	return $result;
}


function editEvent($selected_events, $queue, $comments)
{
	global $database_ged;

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

	// format comment string to avoid errors
	$comments = str_replace("'", "\'", $comments);
	$comments = str_replace("#", "\#", $comments);

	$sql = "UPDATE ".$ged_type."_queue_".$queue." SET comments='$comments' WHERE id = $id";
	$result = sqlrequest($database_ged, $sql);
	if($result){
		message(11, " : ".getLabel("message.event_edited"), "ok");
	} else {
		message(11, " : ".getLabel("message.event_edited_error"), "danger");
	}
}


public function set_controller($controller, $action)
	{
		include CLASS_DIR . 'module.php';

		$module = new Module($controller);

		define ('MODULE_NAME', $module->get_name());

		$class_file = APP_DIR . 'controller/' . MODULE_NAME . '.php';
		$class_name = ucfirst(MODULE_NAME) . '_Controller';
		$class_method = ucfirst($action) . '_Action';

		// tworzy obiekt kontrolera:

		if (file_exists($class_file))
		{
			include $class_file;

			if (class_exists($class_name))
			{
				$this->controller_object = new $class_name($this);

				$this->set_acl($this);
			}
			else
			{
				die ('Class:
'.$class_name.'
 not found.');
			}
		}
		else
		{
			die ('File:
'.$class_file.'
 not found.');
		}

		// tworzy obiekt modelu:

		$this->set_model_object(MODULE_NAME);

		// tworzy obiekt widoku:

		$this->set_view_object(MODULE_NAME);

		// wywołuje akcję (metodę) kontrolera:

		if (method_exists($class_name, $class_method))
		{
			$this->controller_object->{$class_method}();
		}
		else
		{
			die ('Method:
'.$class_method.'
 in class:
'.$class_name.'
 not found.');
		}
	}


    public function dispatch($messages, $final)
    {
        $targetErrors = [];
        foreach ($this->targets as $target) {
            if ($target->enabled) {
                try {
                    $target->collect($messages, $final);
                } catch (\Exception $e) {
                    $target->enabled = false;
                    $targetErrors[] = [
                        'Unable to send log via ' . get_class($target) . ': ' . ErrorHandler::convertExceptionToString($e),
                        Logger::LEVEL_WARNING,
                        __METHOD__,
                        microtime(true),
                        [],
                    ];
                }
            }
        }

        if (!empty($targetErrors)) {
            $this->dispatch($targetErrors, true);
        }
    }


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

        $count = $DB->query_single(
	        'count(*) as total',
	        'nv_comments',
	        'website = '.protect($website->id).' AND status = 3'
        );

        $ok = $DB->execute('
			DELETE FROM nv_comments
             WHERE website = '.protect($website->id).'
               AND status = 3
        ');

        if($ok)
            return $count;
    }


    public static function remove($id)
    {
        global $DB;
        global $website;

        if(empty($id))
            return 'invalid_id';

        $DB->execute('
            DELETE FROM nv_notes
                WHERE website = '.protect($website->id).'
                  AND id = '.protect($id).'
                LIMIT 1'
        );

        return 'true';
    }


    public function load_lines()
    {
        global $DB;

        $DB->query('
            SELECT *
            FROM nv_orders_lines
            WHERE `order` = '.protect($this->id).'
            ORDER BY position ASC'
        );
        $this->lines = $DB->result();
    }


    public static function find_by_reference($reference, $website_id=null)
    {
        global $DB;
        global $website;

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

        $order_id = $DB->query_single(
            'id',
            'nv_orders',
            'reference = '.protect($reference).' AND website = "'.$website_id.'"'
        );

        return $order_id;
    }


    public static function country_name_by_code($code, $language="")
    {
        global $DB;

        $lang = core_get_language($language);

        $DB->query('SELECT name
					FROM nv_countries
		 			WHERE lang = '.protect($lang).'
					  AND country_code = '.protect($code));

        $row = $DB->first();

        return $row->name;
    }


	public static function countries_regions($country_id="")
	{
		global $DB;

		// note: regions have no translation to any language right now

        $country_query = " 1=1 ";
        if(!empty($country_id))
            $country_query = ' AND r.country = '.protect($country_id);

		$DB->query('
            SELECT r.`numeric` AS region_id, c.country_code, r.name
            FROM nv_countries c, nv_countries_regions r
            WHERE c.lang = "en" AND
                  c.`numeric` = r.country AND
                  r.lang = "" AND
                  '.$country_query.'
            ORDER BY name ASC
        ');

		$rs = $DB->result();

		return $rs;
	}


                       AND lang = '.protect($lang).'
                       AND subtype IN ('.implode(",", array_map(function($k){ return protect($k);}, $subtypes)).')'
                );


	public static function object_votes_by_score($object, $object_id)
	{
		global $DB;
		global $website;

		$DB->query('
			SELECT value, COUNT(*) as votes
			  FROM nv_webuser_votes
             WHERE website = '.protect($website->id).'
			   AND object  = '.protect($object).'
               AND object_id = '.protect($object_id).'
			 GROUP BY value
			 ORDER BY value ASC
		 ');

		$data = $DB->result();

		return $data;
	}


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

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

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

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

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

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

		return true;
	}


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


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

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

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

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

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

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

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

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

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


                    $sort    = in_array(strtolower($val), array('asc', 'desc')) ? ' ' . $val : '';
                    $array[] = $this->parseKey($key, true) . $sort;
                }
            }


public function display_sdm_stats_meta_box($post) {  //Stats metabox
	$old_count = get_post_meta($post->ID, 'sdm_count_offset', true);
	$value = isset($old_count) && $old_count != '' ? $old_count : '0';

	// Get checkbox for "disable download logging"
	$no_logs = get_post_meta($post->ID, 'sdm_item_no_log', true);
	$checked = isset($no_logs) && $no_logs === 'on' ? 'checked="checked"' : '';

	_e('These are the statistics for this download item.', 'simple-download-monitor');
	echo '

';

	global $wpdb;
	$wpdb->get_results($wpdb->prepare('SELECT * FROM ' . $wpdb->prefix . 'sdm_downloads WHERE post_id=%s', $post->ID));

	echo '
';
	_e('Number of Downloads:', 'simple-download-monitor');
	echo ' ' . $wpdb->num_rows . '';
	echo '
';

	echo '
';
	_e('Offset Count: ', 'simple-download-monitor');
	echo '
';
	echo ' <input type="text" size="10" name="sdm_count_offset" value="' . $value . '" />';
	echo '
' . __('Enter any positive or negative numerical value; to offset the download count shown to the visitors (when using the download counter shortcode).', 'simple-download-monitor') . '
';
	echo '
';

	echo '
';
	echo '
';
	echo '<input type="checkbox" name="sdm_item_no_log" ' . $checked . ' />';
	echo '';
	_e('Disable download logging for this item.', 'simple-download-monitor');
	echo '
';

	wp_nonce_field('sdm_count_offset_nonce', 'sdm_count_offset_nonce_check');
    }


function init_args()
{
	$_REQUEST=strings_stripSlashes($_REQUEST);

	$args = new stdClass();
	$args->req_spec_id = isset($_REQUEST['req_spec_id']) ? $_REQUEST['req_spec_id'] : 0;
	$args->doCompare = isset($_REQUEST['doCompare']) ? true : false;
	$args->left_item_id = isset($_REQUEST['left_item_id']) ? intval($_REQUEST['left_item_id']) : -1;
	$args->right_item_id = isset($_REQUEST['right_item_id']) ? intval($_REQUEST['right_item_id']) :  -1;
	$args->tproject_id = isset($_SESSION['testprojectID']) ? $_SESSION['testprojectID'] : 0;
	$args->useDaisyDiff = (isset($_REQUEST['diff_method']) && ($_REQUEST['diff_method'] == 'htmlCompare')) ? 1 : 0;

	$diffEngineCfg = config_get("diffEngine");
	$args->context = null;
	if( !isset($_REQUEST['context_show_all']))
	{
		$args->context = (isset($_REQUEST['context']) && is_numeric($_REQUEST['context'])) ? $_REQUEST['context'] : $diffEngineCfg->context;
	}

	return $args;
}


function init_args() {

	$args = new stdClass();

	$_REQUEST = strings_stripSlashes($_REQUEST);

	$args->build_id = isset($_REQUEST['build_id']) ? $_REQUEST['build_id'] : 0;
	$args->confirmed = isset($_REQUEST['confirmed']) && $_REQUEST['confirmed'] == 'yes' ? true : false;

	$args->user_id = $_SESSION['userID'];
	$args->testproject_id = $_SESSION['testprojectID'];
	$args->testproject_name = $_SESSION['testprojectName'];

	$args->refreshTree = isset($_SESSION['setting_refresh_tree_on_action']) ?
	                     $_SESSION['setting_refresh_tree_on_action'] : false;

	return $args;
}


    public function getRawRevisionsAndCount($limit, PFUser $author)
    {
        return svn_get_revisions(
            $this->project,
            0,
            $limit,
            '',
            $author->getUserName(),
            '',
            '',
            0,
            false
        );
    }


    public function getQueryGroupby()
    {
        return '';
    }


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


$parent   = $dIF->getItemFromDb($item->getParentId());
                $content .= '
';
                $content .= '' . 'getId() . '">' . $item->getTitle() . '	';
                $content .= '';
                if ($parent === null || $dIF->isRoot($parent)) {
                    $content .= '	';
                } else {
                    $content .=  'defaultUrl . '&action=show&id=' . $parent->getId() . '">' . $parent->getTitle() . '	';
                }
                $content .= '' . $hp->purify($uH->getDisplayNameFromUserId($row['user_id'])) . '	';
                $content .= '' . format_date($GLOBALS['Language']->getText('system', 'datefmt'), $row['lock_date']) . '	';
                $content .= '
';
            }
        }


public function column_description( $item ) {
		$return = $item->object_name;

		switch ( $item->object_type ) {
			case 'Post' :
				$return = sprintf( '%s', get_edit_post_link( $item->object_id ), $item->object_name );
				break;

			case 'Taxonomy' :
				if ( ! empty( $item->object_id ) )
					$return = sprintf( '%s', get_edit_term_link( $item->object_id, $item->object_subtype ), $item->object_name );
				break;

			case 'Comments' :
				if ( ! empty( $item->object_id ) && $comment = get_comment( $item->object_id ) ) {
					$return = sprintf( '%s #%d', get_edit_comment_link( $item->object_id ), $item->object_name, $item->object_id );
				}
				break;

			case 'Export' :
				if ( 'all' === $item->object_name ) {
					$return = __( 'All', 'aryo-activity-log' );
				} else {
					$pt     = get_post_type_object( $item->object_name );
					$return = ! empty( $pt->label ) ? $pt->label : $item->object_name;
				}
				break;

			case 'Options' :
			case 'Core' :
				$return = __( $item->object_name, 'aryo-activity-log' );
				break;
		}

		$return = apply_filters( 'aal_table_list_column_description', $return, $item );

		return $return;
	}


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


                    $files[$i] = '.' . DIRECTORY_SEPARATOR . basename($file);
                }
                $files = array_map('escapeshellarg', $files);

                $cmd = $arc['cmd'] . ' ' . $arc['argc'] . ' ' . escapeshellarg($name) . ' ' . implode(' ', $files);
                $err_out = '';
                $this->procExec($cmd, $o, $c, $err_out, $dir);
                chdir($cwd);
            } else {
                return false;
            }
        }
        $path = $dir . DIRECTORY_SEPARATOR . $name;
        return file_exists($path) ? $path : false;
    }


    protected function remove($path, $force = false)
    {
        $stat = $this->stat($path);

        if (empty($stat)) {
            return $this->setError(elFinder::ERROR_RM, $path, elFinder::ERROR_FILE_NOT_FOUND);
        }

        $stat['realpath'] = $path;
        $this->rmTmb($stat);
        $this->clearcache();

        if (!$force && !empty($stat['locked'])) {
            return $this->setError(elFinder::ERROR_LOCKED, $this->path($stat['hash']));
        }

        if ($stat['mime'] == 'directory' && empty($stat['thash'])) {
            $ret = $this->delTree($this->convEncIn($path));
            $this->convEncOut();
            if (!$ret) {
                return $this->setError(elFinder::ERROR_RM, $this->path($stat['hash']));
            }
        } else {
            if ($this->convEncOut(!$this->_unlink($this->convEncIn($path)))) {
                return $this->setError(elFinder::ERROR_RM, $this->path($stat['hash']));
            }
            $this->clearstatcache();
        }

        $this->removed[] = $stat;
        return true;
    }


    protected function _copy($source, $targetDir, $name)
    {
        $res = false;

        $target = $this->_joinPath($targetDir, $name);
        if ($this->tmp) {
            $local = $this->getTempFile();

            if ($this->connect->get($source, $local)
                && $this->connect->put($target, $local, NET_SFTP_LOCAL_FILE)) {
                $res = true;
            }
            unlink($local);
        } else {
            //not memory efficient
            $res = $this->_filePutContents($target, $this->_getContents($source));
        }

        return $res;
    }


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

        return false;
 */
    }


    protected function _save($fp, $dir, $name, $stat)
    {
        //TODO optionally encrypt $fp before uploading if mime is not already encrypted type
        $path = $this->_joinPath($dir, $name);
        return $this->connect->put($path, $fp)
            ? $path
            : false;
    }


   function prepareInputForAdd($input) {

      if (isset($input["passwd"])) {
         if (empty($input["passwd"])) {
            unset($input["passwd"]);
         } else {
            $input["passwd"] = Toolbox::encrypt(stripslashes($input["passwd"]), GLPIKEY);
         }
      }

      if (isset($input['mail_server']) && !empty($input['mail_server'])) {
         $input["host"] = Toolbox::constructMailServerConfig($input);
      }

      if (!NotificationMailing::isUserAddressValid($input['name'])) {
         Session::addMessageAfterRedirect(__('Invalid email address'), false, ERROR);
      }

      return $input;
   }


    public function boot()
    {
        // Configure the debugbar
        Config::set('debugbar', Config::get('rainlab.debugbar::config'));

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

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

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

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

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


    public function redirect($route, $code = null)
    {
        /** @var Uri $uri */
        $uri = $this['uri'];

        //Check for code in route
        $regex = '/.*(\[(30[1-7])\])$/';
        preg_match($regex, $route, $matches);
        if ($matches) {
            $route = str_replace($matches[1], '', $matches[0]);
            $code = $matches[2];
        }

        if ($code === null) {
            $code = $this['config']->get('system.pages.redirect_default_code', 302);
        }

        if (isset($this['session'])) {
            $this['session']->close();
        }

        if ($uri->isExternal($route)) {
            $url = $route;
        } else {
            $url = rtrim($uri->rootUrl(), '/') . '/';

            if ($this['config']->get('system.pages.redirect_trailing_slash', true)) {
                $url .= trim($route, '/'); // Remove trailing slash
            } else {
                $url .= ltrim($route, '/'); // Support trailing slash default routes
            }
        }

        header("Location: {$url}", true, $code);
        exit();
    }


$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('manufacturers.php', 'page=' . $_GET['page'] . '&mID=' . (int)$mInfo->manufacturers_id), null, null, 'btn-light')];


$contents = ['form' => tep_draw_form('reviews', 'reviews.php', 'page=' . $_GET['page'] . '&rID=' . $rInfo->reviews_id . '&action=deleteconfirm')];


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


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


	public function admin_log($mode = '')
	{
		$errorLogPath = TMP . 'logs' . DS . 'error.log';
		switch($mode) {
			case 'download':
				set_time_limit(0);
				if ($this->_downloadErrorLog()) {
					exit();
				}
				$this->BcMessage->setInfo('エラーログが存在しません。');
				$this->redirect(['action' => 'log']);
				break;
			case 'delete':
				$this->_checkSubmitToken();
				if (file_exists($errorLogPath)) {
					if (unlink($errorLogPath)) {
						$messages[] = __d('baser', 'エラーログを削除しました。');
						$error = false;
					} else {
						$messages[] = __d('baser', 'エラーログが削除できませんでした。');
						$error = true;
					}
				} else {
					$messages[] = __d('baser', 'エラーログが存在しません。');
					$error = false;
				}

				if ($messages) {
					$this->BcMessage->set(implode("\n", $messages), $error);
				}
				$this->redirect(['action' => 'log']);
				break;

		}

		$fileSize = 0;
		if (file_exists($errorLogPath)) {
			$fileSize = filesize($errorLogPath);
		}

		$this->pageTitle = __d('baser', 'データメンテナンス');
		$this->help = 'tools_log';
		$this->set('fileSize', $fileSize);
	}


	public function admin_write_schema()
	{
		$path = TMP . 'schemas' . DS;

		/* 表示設定 */
		$this->pageTitle = __d('baser', 'スキーマファイル生成');
		$this->help = 'tools_write_schema';

		if (!$this->request->data) {
			$this->request->data['Tool']['connection'] = 'core';
			return;
		}

		if (empty($this->request->data['Tool'])) {
			$this->BcMessage->setError(__d('baser', 'テーブルを選択してください。'));
			return;
		}

		if (!$this->_resetTmpSchemaFolder()) {
			$this->BcMessage->setError('フォルダ：' . $path . ' が存在するか確認し、存在する場合は、削除するか書込権限を与えてください。');
			$this->redirect(['action' => 'write_schema']);
		}
		if (!$this->Tool->writeSchema($this->request->data, $path)) {
			$this->BcMessage->setError(__d('baser', 'スキーマファイルの生成に失敗しました。'));
			return;
		}

		$Simplezip = new Simplezip();
		$Simplezip->addFolder($path);
		$Simplezip->download('schemas');
		exit();
	}


    protected function redirectToOperator(Thread $thread, $operator_id)
    {
        if ($thread->state != Thread::STATE_CHATTING) {
            // We can redirect only threads which are in proggress now.
            return false;
        }

        // Redirect the thread
        $thread->state = Thread::STATE_WAITING;
        $thread->nextAgent = $operator_id;
        $thread->agentId = 0;

        // Check if the target operator belongs to the current thread's group.
        // If not reset the current thread's group.
        if ($thread->groupId != 0) {
            $db = Database::getInstance();
            list($groups_count) = $db->query(
                ("SELECT count(*) AS count "
                    . "FROM {operatortoopgroup} "
                    . "WHERE operatorid = ? AND groupid = ?"),
                array($operator_id, $thread->groupId),
                array(
                    'return_rows' => Database::RETURN_ONE_ROW,
                    'fetch_type' => Database::FETCH_NUM,
                )
            );
            if ($groups_count === 0) {
                $thread->groupId = 0;
            }
        }

        $thread->save();

        // Send notification message
        $thread->postMessage(
            Thread::KIND_EVENTS,
            getlocal(
                'Operator {0} redirected you to another operator. Please wait a while.',
                array(get_operator_name($this->getOperator())),
                $thread->locale,
                true
            )
        );

        return true;
    }


    public function rename(){

        if($this->request->isMethod('POST')){

            if(\Storage::move($this->request->input('old_file'), $this->request->input('new_file'))){
                if($this->request->ajax()){
                    return response()->json(['success' => trans('File successfully renamed!')]);
                }
            }else{
                if($this->request->ajax()){
                    return response()->json(['danger' => trans('message.something_went_wrong')]);
                }
            }

        }

    }


    public static function loadFrom(Db $zdb, $id, $mailing, $new = true)
    {
        try {
            $select = $zdb->select(self::TABLE);
            $select->where('mailing_id = ' . $id);

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

            return $mailing->loadFromHistory($result, $new);
        } catch (Throwable $e) {
            Analog::log(
                'Unable to load mailing model #' . $id . ' | ' .
                $e->getMessage(),
                Analog::WARNING
            );
            throw $e;
        }
    }


    public static function loadFieldType(Db $zdb, $id)
    {
        try {
            $select = $zdb->select(self::TABLE);
            $select->where('field_id = ' . $id);

            $results = $zdb->execute($select);
            $result = $results->current();
            if ($result) {
                $field_type = $result->field_type;
                $field_type = self::getFieldType($zdb, $field_type);
                $field_type->loadFromRs($result);
                return $field_type;
            }
        } catch (Throwable $e) {
            Analog::log(
                __METHOD__ . ' | Unable to retrieve field `' . $id .
                '` information | ' . $e->getMessage(),
                Analog::ERROR
            );
            return false;
        }
        return false;
    }


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

            $results = $this->zdb->execute($select);
            if ($results->count() > 0) {
                $result = $results->current();
                $this->loadFromRS($result);

                return true;
            } else {
                Analog::log(
                    'Unknown ID ' . $id,
                    Analog::ERROR
                );
                return false;
            }
        } catch (Throwable $e) {
            Analog::log(
                'Cannot load ' . $this->getType() . ' from id `' . $id . '` | ' .
                $e->getMessage(),
                Analog::WARNING
            );
            throw $e;
        }
    }


    public function delete($id)
    {
        $ret = $this->get($id);
        if (!$ret) {
            /* get() already logged */
            return self::ID_NOT_EXITS;
        }

        if ($this->isUsed($id)) {
            $this->errors[] = _T("Cannot delete this label: it's still used");
            return false;
        }

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

            $this->zdb->execute($delete);
            $this->deleteTranslation($ret->{$this->flabel});

            Analog::log(
                $this->getType() . ' ' . $id . ' deleted successfully.',
                Analog::INFO
            );

            $this->zdb->connection->commit();
            return true;
        } catch (Throwable $e) {
            $this->zdb->connection->rollBack();
            Analog::log(
                'Unable to delete ' . $this->getType() . ' ' . $id .
                ' | ' . $e->getMessage(),
                Analog::ERROR
            );
            throw $e;
        }
    }


                        $subgroup->remove(true);
                    }
                }

                Analog::log(
                    'Cascading remove ' . $this->group_name .
                    '. Members and managers will be detached.',
                    Analog::INFO
                );

                //delete members
                $delete = $zdb->delete(self::GROUPSUSERS_TABLE);
                $delete->where(
                    self::PK . ' = ' . $this->id
                );
                $zdb->execute($delete);

                //delete managers
                $delete = $zdb->delete(self::GROUPSMANAGERS_TABLE);
                $delete->where(
                    self::PK . ' = ' . $this->id
                );
                $zdb->execute($delete);
            }

            //delete group itself
            $delete = $zdb->delete(self::TABLE);
            $delete->where(
                self::PK . ' = ' . $this->id
            );
            $zdb->execute($delete);

            //commit all changes
            if ($transaction) {
                $zdb->connection->commit();
            }

            return true;
        } catch (Throwable $e) {
            if ($transaction) {
                $zdb->connection->rollBack();
            }
            if ($e->getCode() == 23000) {
                Analog::log(
                    str_replace(
                        '%group',
                        $this->group_name,
                        'Group "%group" still have members!'
                    ),
                    Analog::WARNING
                );
                $this->isempty = false;
            } else {
                Analog::log(
                    'Unable to delete group ' . $this->group_name .
                    ' (' . $this->id . ') |' . $e->getMessage(),
                    Analog::ERROR
                );
                throw $e;
            }
            return false;
        }
    }


						unset($return[$key]);
				}
			}
			break;
	}
	return @array_change_key_case($return, CASE_UPPER);
}


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


function DateInputAY($value, $name, $counter = 1, $placeholder = _enterDate)
{

    $show = "";
    $date_sep = "";
    $monthVal = "";
    $yearVal = "";
    $dayVal = "";
    $display = "";

    if ($value != '')
        return '

' . ProperDateAY($value) . '
	<input type=text id="date_' . $counter . '" ' . $show . '  style="display:none" readonly>		<input type=hidden ' . $monthVal . ' id="monthSelect' . $counter . '" name="month_' . $name . '" ><input type=hidden ' . $dayVal . '  id="daySelect' . $counter . '"   name="day_' . $name . '"><input type=hidden ' . $yearVal . '  id="yearSelect' . $counter . '" name="year_' . $name . '" >

';
    else {
        if ($counter == 2)
            return '<input type="text" id="date_' . $counter . '"  data-placeholder="' . $placeholder . '" class="form-control daterange-single"><input type=hidden ' . $monthVal . ' id="monthSelect' . $counter . '" name="month_' . $name . '" /><input type=hidden ' . $dayVal . '  id="daySelect' . $counter . '"   name="day_' . $name . '" /><input type=hidden ' . $yearVal . '  id="yearSelect' . $counter . '" name="year_' . $name . '" />';
        else
            return '<input type="text" id="date_' . $counter . '"  data-placeholder="' . $placeholder . '" class="form-control daterange-single"><input type=hidden ' . $monthVal . ' id="monthSelect' . $counter . '" name="month_' . $name . '" /><input type=hidden ' . $dayVal . '  id="daySelect' . $counter . '"   name="day_' . $name . '"><input type=hidden ' . $yearVal . '  id="yearSelect' . $counter . '" name="year_' . $name . '" />';
    }
}


function db_case($array)
{
    global $DatabaseType;

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

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

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

            $counter++;
        }
    }

    return $string;
}


function singleQuoteReplace($param1 = false, $param2 = false, $param3)
{
    return str_replace("'", "''", str_replace("\'", "'", $param3));
}


        $percent = round($percent, 0);
    } else {
        $percent = round($percent, 2); // school default
    }
    if ($ret == '%')
        return $percent;

    if (!$_openSIS['_makeLetterGrade']['grades'][$grade_scale_id])
        $_openSIS['_makeLetterGrade']['grades'][$grade_scale_id] = DBGet(DBQuery('SELECT TITLE,ID,BREAK_OFF FROM report_card_grades WHERE SYEAR=\'' . $cp[1]['SYEAR'] . '\' AND SCHOOL_ID=\'' . $cp[1]['SCHOOL_ID'] . '\' AND GRADE_SCALE_ID=\'' . $grade_scale_id . '\' ORDER BY BREAK_OFF IS NOT NULL DESC,BREAK_OFF DESC,SORT_ORDER'));

    foreach ($_openSIS['_makeLetterGrade']['grades'][$grade_scale_id] as $grade) {
        if ($does_breakoff == 'Y' ? $percent >= $programconfig[$staff_id][$course_period_id . '-' . $grade['ID']] && is_numeric($programconfig[$staff_id][$course_period_id . '-' . $grade['ID']]) : $percent >= $grade['BREAK_OFF'])
            return $ret == 'ID' ? $grade['ID'] : $grade['TITLE'];
    }
}


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

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

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


function db_seq_nextval($seqname)
{
    global $DatabaseType;

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

    return $seq;
}


                        echo '<LANGUAGE>' . htmlentities($value_arr['LANGUAGE']) . '</LANGUAGE>';
                        foreach ($value_arr['ENROLLMENT_INFO'] as $eid => $ed) {
                            echo '<ENROLLMENT_INFO_' . htmlentities($eid) . '>';
                            echo '<SCHOOL_ID>' . htmlentities($ed['SCHOOL_ID']) . '</SCHOOL_ID>';
                            echo '<CALENDAR>' . htmlentities($ed['CALENDAR']) . '</CALENDAR>';
                            echo '<GRADE>' . htmlentities($ed['GRADE']) . '</GRADE>';
                            echo '<SECTION>' . htmlentities($ed['SECTION']) . '</SECTION>';
                            echo '<START_DATE>' . htmlentities($ed['START_DATE']) . '</START_DATE>';
                            echo '<DROP_DATE>' . htmlentities($ed['DROP_DATE']) . '</DROP_DATE>';
                            echo '<ENROLLMENT_CODE>' . htmlentities($ed['ENROLLMENT_CODE']) . '</ENROLLMENT_CODE>';
                            echo '<DROP_CODE>' . htmlentities($ed['DROP_CODE']) . '</DROP_CODE>';
                            echo '</ENROLLMENT_INFO_' . htmlentities($eid) . '>';
                        }
                        echo '</STUDENT>';
                    }
                    echo '</SCHOOL>';
                }


        foreach($course_RET as $period_day)
        {
            $period_days_append_sql .="(sp.start_time<='$period_day[END_TIME]' AND '$period_day[START_TIME]'<=sp.end_time AND DAYS LIKE '%$period_day[DAYS]%') OR ";
        }


function _makeMpName($value) {
    if ($value != '') {
        $get_name = DBGet(DBQuery('SELECT TITLE FROM marking_periods WHERE marking_period_id=' . $value));
        return $get_name[1]['TITLE'];
    } else
        return ''._customCoursePeriod.'';
}


                foreach ($value as $i => $j) {

                    $column_check = explode('_', $i);
                    if ($column_check[0] == 'CUSTOM') {
                        $check_validity = DBGet(DBQuery('SELECT COUNT(*) as REC_EX FROM school_custom_fields WHERE ID=' . $column_check[1] . ' AND (SCHOOL_ID=' . $get_school_info[$key]['ID'].' OR SCHOOL_ID=0)'));
                        if ($check_validity[1]['REC_EX'] == 0)
                            $j = 'NOT_AVAILABLE_FOR';
                    }
                    $get_school_info[$key][$i] = trim($j);
                }


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


    public function pageToContainedHtml(Page $page)
    {
        $page->html = (new PageContent($page))->render();
        $pageHtml = view('pages.export', [
            'page'   => $page,
            'format' => 'html',
        ])->render();

        return $this->containHtml($pageHtml);
    }


    protected function configure()
    {
        $this
            ->setName('kimai:version')
            ->setDescription('Receive version information')
            ->setHelp('This command allows you to fetch various version information about Kimai.')
            ->addOption('name', null, InputOption::VALUE_NONE, 'Display the major release name')
            ->addOption('candidate', null, InputOption::VALUE_NONE, 'Display the current version candidate (e.g. "stable" or "dev")')
            ->addOption('short', null, InputOption::VALUE_NONE, 'Display the version only')
            ->addOption('semver', null, InputOption::VALUE_NONE, 'Semantical versioning (SEMVER) compatible version string')
        ;
    }


    public function testBuild()
    {
        $version = Constants::VERSION;
        $versionParts = explode('.', $version);
        $major = (int) $versionParts[0];
        $minor = (int) $versionParts[1];
        $patch = isset($versionParts[2]) ? (int) $versionParts[2] : 0;

        $expectedId = $major * 10000 + $minor * 100 + $patch;

        self::assertEquals('1.14', Constants::VERSION, 'Invalid release number');
        self::assertTrue(\in_array(Constants::STATUS, ['dev', 'stable']), 'Invalid status');
        self::assertEquals($expectedId, Constants::VERSION_ID, 'Invalid version ID');
    }


    public function uploadCompanyLogo(Request $request)
    {
        $company = Company::find($request->header('company'));

        $this->authorize('manage company', $company);

        $data = json_decode($request->company_logo);

        if ($data) {
            $company = Company::find($request->header('company'));

            if ($company) {
                $company->clearMediaCollection('logo');

                $company->addMediaFromBase64($data->data)
                    ->usingFileName($data->name)
                    ->toMediaCollection('logo');
            }
        }

        return response()->json([
            'success' => true,
        ]);
    }


list($h, $m) = explode('.', $row['RunAt']);

			$main .= '
';
			$main .= '
' . $row['Title'] . '
';

			if(!empty($systems_for_schedule))
			{
				if($row['RunAt'] > date('H.i'))
				{
					$run_in_future = true;
					$main .= '
Runs In ' . pts_strings::format_time((($h * 60) + $m) - ((date('H') * 60) + date('i')), 'MINUTES') . '
';
				}
				else
				{
					$run_in_future = false;
					$main .= '
Triggered ' . pts_strings::format_time(max(1, (date('H') * 60) + date('i') - (($h * 60) + $m)), 'MINUTES') . ' Ago
';
				}
			}

			foreach($systems_for_schedule as $system_id)
			{
				$pprid = self::result_match($row['ScheduleID'], $system_id, date('Y-m-d'));

				if($pprid)
					$main .= '';

				$main .= phoromatic_server::system_id_to_name($system_id);

				if($pprid)
					$main .= '';
				else if(!$run_in_future)
				{
					$sys_info = self::system_info($system_id);
					$last_comm_diff = time() - strtotime($sys_info['LastCommunication']);

					$main .= ' ';
					if($last_comm_diff > 3600)
					{
						$main .= 'Last Communication: ' . pts_strings::format_time($last_comm_diff, 'SECONDS', true, 60) . ' Ago';
					}
					else
					{
						$main .= $sys_info['CurrentTask'];
					}
					$main .= '';
				}
				$main .= '
';
			}

			$main .= '
';
		}
		$main .= '
';

		$main .= '
';

		echo '
' . $main . '
';
		//echo phoromatic_webui_main($main, phoromatic_webui_right_panel_logged_in());
		echo phoromatic_webui_footer();
	}


function phoromatic_account_id_to_group_name($account_id)
{
	// XXX deprecated
	return phoromatic_server::account_id_to_group_name($account_id);
}


	public function testDolEval()
	{
		global $conf,$user,$langs,$db;
		$conf=$this->savconf;
		$user=$this->savuser;
		$langs=$this->savlangs;
		$db=$this->savdb;

		$result=dol_eval('1==1', 1, 0);
		print "result = ".$result."\n";
		$this->assertTrue($result);

		$result=dol_eval('1==2', 1, 0);
		print "result = ".$result."\n";
		$this->assertFalse($result);

		include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
		include_once DOL_DOCUMENT_ROOT.'/projet/class/task.class.php';
		$result=dol_eval('(($reloadedobj = new Task($db)) && ($reloadedobj->fetchNoCompute($object->id) > 0) && ($secondloadedobj = new Project($db)) && ($secondloadedobj->fetchNoCompute($reloadedobj->fk_project) > 0)) ? $secondloadedobj->ref: "Parent project not found"', 1, 1);
		print "result = ".$result."\n";
		$this->assertEquals('Parent project not found', $result);

		$result=dol_eval('$a=function() { }; $a;', 1, 1);
		print "result = ".$result."\n";
		$this->assertContains('Bad string syntax to evaluate', $result);

		$result=dol_eval('$a=exec("ls");', 1, 1);
		print "result = ".$result."\n";
		$this->assertContains('Bad string syntax to evaluate', $result);

		$result=dol_eval('$a=exec ("ls")', 1, 1);
		print "result = ".$result."\n";
		$this->assertContains('Bad string syntax to evaluate', $result);

		$result=dol_eval('$a="test"; $$a;', 1, 0);
		print "result = ".$result."\n";
		$this->assertContains('Bad string syntax to evaluate', $result);

		$result=dol_eval('`ls`', 1, 0);
		print "result = ".$result."\n";
		$this->assertContains('Bad string syntax to evaluate', $result);
	}


    private function section($nodes, $id, $filters, $start, $end, $otag, $ctag, $level)
    {
        $source   = var_export(substr($this->source, $start, $end - $start), true);
        $callable = $this->getCallable();

        if ($otag !== '{{' || $ctag !== '}}') {
            $delimTag = var_export(sprintf('{{= %s %s =}}', $otag, $ctag), true);
            $helper = sprintf('$this->lambdaHelper->withDelimiters(%s)', $delimTag);
            $delims = ', ' . $delimTag;
        } else {
            $helper = '$this->lambdaHelper';
            $delims = '';
        }

        $key = ucfirst(md5($delims . "\n" . $source));

        if (!isset($this->sections[$key])) {
            $this->sections[$key] = sprintf($this->prepare(self::SECTION), $key, $callable, $source, $helper, $delims, $this->walk($nodes, 2));
        }

        $method  = $this->getFindMethod($id);
        $id      = var_export($id, true);
        $filters = $this->getFilters($filters, $level);

        return sprintf($this->prepare(self::SECTION_CALL, $level), $id, $method, $id, $filters, $key);
    }


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


    public function tableCleanup(int $maxInactiveMinutes = 30)
    {
        $now = new \DateTime();
        $minutesBack = new \DateInterval('PT' . $maxInactiveMinutes . 'M');
        $timestamp = $now->sub($minutesBack)->format('Y-m-d H:i:s');

        $sql = 'DELETE FROM '.TBL_SESSIONS.'
                 WHERE ses_timestamp < ? -- $timestamp
                   AND ses_session_id <> ? -- $this->getValue(\'ses_session_id\')';
        $this->db->queryPrepared($sql, array($timestamp, $this->getValue('ses_session_id')));
    }


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


	public function updateTab($id, $array)
	{
		if (!$id || $id == '') {
			$this->setAPIResponse('error', 'id was not set', 422);
			return null;
		}
		if (!$array) {
			$this->setAPIResponse('error', 'no data was sent', 422);
			return null;
		}
		$tabInfo = $this->getTabById($id);
		if ($tabInfo) {
			$array = $this->checkKeys($tabInfo, $array);
		} else {
			$this->setAPIResponse('error', 'No tab info found', 404);
			return false;
		}
		if (array_key_exists('name', $array)) {
			$array['name'] = htmlspecialchars($array['name']);
			if ($this->isTabNameTaken($array['name'], $id)) {
				$this->setAPIResponse('error', 'Tab name: ' . $array['name'] . ' is already taken', 409);
				return false;
			}
		}
		if (array_key_exists('default', $array)) {
			if ($array['default']) {
				$this->clearTabDefault();
			}
		}
		$response = [
			array(
				'function' => 'query',
				'query' => array(
					'UPDATE tabs SET',
					$array,
					'WHERE id = ?',
					$id
				)
			),
		];
		$this->setAPIResponse(null, 'Tab info updated');
		$this->setLoggerChannel('Tab Management');
		$this->logger->debug('Edited Tab Info for [' . $tabInfo['name'] . ']');
		return $this->processQueries($response);
	}


function URLEscape( $string )
{
	$string = preg_replace_callback(
		// Match both decimal & hex code (although hex codes can contain a-f letters).
		// Should be enough as the alphabet hex codes only have numbers.
		"/(&#x?[0-9]+;?)/i",
		function( $match ) {
			if ( mb_substr( $match[1], -1 ) !== ';' )
			{
				// Fix stored XSS security issue: add semicolon to HTML entity so it can be decoded.
				// @link https://www.php.net/manual/en/function.html-entity-decode.php#104617
				$match[1] .= ';';
			}

			return $match[1];
		},
		$string
	);

	// Fix stored XSS security issue: decode HTML entities from URL.
	$string = html_entity_decode( (string) $string );

	$remove = [
		// Fix stored XSS security issue: remove inline JS from URL.
		'javascript:',
	];

	foreach ( $remove as $remove_string )
	{
		while ( strpos( $string, $remove_string ) !== false )
		{
			$string = str_ireplace( $remove, '', $string );
		}
	}

	$entities = [
		'%21',
		'%2A',
		'%27',
		'%28',
		'%29',
		'%3B',
		'%3A',
		'%40',
		'%26',
		'%3D',
		'%2B',
		'%24',
		'%2C',
		'%2F',
		'%3F',
		'%25',
		'%23',
		'%5B',
		'%5D',
	];

	$replacements = [
		'!',
		'*',
		"'",
		'(',
		')',
		';',
		':',
		'@',
		'&',
		'=',
		'+',
		'$',
		',',
		'/',
		'?',
		'%',
		'#',
		'[',
		']',
	];

	return str_replace(
		$entities,
		$replacements,
		rawurlencode( $string )
	);
}


    public function store(CreateAppointmentCalendarRequest $request)
    {

        $client_id = null;
        $user = User::where('external_id', $request->user)->first();

        if ($request->client_external_id) {
            $client_id = Client::where('external_id', $request->client_external_id)->first()->id;
            if (!$client_id) {
                return response(__("Client not found"), 422);
            }
        }

        $request_type = null;
        $request_id = null;
        if ($request->source_type && $request->source_external_id) {
            $request_type = $request->source_type;

            $entry = $request_type::whereExternalId($request->source_external_id);
            $request_id = $entry->id;
        }

        if (!$user) {
            return response(__("User not found"), 422);
        }

        $startTime = str_replace(["am", "pm", ' '], "", $request->start_time) . ':00';
        $endTime = str_replace(["am", "pm", ' '], "", $request->end_time) . ':00';

        $appointment = Appointment::create([
            'external_id' => Uuid::uuid4()->toString(),
            'source_type' => $request_type,
            'source_id' => $request_id,
            'client_id' => $client_id,
            'title' => $request->title,
            'start_at' => Carbon::parse($request->start_date . " " . $startTime),
            'end_at' => Carbon::parse($request->end_date . " " . $endTime),
            'user_id' => $user->id,
            'color' => $request->color
        ]);
        $appointment->user_external_id = $user->external_id;
        $appointment->start_at = $appointment->start_at;

        return response($appointment);
    }


public function anyData()
    {
        $tasks = Task::with(['user', 'status', 'client'])->select(
            collect(['external_id', 'title', 'created_at', 'deadline', 'user_assigned_id', 'status_id', 'client_id'])
                ->map(function ($field) {
                    return (new Task())->qualifyColumn($field);
                })
                ->all()
        );

        return Datatables::of($tasks)
            ->addColumn('titlelink', '{{$title}}')
            ->editColumn('client', function ($projects) {
                return $projects->client->company_name;
            })
            ->editColumn('created_at', function ($tasks) {
                return $tasks->created_at ? with(new Carbon($tasks->created_at))
                    ->format(carbonDate()) : '';
            })
            ->editColumn('deadline', function ($tasks) {
                return $tasks->created_at ? with(new Carbon($tasks->deadline))
                    ->format(carbonDate()) : '';
            })
            ->editColumn('user_assigned_id', function ($tasks) {
                return $tasks->user->name;
            })
            ->editColumn('status_id', function ($tasks) {
                return 'status->color . '"> ' .
                    $tasks->status->title . '';
            })
            ->addColumn('view', function ($tasks) {
                return 'external_id) . '" class="btn btn-link">' . __('View') .''
                . 'external_id) . '" data-title="'. $tasks->title . '" data-target="#deletion" class="btn btn-link">' . __('Delete') .''
                ;
            })
            ->rawColumns(['titlelink','view', 'status_id'])
            ->make(true);
    }


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


function updateBasicSettings(PDFStructure &$structure) {
	// set headline
	if (isset($_POST['headline'])) {
		$structure->setTitle(str_replace('<', '', str_replace('>', '', $_POST['headline'])));
	}
	// set logo
	if (isset($_POST['logoFile'])) {
		$structure->setLogo($_POST['logoFile']);
	}
	// set folding marks
	if (isset($_POST['foldingmarks'])) {
		$structure->setFoldingMarks($_POST['foldingmarks']);
	}
}


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


html: function (token, attrs, content) {
			var size = $.inArray(attrs.defaultattr, mybbCmd.fsStr) + 1;
			if (!isNaN(attrs.defaultattr)) {
				size = attrs.defaultattr;
				if (size > 7)
					size = 7;
				if (size < 1)
					size = 1;
			}
			if (size < 0) {
				size = 0;
			}
			return '' + content + '';
		}


        function ComponentRawSourceDialogController(scope, $mdDialog) {
          scope.close = function() {
            $mdDialog.hide();
          };
        }


  var url2FilePath = function(url){
    var subPath = url.substr("/tests/frontend".length);
    if (subPath == ""){
      subPath = "index.html"
    }
    subPath = subPath.split("?")[0];

    var filePath = path.normalize(npm.root + "/../tests/frontend/")
    filePath += subPath.replace("..", "");
    return filePath;
  }


  Tooltip.prototype.hide = function (callback) {
    var that = this
    var $tip = $(this.$tip)
    var e    = $.Event('hide.bs.' + this.type)

    function complete() {
      if (that.hoverState != 'in') $tip.detach()
      that.$element
        .removeAttr('aria-describedby')
        .trigger('hidden.bs.' + that.type)
      callback && callback()
    }

    this.$element.trigger(e)

    if (e.isDefaultPrevented()) return

    $tip.removeClass('in')

    $.support.transition && $tip.hasClass('fade') ?
      $tip
        .one('bsTransitionEnd', complete)
        .emulateTransitionEnd(Tooltip.TRANSITION_DURATION) :
      complete()

    this.hoverState = null

    return this
  }


	_removeCurrentsFromItems: function() {

		var list = this.currentItem.find(":data(" + this.widgetName + "-item)");

		this.items = $.grep(this.items, function (item) {
			for (var j=0; j < list.length; j++) {
				if(list[j] === item.item[0]) {
					return false;
				}
			}
			return true;
		});

	},


				update: function(container, p) {

					// 1. If a className is set as 'placeholder option, we don't force sizes - the class is responsible for that
					// 2. The option 'forcePlaceholderSize can be enabled to force it even if a class name is specified
					if(className && !o.forcePlaceholderSize) {
						return;
					}

					//If the element doesn't have a actual height by itself (without styles coming from a stylesheet), it receives the inline height from the dragged item
					if(!p.height()) { p.height(that.currentItem.innerHeight() - parseInt(that.currentItem.css("paddingTop")||0, 10) - parseInt(that.currentItem.css("paddingBottom")||0, 10)); }
					if(!p.width()) { p.width(that.currentItem.innerWidth() - parseInt(that.currentItem.css("paddingLeft")||0, 10) - parseInt(that.currentItem.css("paddingRight")||0, 10)); }
				}


function hd(a,b,c,d){var e={m:["eine Minute","einer Minute"],h:["eine Stunde","einer Stunde"],d:["ein Tag","einem Tag"],dd:[a+" Tage",a+" Tagen"],M:["ein Monat","einem Monat"],MM:[a+" Monate",a+" Monaten"],y:["ein Jahr","einem Jahr"],yy:[a+" Jahre",a+" Jahren"]};return b?e[c][0]:e[c][1]}


function Md(a,b,c,d){var e=a+" ";switch(c){case"s":return b||d?"nekaj sekund":"nekaj sekundami";case"m":return b?"ena minuta":"eno minuto";case"mm":return e+=1===a?b?"minuta":"minuto":2===a?b||d?"minuti":"minutama":5>a?b||d?"minute":"minutami":b||d?"minut":"minutami";case"h":return b?"ena ura":"eno uro";case"hh":return e+=1===a?b?"ura":"uro":2===a?b||d?"uri":"urama":5>a?b||d?"ure":"urami":b||d?"ur":"urami";case"d":return b||d?"en dan":"enim dnem";case"dd":return e+=1===a?b||d?"dan":"dnem":2===a?b||d?"dni":"dnevoma":b||d?"dni":"dnevi";case"M":return b||d?"en mesec":"enim mesecem";case"MM":return e+=1===a?b||d?"mesec":"mesecem":2===a?b||d?"meseca":"mesecema":5>a?b||d?"mesece":"meseci":b||d?"mesecev":"meseci";case"y":return b||d?"eno leto":"enim letom";case"yy":return e+=1===a?b||d?"leto":"letom":2===a?b||d?"leti":"letoma":5>a?b||d?"leta":"leti":b||d?"let":"leti"}}function Nd(a){var b=a;return b=-1!==a.indexOf("jaj")?b.slice(0,-3)+"leS":-1!==a.indexOf("jar")?b.slice(0,-3)+"waQ":-1!==a.indexOf("DIS")?b.slice(0,-3)+"nem":b+" pIq"}function Od(a){var b=a;return b=-1!==a.indexOf("jaj")?b.slice(0,-3)+"Hu’":-1!==a.indexOf("jar")?b.slice(0,-3)+"wen":-1!==a.indexOf("DIS")?b.slice(0,-3)+"ben":b+" ret"}function Pd(a,b,c,d){var e=Qd(a);switch(c){case"mm":return e+" tup";case"hh":return e+" rep";case"dd":return e+" jaj";case"MM":return e+" jar";case"yy":return e+" DIS"}}function Qd(a){var b=Math.floor(a%1e3/100),c=Math.floor(a%100/10),d=a%10,e="";return b>0&&(e+=Sg[b]+"vatlh"),c>0&&(e+=(""!==e?" ":"")+Sg[c]+"maH"),d>0&&(e+=(""!==e?" ":"")+Sg[d]),""===e?"pagh":e}function Rd(a,b,c,d){var e={s:["viensas secunds","'iensas secunds"],m:["'n míut","'iens míut"],mm:[a+" míuts",""+a+" míuts"],h:["'n þora","'iensa þora"],hh:[a+" þoras",""+a+" þoras"],d:["'n ziua","'iensa ziua"],dd:[a+" ziuas",""+a+" ziuas"],M:["'n mes","'iens mes"],MM:[a+" mesen",""+a+" mesen"],y:["'n ar","'iens ar"],yy:[a+" ars",""+a+" ars"]};return d?e[c][0]:b?e[c][0]:e[c][1]}


    context.it.only = function(title, fn){
      var test = context.it(title, fn);
      var reString = '^' + utils.escapeRegexp(test.fullTitle()) + '$';
      mocha.grep(new RegExp(reString));
      return test;
    };


Runnable.prototype.timeout = function(ms){
  if (0 == arguments.length) return this._timeout;
  if ('string' == typeof ms) ms = milliseconds(ms);
  debug('timeout %d', ms);
  this._timeout = ms;
  if (this.timer) this.resetTimeout();
  return this;
};


    context.teardown = function(fn){
      suites[0].afterEach(fn);
    };


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


exports.create = function(parent, title){
  var suite = new Suite(title, parent.ctx);
  suite.parent = parent;
  if (parent.pending) suite.pending = true;
  title = suite.fullTitle();
  parent.addSuite(suite);
  return suite;
};


Context.prototype.runnable = function(runnable){
  if (0 == arguments.length) return this._runnable;
  this.test = this._runnable = runnable;
  return this;
};


module.exports = function(type){
  return function(){
  }
};


Suite.prototype.afterAll = function(fn){
  if (this.pending) return this;
  var hook = new Hook('"after all" hook', fn);
  hook.parent = this;
  hook.timeout(this.timeout());
  hook.slow(this.slow());
  hook.ctx = this.ctx;
  this._afterAll.push(hook);
  this.emit('afterAll', hook);
  return this;
};


exports.escapeRegexp = function(str){
  return str.replace(/[-\\^$*+?.()|[\]{}]/g, "\\$&");
};


function Min(runner) {
  Base.call(this, runner);

  runner.on('start', function(){
    // clear screen
    process.stdout.write('\u001b[2J');
    // set cursor position
    process.stdout.write('\u001b[1;3H');
  });

  runner.on('end', this.epilogue.bind(this));
}


    context.describe.only = function(title, fn){
      var suite = context.describe(title, fn);
      mocha.grep(suite.fullTitle());
      return suite;
    };


Progress.prototype.fontSize = function(n){
  this._fontSize = n;
  return this;
};


    global.onerror = function(err, url, line){
      fn(new Error(err + ' (' + url + ':' + line + ')'));
      return true;
    };


Suite.prototype.eachTest = function(fn){
  utils.forEach(this.tests, fn);
  utils.forEach(this.suites, function(suite){
    suite.eachTest(fn);
  });
  return this;
};


exports.escape = function(html){
  return String(html)
    .replace(/&/g, '&')
    .replace(/"/g, '"')
    .replace(/</g, '<')
    .replace(/>/g, '>');
};


		start      : function(e, ui) {
			var targets = $.map(ui.helper.data('files')||[], function(h) { return h || null ;}),
			locked = false,
			cnt, h;
			self.draggingUiHelper = ui.helper;
			cnt = targets.length;
			while (cnt--) {
				h = targets[cnt];
				if (files[h].locked) {
					locked = true;
					ui.helper.data('locked', true);
					break;
				}
			}
			!locked && self.trigger('lockfiles', {files : targets});

		},


	this.upload = function(files) {
			return this.transport.upload(files, this);
		}


						fm.trigger('unlockfiles', {files : helper.data('files'), helper: helper});
					},


	this.diff = function(incoming, onlydir) {
		var raw       = {},
			added     = [],
			removed   = [],
			changed   = [],
			isChanged = function(hash) {
				var l = changed.length;

				while (l--) {
					if (changed[l].hash == hash) {
						return true;
					}
				}
			};

		$.each(incoming, function(i, f) {
			raw[f.hash] = f;
		});

		// find removed
		$.each(files, function(hash, f) {
			if (!onlydir || f.phash === onlydir) {
				!raw[hash] && removed.push(hash);
			}
		});

		// compare files
		$.each(raw, function(hash, file) {
			var origin = files[hash];

			if (!origin) {
				added.push(file);
			} else {
				$.each(file, function(prop) {
					if (file[prop] != origin[prop]) {
						changed.push(file)
						return false;
					}
				});
			}
		});

		// parents of removed dirs mark as changed (required for tree correct work)
		$.each(removed, function(i, hash) {
			var file  = files[hash],
				phash = file.phash;

			if (phash
			&& file.mime == 'directory'
			&& $.inArray(phash, removed) === -1
			&& raw[phash]
			&& !isChanged(phash)) {
				changed.push(raw[phash]);
			}
		});

		return {
			added   : added,
			removed : removed,
			changed : changed
		};
	}


	this.exec = function() {
		if (!this.dialog) {
			content.find('#apiver').text(this.fm.api);
			this.dialog = this.fm.dialog(content, {title : this.title, width : 530, autoOpen : false, destroyOnClose : false});
		}

		this.dialog.elfinderdialog('open').find('.ui-tabs-nav li a:first').click();
	};


elFinder.prototype.commands.forward = function() {
	this.alwaysEnabled = true;
	this.updateOnSelect = true;
	this.shortcuts = [{
		pattern     : 'ctrl+right'
	}];

	this.getstate = function() {
		return this.fm.history.canForward() ? 0 : -1;
	}

	this.exec = function() {
		return this.fm.history.forward();
	}

}


				cancel = function() {
					var close = function(){
						dfrd.reject();
						ta.elfinderdialog('close');
					};
					ta.editor && ta.editor.save(ta[0], ta.editor.instance);
					if (rtrim(old) !== rtrim(ta.val())) {
						old = ta.val();
						fm.confirm({
							title  : self.title,
							text   : 'confirmNotSave',
							accept : {
								label    : 'btnSaveClose',
								callback : function() {
									save();
									close();
								}
							},
							cancel : {
								label    : 'btnClose',
								callback : close
							}
						});
					} else {
						close();
					}
				},


							top  : parseInt(nav.scrollTop())+'px',
							left : ltr ? 'auto' : parseInt(nav.scrollLeft() + offset),
							right: ltr ? parseInt(nav.scrollLeft() - offset) * -1 : 'auto'
						});


		this.trigger('resize', {width : node.width(), height : node.height()});
	}


							left   : parseInt($(window).scrollLeft())+'px',
							top    : parseInt($(window).scrollTop()) +'px'
						})
					})
					.bind(self.resize, function(e) {
						self.preview.trigger('changesize');
					})
					.trigger(scroll)
					.trigger(self.resize);

					win.bind('mousemove', function(e) {
						navbar.stop(true, true).show().delay(3000).fadeOut('slow');
					})
					.mousemove();

					navbar.mouseenter(function() {
						navbar.stop(true, true).show();
					})
					.mousemove(function(e) {
						e.stopPropagation();
					});
				}


				text   : fm.i18n('confirmUnmount', drive.name),
				accept : {
					label    : 'btnUnmount',
					callback : function() {
						fm.request({
							data   : {cmd  : 'netmount', protocol : 'netunmount', host: drive.netkey, user : drive.hash, pass : 'dum'},
							notify : {type : 'netunmount', cnt : 1, hideCnt : true},
							preventFail : true
						})
						.fail(function(error) {
							dfrd.reject(error);
						})
						.done(function(data) {
							var chDrive = (fm.root() == drive.hash);
							data.removed = [ drive.hash ];
							fm.remove(data);
							if (chDrive) {
								var files = fm.files();
								for (var i in files) {
									if (fm.file(i).mime == 'directory') {
										fm.exec('open', i);
										break;
									}
								}
							}
							dfrd.resolve();
						});
					}
				},
				cancel : {
					label    : 'btnCancel',
					callback : function() { dfrd.reject(); }
				}
			});
		}

		return dfrd;
	};


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


			add = function(files) {
				var place    = list ? cwd.find('tbody') : cwd,
					l        = files.length,
					ltmb     = [],
					atmb     = {},
					dirs     = false,
					findNode = function(file) {
						var pointer = cwd.find('[id]:first'), file2;

						while (pointer.length) {
							file2 = fm.file(fm.cwdId2Hash(pointer.attr('id')));
							if (!pointer.hasClass('elfinder-cwd-parent') && file2 && fm.compare(file, file2) < 0) {
								return pointer;
							}
							pointer = pointer.next('[id]');
						}
					},
					findIndex = function(file) {
						var l = buffer.length, i;

						for (i =0; i < l; i++) {
							if (fm.compare(file, buffer[i]) < 0) {
								return i;
							}
						}
						return l || -1;
					},
					file, hash, node, ndx;

				l && wrapper.removeClass('elfinder-cwd-wrapper-empty');

				while (l--) {
					file = files[l];
					hash = file.hash;

					if ($('#'+fm.cwdHash2Id(hash)).length) {
						continue;
					}

					if ((node = findNode(file)) && node.length) {
						node.before(itemhtml(file));
					} else if ((ndx = findIndex(file)) >= 0) {
						buffer.splice(ndx, 0, file);
					} else {
						place.append(itemhtml(file));
					}

					if ($('#'+fm.cwdHash2Id(hash)).length) {
						if (file.mime == 'directory') {
							dirs = true;
						} else if (file.tmb) {
							file.tmb === 1 ? ltmb.push(hash) : (atmb[hash] = file.tmb);
						}
					}
				}

				bottomMarkerShow(place);
				attachThumbnails(atmb);
				ltmb.length && loadThumbnails(ltmb);
				dirs && !mobile && makeDroppable();
			},


			updateDroppable = function(target) {
				var limit = 100,
					next;

				if (!target) {
					tree.find('div.'+uploadable).find(selNavdir+':not(.elfinder-ro,.elfinder-na)').addClass('native-droppable');
					target = tree.find('div.'+pastable).find(selNavdir+':not(.'+droppable+',.elfinder-ro,.elfinder-na)');
				}

				if (target.length > limit) {
					next = target.slice(limit);
					target = target.slice(0, limit);
				}

				target.droppable(droppableopts);

				if (next) {
					setTimeout(function(){
						updateDroppable(next);
					}, 20);
				}
			},


			setstat    = function(files, cwd) {
				var c = 0,
					s = 0;

				$.each(files, function(i, file) {
					if (!cwd || file.phash == cwd) {
						c++;
						s += parseInt(file.size)||0;
					}
				})
				size.html(titleitems+': '+c+', '+titlesize+': '+fm.formatSize(s));
			},


				multi = function(files, num){
					var sfiles = [], cid;
					if (!abort) {
						while(files.length && sfiles.length < num) {
							sfiles.push(files.shift());
						}
						if (sfiles.length) {
							for (var i=0; i < sfiles.length; i++) {
								if (abort) {
									break;
								}
								cid = isDataType? (sfiles[i][0][0]._cid || null) : (sfiles[i][0]._cid || null);
								if (!!failChunk[cid]) {
									last--;
									continue;
								}
								fm.exec('upload', {
									type: data.type,
									isDataType: isDataType,
									files: sfiles[i],
									checked: true,
									target: target,
									renames: renames,
									hashes: hashes,
									multiupload: true})
								.fail(function(error) {
									if (cid) {
										failChunk[cid] = true;
									}
								})
								.always(function(e) {
									if (e && e.added) added = $.merge(added, e.added);
									if (last <= ++done) {
										fm.trigger('multiupload', {added: added});
										notifyto && clearTimeout(notifyto);
										if (checkNotify()) {
											self.notify({type : 'upload', cnt : -cnt, progress : 0, size : 0});
										}
									}
									multi(files, 1); // Next one
								});
							}
						}
					}
					if (sfiles.length < 1 || abort) {
						if (abort) {
							notifyto && clearTimeout(notifyto);
							if (cid) {
								failChunk[cid] = true;
							}
							dfrd.reject();
						} else {
							dfrd.resolve();
							self.uploads.xhrUploading = false;
						}
					}
				},


shortcuts = function() {
			var sh = fm.shortcuts();
			// shortcuts tab
			html.push('
');

			if (sh.length) {
				html.push('
');
				$.each(sh, function(i, s) {
					html.push(stpl.replace(/\{pattern\}/, s[0]).replace(/\{descrip\}/, s[1]));
				});

				html.push('
');
			} else {
				html.push('
'+fm.i18n('shortcutsof')+'
');
			}

			html.push('
');

		},


			return {changed : [this.normalizeFile(data.target, phash)]};
		}

		phash = data.cwd.hash;

		if (data.tree) {
			$.each(this.normalizeTree(data.tree), function(i, file) {
				files[file.hash] = file;
			});
		}

		$.each(data.cdc||[], function(i, file) {
			var hash = file.hash;

			if (files[hash]) {
				files[hash].date   = file.date;
				files[hash].locked = file.hash == phash ? true : file.rm === void(0) ? false : !file.rm;
			} else {
				files[hash] = self.normalizeFile(file, phash, data.tmb);
			}
		});

		if (!data.tree) {
			$.each(this.fm.files(), function(hash, file) {
				if (!files[hash] && file.phash != phash && file.mime == 'directory') {
					files[hash] = file;
				}
			});
		}

		if (cmd == 'open') {
			return {
					cwd     : files[phash] || this.normalizeFile(data.cwd),
					files   : $.map(files, function(f) { return f }),
					options : self.normalizeOptions(data),
					init    : !!data.params,
					debug   : data.debug
				};
		}

		return $.extend({
			current : data.cwd.hash,
			error   : data.error,
			warning : data.warning,
			options : {tmb : !!data.tmb}
		}, this.fm.diff($.map(files, filter)));

	}


pimcore.helpers.grid.getTranslationColumnRenderer = function (value, metaData, record, rowIndex, colIndex, store) {
    return t(value);
};


function uploadSizeError( up, file, over100mb ) {
	var message;

	if ( over100mb )
		message = pluploadL10n.big_upload_queued.replace('%s', file.name) + ' ' + pluploadL10n.big_upload_failed.replace('%1$s', '').replace('%2$s', '');
	else
		message = pluploadL10n.file_exceeds_size_limit.replace('%s', file.name);

	jQuery('#media-items').append('

' + message + '

');
	up.removeFile(file);
}


		success:function (data, textStatus) {
			updateIndex(context_id, context);
			handleGenericAjaxResponse(data);
		},


		beforeSend: function (XMLHttpRequest) {
			$(".loading").show();
		},


	__uuidv4() {
		return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
			var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
			return v.toString(16);
		});
	}


        var policy = function (tagName, attribs) {
            if (!(html4.ELEMENTS[tagName] & html4.eflags.UNSAFE)) {
                return {
                    'attribs': sanitizeAttribs(tagName, attribs,
                        noop, noop, record_messages)
                    };
            } else {
                record_messages(tagName + " removed", {
                  change: "removed",
                  tagName: tagName
                });
            }
        };

        var sanitized = caja.sanitizeWithPolicy(html, policy);

        if (allow_css) {
            // sanitize style tags as stylesheets
            sanitized = sanitize_stylesheets(sanitized, policy);
        }

        return sanitized;
    };


LdapAuth.prototype._findUser = function (username, callback) {
  var self = this;
  if (!username) {
    return callback("empty username");
  }

  var searchFilter = self.opts.searchFilter.replace(/{{username}}/g, username);
  var opts = {filter: searchFilter, scope: self.opts.searchScope};
  if (self.opts.searchAttributes) {
    opts.attributes = self.opts.searchAttributes;
  }

  self._search(self.opts.searchBase, opts, function (err, result) {
    if (err) {
      self.log && self.log.trace('ldap authenticate: user search error: %s %s %s', err.code, err.name, err.message);
      return callback(err);
    }

    switch (result.length) {
    case 0:
      return callback();
    case 1:
      return callback(null, result[0])
    default:
      return callback(format(
        'unexpected number of matches (%s) for "%s" username',
        result.length, username));
    }
  });
};


Note.renderNote = function(note) {
    if (!note) {
        return;
    }
    // title
    $("#noteTitle").val(note.Title);

    // 当前正在编辑的
    // tags
    Tag.input.setTags(note.Tags);
};


  function parseAssignment () {
    var name, args, value, valid;

    var node = parseConditional();

    if (token == '=') {
      if (type.isSymbolNode(node)) {
        // parse a variable assignment like 'a = 2/3'
        name = node.name;
        getTokenSkipNewline();
        value = parseAssignment();
        return new AssignmentNode(new SymbolNode(name), value);
      }
      else if (type.isAccessorNode(node)) {
        // parse a matrix subset assignment like 'A[1,2] = 4'
        getTokenSkipNewline();
        value = parseAssignment();
        return new AssignmentNode(node.object, node.index, value);
      }
      else if (type.isFunctionNode(node)) {
        // parse function assignment like 'f(x) = x^2'
        valid = true;
        args = [];

        name = node.name;
        node.args.forEach(function (arg, index) {
          if (type.isSymbolNode(arg)) {
            args[index] = arg.name;
          }
          else {
            valid = false;
          }
        });

        if (valid) {
          getTokenSkipNewline();
          value = parseAssignment();
          return new FunctionAssignmentNode(name, args, value);
        }
      }

      throw createSyntaxError('Invalid left hand side of assignment operator =');
    }

    return node;
  }


            text: Ext.util.Format.htmlEncode(record.get('name')),
            qtip: Tine.Tinebase.common.doubleEncode(record.get('host')),
            leaf: false,
            cls: 'felamimail-node-account',
            delimiter: record.get('delimiter'),
            ns_personal: record.get('ns_personal'),
            account_id: record.data.id,
            listeners: {
                scope: this,
                load: function(node) {
                    var account = this.accountStore.getById(node.id);
                    this.updateAccountStatus(account);
                }
            }
        });


                qtip: Tine.Tinebase.common.doubleEncode(attr.name.name)
            });
        }

        // copy 'real' data to a node record NOTE: not a full record as we have no record reader here
        var nodeData = Ext.copyTo({}, attr, Tine.Filemanager.Model.Node.getFieldNames());
        attr.nodeRecord = new Tine.Filemanager.Model.Node(nodeData);
    },


                        text : Ext.util.Format.htmlEncode(this.app.i18n._hidden(attr.name)),
                        qtip : Tine.Tinebase.common.doubleEncode(attr.description ? this.app.i18n._hidden(attr.description) + ' ' + addText : addText),
                        selected : attr.id === this.selectedFilterId,
                        id : attr.id,

                        sorting : attr.sorting,
                        draggable : true,
                        allowDrop : false,

                        leaf : attr.leaf === false ? attr.leaf : true,
                        cls : 'tinebase-westpanel-node-favorite' + addClass
                    });
                }


    menuItemTemplate: function (item) {
      return `<a>${item.string}</a>`;
    },


    $scope.save = function() {
      var form = this.fsForm;
      RequisitionsService.startTiming();
      RequisitionsService.saveForeignSourceDefinition($scope.foreignSourceDef).then(
        function() { // success
          growl.success('The definition for the requisition ' + $scope.foreignSource + ' has been saved.');
          form.$dirty = false;
        },
        $scope.errorHandler
      );
    };


    $scope.addRequisition = function() {
      bootbox.prompt('A requisition is required, please enter the name for a new requisition', function(foreignSource) {
        if (foreignSource) {
          RequisitionsService.addRequisition(foreignSource).then(
            function() { // success
              RequisitionsService.synchronizeRequisition(foreignSource, false).then(
                function() {
                  growl.success('The requisition ' + foreignSource + ' has been created and synchronized.');
                  $scope.foreignSources.push(foreignSource);
                },
                $scope.errorHandler
              );
            },
            $scope.errorHandler
          );
        } else {
          window.location.href = Util.getBaseHref() + 'admin/opennms/index.jsp'; // TODO Is this the best way ?
        }
      });
    };


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


    $scope.clone = function(foreignSource) {
      var availableForeignSources = [];
      angular.forEach($scope.requisitionsData.requisitions, function(r) {
        if (r.foreignSource !== foreignSource) {
          availableForeignSources.push(r.foreignSource);
        }
      });
      var modalInstance = $uibModal.open({
        backdrop: 'static',
        keyboard: false,
        controller: 'CloneForeignSourceController',
        templateUrl: cloneForeignsourceView,
        resolve: {
          foreignSource: function() { return foreignSource; },
          availableForeignSources: function() { return availableForeignSources; }
        }
      });
      modalInstance.result.then(function(targetForeignSource) {
        bootbox.confirm('This action will override the existing foreign source definition for the requisition named ' + targetForeignSource + ', using ' + foreignSource + ' as a template. Are you sure you want to continue ? This cannot be undone.', function(ok) {
          if (!ok) {
            return;
          }
          RequisitionsService.startTiming();
          RequisitionsService.cloneForeignSourceDefinition(foreignSource, targetForeignSource).then(
            function() { // success
              growl.success('The foreign source definition for ' + foreignSource + ' has been cloned to ' + targetForeignSource);
            },
            $scope.errorHandler
          );
        });
      });
    };


synchronize: function(requisition, errorHandler) {
        /**
        * @param {object} requisition The requisition object
        * @param {string} rescanExisting true to perform a full scan, false to only add/remove nodes without scan, dbonly for all DB operations without scan
        */
        var doSynchronize = function(requisition, rescanExisting) {
          RequisitionsService.startTiming();
          RequisitionsService.synchronizeRequisition(requisition.foreignSource, rescanExisting).then(
            function() { // success
              growl.success('The import operation has been started for ' + requisition.foreignSource + ' (rescanExisting? ' + rescanExisting + ')
Use refresh to update the deployed statistics');
              requisition.setDeployed(true);
            },
            errorHandler
          );
        };
        bootbox.prompt({
            title: 'Synchronize Requisition  ' +  requisition.foreignSource,
            message: '
Choose a scan option:
',
            inputType: 'radio',
            inputOptions: [
            {
                text: 'Scan all nodes',
                value: 'true',
            },
            {
                text: 'Scan added nodes only',
                value: 'false',
            },
            {
                text: 'No scanning',
                value: 'dbonly',
            }
            ],
            buttons: {
                    confirm: {
                        label: 'Synchronize',
                    },
                    cancel: {
                        label: 'Cancel',
                    }
                },
            swapButtonOrder: 'true',
            callback: function (result) {
                if (result !== null) {
                    doSynchronize(requisition, result);
                }
            }
        });
      }


    $scope.reset = function() {
      bootbox.confirm('Are you sure you want to reset the foreign source definition to the default ?', function(ok) {
        if (ok) {
          RequisitionsService.startTiming();
          RequisitionsService.deleteForeignSourceDefinition($scope.foreignSource).then(
            function() { // success
              growl.success('The foreign source definition for ' + $scope.foreignSource + 'has been reseted.');
              $scope.initialize();
            },
            $scope.errorHandler
          );
        }
      });
    };


    $scope.refresh = function() {
      growl.success('Retrieving node ' + $scope.foreignId + ' from requisition ' + $scope.foreignSource + '...');
      RequisitionsService.getNode($scope.foreignSource, $scope.foreignId).then(
        function(node) { // success
          $scope.node = node;
        },
        $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
      );
    };


    $scope.provision = function() {
      $scope.isSaving = true;
      growl.info($sanitize('The node ' + $scope.node.nodeLabel + ' is being added to requisition ' + $scope.node.foreignSource + '. Please wait...'));
      var successMessage = $sanitize('The node ' + $scope.node.nodeLabel + ' has been added to requisition ' + $scope.node.foreignSource);
      RequisitionsService.quickAddNode($scope.node).then(
        function() { // success
          $scope.reset();
          bootbox.dialog({
            message: successMessage,
            title: 'Success',
            buttons: {
              main: {
                label: 'Ok',
                className: 'btn-secondary'
              }
            }
          });
        },
        $scope.errorHandler
      );
    };


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


var doSynchronize = function(requisition, rescanExisting) {
          RequisitionsService.startTiming();
          RequisitionsService.synchronizeRequisition(requisition.foreignSource, rescanExisting).then(
            function() { // success
              growl.success('The import operation has been started for ' + requisition.foreignSource + ' (rescanExisting? ' + rescanExisting + ')
Use refresh to update the deployed statistics');
              requisition.setDeployed(true);
            },
            errorHandler
          );
        };


function getMethods(a){var b=[],c;for(c in a)try{"function"==typeof a[c]&&b.push(c+": "+a[c].toString())}catch(e){b.push(c+": inaccessible")}return b}function dump(a,b){var c="";b||(b=0);for(var e="",d=0;d<b+1;d++)e+=" ";if("object"==typeof a)for(var f in a)d=a[f],"object"==typeof d?(c+=e+"'"+f+"' ...\n",c+=dump(d,b+1)):c+=e+"'"+f+"' => \""+d+'"\n';else c="===>"+a+"<===("+typeof a+")";return c};(function(a){a.fn.fc_set_tab_list=function(b){var c={toggle_speed:300,fc_list_forms:a(".fc_list_forms"),fc_list_add:a("#fc_list_add")};b=a.extend(c,b);return this.each(function(){var c=a(this),d=c.closest("ul").children("li"),f="fc_list_"+c.children("input").val(),g=a("#"+f),h=a("#fc_install_new");b.fc_list_forms.not(":first").slideUp(0);0===b.fc_list_add.size()?d.filter(":first").addClass("fc_active"):b.fc_list_add.unbind().click(function(){d.removeClass("fc_active");b.fc_list_forms.not(h).slideUp(0);


function stat(dir, files, cb) {
  var batch = new Batch();

  batch.concurrency(10);

  files.forEach(function(file, i){
    batch.push(function(done){
      fs.stat(join(dir, file), done);
    });
  });

  batch.end(cb);
}


exports = module.exports = function directory(root, options){
  options = options || {};

  // root required
  if (!root) throw new Error('directory() root path required');
  var hidden = options.hidden
    , icons = options.icons
    , view = options.view || 'tiles'
    , filter = options.filter
    , root = normalize(root + sep)
    , template = options.template || defaultTemplate;

  return function directory(req, res, next) {
    if ('GET' != req.method && 'HEAD' != req.method) return next();

    var url = parse(req.url)
      , dir = decodeURIComponent(url.pathname)
      , path = normalize(join(root, dir))
      , originalUrl = parse(req.originalUrl)
      , originalDir = decodeURIComponent(originalUrl.pathname)
      , showUp = path != root;

    // null byte(s), bad request
    if (~path.indexOf('\0')) return next(utils.error(400));

    // malicious path, forbidden
    if (0 != path.indexOf(root)) return next(utils.error(403));

    // check if we have a directory
    fs.stat(path, function(err, stat){
      if (err) return 'ENOENT' == err.code
        ? next()
        : next(err);

      if (!stat.isDirectory()) return next();

      // fetch files
      fs.readdir(path, function(err, files){
        if (err) return next(err);
        if (!hidden) files = removeHidden(files);
        if (filter) files = files.filter(filter);
        files.sort();

        // content-negotiation
        var type = new Negotiator(req).preferredMediaType(mediaTypes);

        // not acceptable
        if (!type) return next(utils.error(406));
        exports[mediaType[type]](req, res, files, next, originalDir, showUp, icons, path, view, template);
      });
    });
  };
};


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 toString(stringify) {
  if (!stringify || 'function' !== typeof stringify) stringify = qs.stringify;

  var query
    , url = this
    , protocol = url.protocol;

  if (protocol && protocol.charAt(protocol.length - 1) !== ':') protocol += ':';

  var result =
    protocol +
    ((url.protocol && url.slashes) || isSpecial(url.protocol) ? '//' : '');

  if (url.username) {
    result += url.username;
    if (url.password) result += ':'+ url.password;
    result += '@';
  } else if (url.password) {
    result += ':'+ url.password;
    result += '@';
  } else if (
    url.protocol !== 'file:' &&
    isSpecial(url.protocol) &&
    !url.host &&
    url.pathname !== '/'
  ) {
    //
    // Add back the empty userinfo, otherwise the original invalid URL
    // might be transformed into a valid one with `url.pathname` as host.
    //
    result += '@';
  }

  result += url.host + url.pathname;

  query = 'object' === typeof url.query ? stringify(url.query) : url.query;
  if (query) result += '?' !== query.charAt(0) ? '?'+ query : query;

  if (url.hash) result += url.hash;

  return result;
}


function main(){
    //Try using pkg-config, but if it fails and it is on Windows, try the fallback
    exec("pkg-config " + opencv + " " + flag, function(error, stdout, stderr){
        if(error){
            if(process.platform === "win32"){
                fallback();
            }
            else{
                throw new Error("ERROR: failed to run: pkg-config", opencv, flag);
            }
        }
        else{
            console.log(stdout);
        }
    });
}


function main() {
    // adapter.subscribeForeignStates('*');
    // adapter.subscribeForeignObjects('*');

    adapter.config.defaultUser = adapter.config.defaultUser || 'admin';
    if (!adapter.config.defaultUser.match(/^system\.user\./)) {
        adapter.config.defaultUser = 'system.user.' + adapter.config.defaultUser;
    }

    if (adapter.config.secure) {
        // Load certificates
        adapter.getCertificates((err, certificates, leConfig) => {
            adapter.config.certificates = certificates;
            adapter.config.leConfig     = leConfig;

            getData(() => webServer = new Web(adapter.config, adapter, initSocket));
        });
    } else {
        getData(() => webServer = new Web(adapter.config, adapter, initSocket));
    }

    patchRepos(() => {
        // By default update repository every 24 hours
        if (adapter.config.autoUpdate === undefined) {
            adapter.config.autoUpdate = 24;
        }
        adapter.config.autoUpdate = parseInt(adapter.config.autoUpdate, 10) || 0;
        if (adapter.config.autoUpdate) {
            setInterval(() => updateRegister(), adapter.config.autoUpdate * 3600000);
            updateRegister();
        }
    });
}


    main.unsubscribeStates = function (patterns) {
        if (!patterns) return;
        if (typeof patterns === 'object') {
            for (var s = 0; s < patterns.length; s++) {
                if (main.subscribesStates[patterns[s]]) {
                    main.subscribesStates[patterns[s]]--;
                }
                if (main.subscribesStates[patterns[s]] === 0) {
                    console.debug('Unsibscribe: ' + patterns[s]);
                    main.socket.emit('unsubscribe', patterns[s]);
                    delete main.subscribesStates[patterns[s]];
                }
            }
        } else {
            if (main.subscribesStates[patterns]) {
                main.subscribesStates[patterns]--;
            }
            if (main.subscribesStates[patterns] === 0) {
                console.debug('Unsibscribe: ' + patterns);
                main.socket.emit('unsubscribe', patterns);
                delete main.subscribesStates[patterns];
            }
        }
    };


    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 + '" />';
    };