    public function get_info($object_id, $table_name = '')
    {
        $table_name = $table_name ? Dba::escape($table_name) : Dba::escape(strtolower(get_class($this)));

        // Make sure we've got a real id
        if ($object_id < 1) {
            return array();
        }

        if (self::is_cached($table_name, $object_id)) {
            return self::get_from_cache($table_name, $object_id);
        }

        $sql        = "SELECT * FROM `$table_name` WHERE `id`='$object_id'";
        $db_results = Dba::read($sql);

        if (!$db_results) {
            return array();
        }

        $row = Dba::fetch_assoc($db_results);

        self::add_to_cache($table_name, $object_id, $row);

        return $row;
    } // get_info


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


function ttMitigateCSRF() {
  // No need to do anything for get requests.
  global $request;
  if ($request->isGet())
    return true;

  $origin = $_SERVER['HTTP_ORIGIN'];
  if ($origin) {
    $pos = strpos($origin, '//');
    $origin = substr($origin, $pos+2); // Strip protocol.
  }
  if (!$origin) {
    // Try using referer.
    $origin = $_SERVER['HTTP_REFERER'];
    if ($origin) {
      $pos = strpos($origin, '//');
      $origin = substr($origin, $pos+2); // Strip protocol.
      $pos = strpos($origin, '/');
      $origin = substr($origin, 0, $pos); // Leave host only.
    }
  }
  error_log("origin: ".$origin);
  $target = defined('HTTP_TARGET') ? HTTP_TARGET : $_SERVER['HTTP_HOST'];
  error_log("target: ".$target);
  if (strcmp($origin, $target)) {
    error_log("Potential cross site request forgery. Origin: '$origin' does not match target: '$target'.");
    return false; // Origin and target do not match,
  }

  // TODO: review and improve this function for custom ports.
  return true;
}


    protected function getTestFile($fileName)
    {
        return new \Illuminate\Http\UploadedFile(base_path('tests/test-data/test-file.txt'), $fileName, 'text/plain', 55, null, true);
    }


  public function isLocal() {
    $localhosts = array('::1', '127.0.0.1', '0.0.0.0');
    return (
      in_array(server::get('SERVER_ADDR'), $localhosts) ||
      server::get('SERVER_NAME') == 'localhost' ||
      str::endsWith(server::get('SERVER_NAME'), '.localhost') ||
      str::endsWith(server::get('SERVER_NAME'), '.test')
    );
  }


                $text = sanitize_text_field($agent);
                $agents[] = $text;
            }
        }

        if (sizeof($agents) > 1)
        {
            sort( $agents );
            $agents = array_unique($agents, SORT_STRING);
        }

        $banned_user_agent_data = implode(PHP_EOL, $agents);
        $aio_wp_security->configs->set_value('aiowps_banned_user_agents',$banned_user_agent_data);
        $_POST['aiowps_banned_user_agents'] = ''; //Clear the post variable for the banned address list
        return 1;
    }


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

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

                    break;

                case '$where':

                    if (\is_callable($value)) {

                        // need implementation
                    }

                    break;

                default:

                    $d = '$document';

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

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

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

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

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

                        if (is_null($value)) {

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

                        } else {

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

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

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


    protected function parseChunkedRequest(Request $request)
    {
        $index = $request->get('qqpartindex');
        $total = $request->get('qqtotalparts');
        $uuid = $request->get('qquuid');
        $orig = $request->get('qqfilename');
        $last = ((int) $total - 1) === (int) $index;

        return [$last, $uuid, $index, $orig];
    }


    protected function parseChunkedRequest(Request $request)
    {
        $session = $this->container->get('session');

        $orig = $request->get('name');
        $index = $request->get('chunk');
        $last = (int) $request->get('chunks') - 1 === (int) $request->get('chunk');

        // it is possible, that two clients send a file with the
        // exact same filename, therefore we have to add the session
        // to the uuid otherwise we will get a mess
        $uuid = md5(sprintf('%s.%s', $orig, $session->getId()));

        return [$last, $uuid, $index, $orig];
    }


					$searches[] = $wpdb->prepare( "u.{$field} LIKE %s", '%' . trim( $_POST['search'] ) . '%' );
				}

				$core_search = implode( ' OR ', $searches );

				$this->joins[] = "LEFT JOIN {$wpdb->prefix}um_metadata umm_search ON umm_search.user_id = u.ID";
				$this->sql_where .= " AND ( umm_search.um_value = '" . trim( $_POST['search'] ) . "' OR umm_search.um_value LIKE '%" . trim( $_POST['search'] ) . "%' OR umm_search.um_value LIKE '%" . trim( serialize( strval( $_POST['search'] ) ) ) . "%' OR {$core_search})";

				$this->is_search = true;
			}


    public static function getNameWithCase($name, $surname, $title = false, $id = false, $nick = false)
    {
        $str = '';

        if ($title !== false && $title instanceof Title) {
            $str .= $title->tshort . ' ';
        }

        $str .= mb_strtoupper($name, 'UTF-8') . ' ' .
            ucwords(mb_strtolower($surname, 'UTF-8'), " \t\r\n\f\v-_|");

        if ($id !== false || $nick !== false) {
            $str .= ' (';
        }
        if ($nick !== false) {
            $str .= $nick;
        }
        if ($id !== false) {
            if ($nick !== false && !empty($nick)) {
                $str .= ', ';
            }
            $str .= $id;
        }
        if ($id !== false || $nick !== false) {
            $str .= ')';
        }
        return $str;
    }


    public function getName($translated = true)
    {
        if ($translated === true) {
            return _T($this->name);
        } else {
            return $this->name;
        }
    }


    protected function load($id, $init = true)
    {
        global $login;

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

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

            $count = $results->count();
            if ($count === 0) {
                if ($init === true) {
                    $models = new PdfModels($this->zdb, $this->preferences, $login);
                    $models->installInit();
                    $this->load($id, false);
                } else {
                    throw new \RuntimeException('Model not found!');
                }
            } else {
                $this->loadFromRs($results->current());
            }
        } catch (Throwable $e) {
            Analog::log(
                'An error occurred loading model #' . $id . "Message:\n" .
                $e->getMessage(),
                Analog::ERROR
            );
            throw $e;
        }
    }


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


					$dt = date('Y-m-d', strtotime($match));
					$sql = par_rep("/'$match'/", "'$dt'", $sql);
				}
			}
			if (substr($sql, 0, 6) == "BEGIN;") {
				$array = explode(";", $sql);
				foreach ($array as $value) {
					if ($value != "") {
						$result = $connection->query($value);
						if (!$result) {
							$connection->query("ROLLBACK");
							die(db_show_error($sql, _dbExecuteFailed, mysql_error()));
						}
					}
				}
			} else {
				$result = $connection->query($sql) or die(db_show_error($sql, _dbExecuteFailed, mysql_error()));
			}
			break;
	}


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


                foreach ($val as $vkey => $value) {
                    if ($vkey != 'LAST_UPDATED') {
                        if ($vkey != 'UPDATED_BY') {
                            if ($vkey == 'ID')
                                echo '<SCHOOL_ID>' . htmlentities($value) . '</SCHOOL_ID>';
                            else if ($vkey == 'SYEAR')
                                echo '<SCHOOL_YEAR>' . htmlentities($value) . '</SCHOOL_YEAR>';
                            else if ($vkey == 'TITLE')
                                echo '<SCHOOL_NAME>' . htmlentities($value) . '</SCHOOL_NAME>';
                            else if ($vkey == 'WWW_ADDRESS')
                                echo '<URL>' . htmlentities($value) . '</URL>';
                            else
                                echo '<' . $vkey . '>' . htmlentities($value) . '</' . $vkey . '>';
                        }
                    }
                }


                foreach ($value as $k => $val) {
                    if ($k != 'LAST_UPDATED') {
                        if ($k != 'UPDATED_BY') {
                            if ($k == 'ID')
                                $data['data'][$i]['SCHOOL_ID'] = $val;
                            else if ($k == 'SYEAR')
                                $data['data'][$i]['SCHOOL_YEAR'] = $val;
                            else if ($k == 'TITLE')
                                $data['data'][$i]['SCHOOL_NAME'] = $val;
                            else if ($k == 'WWW_ADDRESS')
                                $data['data'][$i]['URL'] = $val;
                            else
                                $data['data'][$i][$k] = $val;
                        }
                    }
                }


                        echo '</SCHOOL_' . htmlentities($i) . '>';
                        $i++;
                    }
                    echo '</SCHOOL_ACCESS>';
                    //                }
                    echo '</STAFF_' . htmlentities($j) . '>';
                    $j++;
                }


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


        foreach($course_RET as $period_date)
        {
            // $period_days_append_sql .="(sp.start_time<='$period_date[END_TIME]' AND '$period_date[START_TIME]'<=sp.end_time AND IF(course_period_date IS NULL, course_period_date='$period_date[COURSE_PERIOD_DATE]',DAYS LIKE '%$period_date[DAYS]%')) OR ";
              $period_days_append_sql .="(sp.start_time<='$period_date[END_TIME]' AND '$period_date[START_TIME]'<=sp.end_time AND (cpv.course_period_date IS NULL OR cpv.course_period_date='$period_date[COURSE_PERIOD_DATE]') AND cpv.DAYS LIKE '%$period_date[DAYS]%') OR ";

        }


        foreach ($cf_d as $cfd_i => $cfd_d) {
            if ($cfd_i == 'TYPE') {
                $fc = substr($cfd_d, 0, 1);
                $lc = substr($cfd_d, 1);
                $cfd_d = strtoupper($fc) . $lc;
                $get_schools_cf[$cf_i][$cfd_i] = $cfd_d;
                unset($fc);
                unset($lc);
            }
            if ($cfd_i == 'SELECT_OPTIONS' && $cf_d['TYPE'] != 'text') {

                for ($i = 0; $i < strlen($cfd_d); $i++) {
                    $char = substr($cfd_d, $i, 1);
                    if (ord($char) == '13')
                        $char = '<br/>';
                    $new_char[] = $char;
                }

                $cfd_d = implode('', $new_char);
                $get_schools_cf[$cf_i][$cfd_i] = $cfd_d;
                unset($char);
                unset($new_char);
            }
            if ($cfd_i == 'SYSTEM_FIELD' || $cfd_i == 'REQUIRED') {
                if ($cfd_d == 'N')
                    $get_schools_cf[$cf_i][$cfd_i] = 'No';
                if ($cfd_d == 'Y')
                    $get_schools_cf[$cf_i][$cfd_i] = 'Yes';
            }
        }


    protected function __construct() {
        parent::__construct();
        self::$locale = fusion_get_locale('', LOCALE.LOCALESET.'search.php');
    }


	public static function RemoveTransaction($id)
	{
		$sFilepath = APPROOT.'data/transactions/'.$id;
		clearstatcache(true, $sFilepath);
		if (!file_exists($sFilepath)) {
			$bSuccess = false;
			self::Error("RemoveTransaction: Transaction '$id' not found. Pending transactions for this user:\n"
				.implode("\n", self::GetPendingTransactions()));
		} else {
			$bSuccess = @unlink($sFilepath);
		}

		if (!$bSuccess) {
			self::Error('RemoveTransaction: FAILED to remove transaction '.$id);
		} else {
			self::Info('RemoveTransaction: OK '.$id);
		}

		return $bSuccess;
	}


    public static function ListProfiles($oUser = null)
	{
		if (is_null($oUser))
		{
			$oUser = self::$m_oUser;
		}
		if ($oUser === null)
		{
			// Not logged in: no profile at all
			$aProfiles = array();
		}
		elseif ((self::$m_oUser !== null) && ($oUser->GetKey() == self::$m_oUser->GetKey()))
		{
			// Data about the current user can be found into the session data
			if (array_key_exists('profile_list', $_SESSION))
			{
				$aProfiles = $_SESSION['profile_list'];
			}
		}

		if (!isset($aProfiles))
		{
			$aProfiles = self::$m_oAddOn->ListProfiles($oUser);
		}
		return $aProfiles;
	}


    public function __construct($message = null, $code = 404, Exception $previous = null)
    {
        if ($message === null) {
            $message = _('Nothing to show with this id');
        }
        parent::__construct($message, $code, $previous);
    }


function global_cache_key($dir = true)
{
	$cache_key = $_SERVER['REQUEST_URI'];
	$cache_key = str_replace('/', '-', $cache_key);
	$cache_key = mso_slug(' ' . $cache_key);

	if (!$cache_key) $cache_key = 'home'; // главная

	if ($dir) $cache_key = 'html/' . $cache_key . '.html';
		else $cache_key = $cache_key . '.html';

	return $cache_key;
}


function create_thumbs($updir, $img, $name, $thumbnail_width, $thumbnail_height, $quality){
	$arr_image_details	= GetImageSize("$updir/$img");
	$original_width		= $arr_image_details[0];
	$original_height	= $arr_image_details[1];
	$a = $thumbnail_width / $thumbnail_height;
  $b = $original_width / $original_height;

	if ($a<$b) {
     $new_width = $thumbnail_width;
     $new_height	= intval($original_height*$new_width/$original_width);
  } else {
     $new_height = $thumbnail_height;
     $new_width	= intval($original_width*$new_height/$original_height);
  }

	if(($original_width <= $thumbnail_width) AND ($original_height <= $thumbnail_height)) {
	  $new_width = $original_width;
	  $new_height = $original_height;
  }
	if($arr_image_details[2]==1) { $imgt = "imagegif"; $imgcreatefrom = "imagecreatefromgif";  }
	if($arr_image_details[2]==2) { $imgt = "imagejpeg"; $imgcreatefrom = "imagecreatefromjpeg";  }
	if($arr_image_details[2]==3) { $imgt = "imagepng"; $imgcreatefrom = "imagecreatefrompng";  }
	if($imgt) {
		$old_image	= $imgcreatefrom("$updir/$img");
		$new_image	= imagecreatetruecolor($new_width, $new_height);
		imagecopyresampled($new_image,$old_image,0,0,0,0,$new_width,$new_height,$original_width,$original_height);
		imagejpeg($new_image,"$updir/$name",$quality);
		imagedestroy($new_image);
	}
}


    public function saveNewUpload(UploadedFile $uploadedFile, $page_id)
    {
        $attachmentName = $uploadedFile->getClientOriginalName();
        $attachmentPath = $this->putFileInStorage($uploadedFile);
        $largestExistingOrder = Attachment::where('uploaded_to', '=', $page_id)->max('order');

        $attachment = Attachment::forceCreate([
            'name'        => $attachmentName,
            'path'        => $attachmentPath,
            'extension'   => $uploadedFile->getClientOriginalExtension(),
            'uploaded_to' => $page_id,
            'created_by'  => user()->id,
            'updated_by'  => user()->id,
            'order'       => $largestExistingOrder + 1,
        ]);

        return $attachment;
    }


function adodb_addslashes($s)
{
	$len = strlen($s);
	if ($len == 0) return "''";
	if (strncmp($s,"'",1) === 0 && substr($s,$len-1) == "'") return $s; // already quoted

	return "'".addslashes($s)."'";
}


    public function testDuplicateAction()
    {
        $client = $this->getClientForAuthenticatedUser(User::ROLE_ADMIN);
        /** @var EntityManager $em */
        $em = $this->getEntityManager();
        $project = $em->find(Project::class, 1);
        $project->setMetaField((new ProjectMeta())->setName('foo')->setValue('bar'));
        $project->setEnd(new \DateTime());
        $em->persist($project);
        $team = new Team();
        $team->addTeamlead($this->getUserByRole(User::ROLE_ADMIN));
        $team->addProject($project);
        $team->setName('project 1');
        $em->persist($team);
        $rate = new ProjectRate();
        $rate->setProject($project);
        $rate->setRate(123.45);
        $em->persist($rate);
        $activity = new Activity();
        $activity->setName('blub');
        $activity->setProject($project);
        $activity->setMetaField((new ActivityMeta())->setName('blub')->setValue('blab'));
        $em->persist($activity);
        $rate = new ActivityRate();
        $rate->setActivity($activity);
        $rate->setRate(123.45);
        $em->persist($rate);
        $em->flush();

        $this->request($client, '/admin/project/1/duplicate');
        $this->assertIsRedirect($client, '/details');
        $client->followRedirect();
        $node = $client->getCrawler()->filter('div.box#project_rates_box');
        self::assertEquals(1, $node->count());
        $node = $client->getCrawler()->filter('div.box#project_rates_box table.dataTable tbody tr:not(.summary)');
        self::assertEquals(1, $node->count());
        self::assertStringContainsString('123.45', $node->text(null, true));
    }


    public function testDuplicateAction()
    {
        $client = $this->getClientForAuthenticatedUser(User::ROLE_ADMIN);
        $this->request($client, '/admin/teams/1/duplicate');
        $this->assertIsRedirect($client, '/edit');
        $client->followRedirect();
        $node = $client->getCrawler()->filter('#team_edit_form_name');
        self::assertEquals(1, $node->count());
        self::assertEquals('Test team [COPY]', $node->attr('value'));
    }


    public function buildView(FormView $view, FormInterface $form, array $options)
    {
        if (!isset($options['api_data'])) {
            return;
        }

        $apiData = $options['api_data'];

        if (!\is_array($apiData)) {
            throw new \InvalidArgumentException('Option "api_data" must be an array for form "' . $form->getName() . '"');
        }

        if (!isset($apiData['select'])) {
            return;
        }

        if (!isset($apiData['route'])) {
            throw new \InvalidArgumentException('Missing "route" option for "api_data" option for form "' . $form->getName() . '"');
        }

        if (!isset($apiData['route_params'])) {
            $apiData['route_params'] = [];
        }

        $formPrefixes = [];
        $parent = $form->getParent();
        do {
            $formPrefixes[] = $parent->getName();
        } while (($parent = $parent->getParent()) !== null);

        $formPrefix = implode('_', array_reverse($formPrefixes));

        $formField = $formPrefix . '_' . $apiData['select'];

        $view->vars['attr'] = array_merge($view->vars['attr'], [
            'data-form-prefix' => $formPrefix,
            'data-related-select' => $formField,
            'data-api-url' => $this->router->generate($apiData['route'], $apiData['route_params']),
        ]);

        if (isset($apiData['empty_route_params'])) {
            $view->vars['attr'] = array_merge($view->vars['attr'], [
                'data-empty-url' => $this->router->generate($apiData['route'], $apiData['empty_route_params']),
            ]);
        }
    }


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


	private function validateCodeInjectionInMetadata()
	{
		if (
			\function_exists('exif_read_data')
			&& \in_array($this->getMimeType(), ['image/jpeg', 'image/tiff'])
			&& \in_array(exif_imagetype($this->path), [IMAGETYPE_JPEG, IMAGETYPE_TIFF_II, IMAGETYPE_TIFF_MM])
		) {
			$imageSize = getimagesize($this->path, $imageInfo);
			if (
				$imageSize
				&& (empty($imageInfo['APP1']) || 0 === strpos($imageInfo['APP1'], 'Exif'))
				&& ($exifdata = exif_read_data($this->path)) && !$this->validateImageMetadata($exifdata)
			) {
				throw new \App\Exceptions\DangerousFile('ERR_FILE_PHP_CODE_INJECTION');
			}
		}
	}


	public function validate($type = false)
	{
		$return = true;
		try {
			if ($type && $this->getShortMimeType(0) !== $type) {
				throw new \App\Exceptions\DangerousFile('ERR_FILE_ILLEGAL_FORMAT');
			}
			$this->checkFile();
			if (!empty($this->validateAllowedFormat)) {
				$this->validateFormat();
			}
			$this->validateCodeInjection();
			if (($type && 'image' === $type) || 'image' === $this->getShortMimeType(0)) {
				$this->validateImage();
			}
		} catch (\Exception $e) {
			$return = false;
			$message = $e->getMessage();
			if (false === strpos($message, '||')) {
				$message = \App\Language::translateSingleMod($message, 'Other.Exceptions');
			} else {
				$params = explode('||', $message);
				$message = \call_user_func_array('vsprintf', [\App\Language::translateSingleMod(array_shift($params), 'Other.Exceptions'), $params]);
			}
			$this->validateError = $message;
			Log::error("Error: {$e->getMessage()} | {$this->getName()} | {$this->getSize()}", __CLASS__);
		}
		return $return;
	}


					$contentType = str_replace('data:', '', $cur);
				}
			}
		} else {


	public function findAddress(App\Request $request)
	{
		$instance = \App\Map\Address::getInstance($request->getByType('type'));
		$response = new Vtiger_Response();
		if ($instance) {
			$response->setResult($instance->find($request->getByType('value', 'Text')));
		}
		$response->emit();
	}


    public function getFileIdentifiersInFolder($folderIdentifier, $useFilters = true, $recursive = false)
    {
        $filters = $useFilters == true ? $this->fileAndFolderNameFilters : [];
        return $this->driver->getFilesInFolder($folderIdentifier, 0, 0, $recursive, $filters);
    }


	public static function newFromRow( $row, Parameters $parameters, \Title $title, $pageNamespace, $pageTitle ) {
		global $wgLang;

		$article = new Article( $title, $pageNamespace );

		$revActorName = null;
		if ( isset( $row['revactor_actor'] ) ) {
			$revActorName = User::newFromActorId( $row['revactor_actor'] )->getName();
		}

		$titleText = $title->getText();
		if ( $parameters->getParameter( 'shownamespace' ) === true ) {
			$titleText = $title->getPrefixedText();
		}
		$replaceInTitle = $parameters->getParameter( 'replaceintitle' );
		if ( is_array( $replaceInTitle ) && count( $replaceInTitle ) === 2 ) {
			$titleText = preg_replace( $replaceInTitle[0], $replaceInTitle[1], $titleText );
		}

		//Chop off title if longer than the 'titlemaxlen' parameter.
		if ( $parameters->getParameter( 'titlemaxlen' ) !== null && strlen( $titleText ) > $parameters->getParameter( 'titlemaxlen' ) ) {
			$titleText = substr( $titleText, 0, $parameters->getParameter( 'titlemaxlen' ) ) . '...';
		}
		if ( $parameters->getParameter( 'showcurid' ) === true && isset( $row['page_id'] ) ) {
			$articleLink = '[' . $title->getLinkURL( [ 'curid' => $row['page_id'] ] ) . ' ' . htmlspecialchars( $titleText ) . ']';
		} else {
			$articleLink = '[[' . ( $parameters->getParameter( 'escapelinks' ) && ( $pageNamespace == NS_CATEGORY || $pageNamespace == NS_FILE ) ? ':' : '' ) . $title->getFullText() . '|' . htmlspecialchars( $titleText ) . ']]';
		}


	public static function init( $settings = false ) {
		if ( $settings === false ) {
			global $wgDplSettings;

			$settings = $wgDplSettings;
		}

		if ( !is_array( $settings ) ) {
			throw new MWException( __METHOD__ . ": Invalid settings passed." );
		}

		self::$settings = array_merge( self::$settings, $settings );
	}


	public static function onRegistration() {
		if ( !defined( 'DPL_VERSION' ) ) {
			define( 'DPL_VERSION', '3.3.5' );
		}
	}


	public static function setupMigration( Parser &$parser ) {
		$parser->setHook( 'Intersection', [ __CLASS__, 'intersectionTag' ] );
		$parser->addTrackingCategory( 'dpl-intersection-tracking-category' );

		self::init();

		return true;
	}


	public static function onParserFirstCallInit( Parser &$parser ) {
		self::init();

		//DPL offers the same functionality as Intersection.  So we register the <DynamicPageList> tag in case LabeledSection Extension is not installed so that the section markers are removed.
		if ( \DPL\Config::getSetting( 'handleSectionTag' ) ) {
			$parser->setHook( 'section', [ __CLASS__, 'dplTag' ] );
		}

		$parser->setHook( 'DPL', [ __CLASS__, 'dplTag' ] );
		$parser->setHook( 'DynamicPageList', [ __CLASS__, 'intersectionTag' ] );

		$parser->setFunctionHook( 'dpl', [ __CLASS__, 'dplParserFunction' ] );
		$parser->setFunctionHook( 'dplnum', [ __CLASS__, 'dplNumParserFunction' ] );
		$parser->setFunctionHook( 'dplvar', [ __CLASS__, 'dplVarParserFunction' ] );
		$parser->setFunctionHook( 'dplreplace', [ __CLASS__, 'dplReplaceParserFunction' ] );
		$parser->setFunctionHook( 'dplchapter', [ __CLASS__, 'dplChapterParserFunction' ] );
		$parser->setFunctionHook( 'dplmatrix', [ __CLASS__, 'dplMatrixParserFunction' ] );

		return true;
	}


	public function __construct() {
		$this->setRichness( Config::getSetting( 'functionalRichness' ) );

		if ( \DynamicPageListHooks::isLikeIntersection() ) {
			$this->data['ordermethod'] = [
				'default'	=> 'categoryadd',
				'values'	=> [
					'categoryadd',
					'lastedit',
					'none'
				]
			];
			$this->data['order'] = [
				'default'	=> 'descending',
				'values'	=> [
					'ascending',
					'descending'
				]
			];
			$this->data['mode'] = [
				'default'	=> 'unordered',
				'values'	=> [
					'none',
					'ordered',
					'unordered'
				]
			];
			$this->data['userdateformat'] = [
				'default' => 'Y-m-d: '
			];
			$this->data['allowcachedresults']['default'] = 'true';
		}
	}


			Variables::setVar( [ '', '', $argName, $argValue ] );
			if ( defined( 'ExtVariables::VERSION' ) ) {
				\ExtVariables::get( $this->parser )->setVarValue( $argName, $argValue );
			}
		}
	}


	private function setHeader( $header ) {
		if ( \DynamicPageListHooks::getDebugLevel() == 5 ) {
			$header = '<pre><nowiki>' . $header;
		}
		$this->header = $this->replaceVariables( $header );
	}


			Variables::setVar( [ '', '', $variable, $value ] );
			if ( defined( 'ExtVariables::VERSION' ) ) {
				\ExtVariables::get( $this->parser )->setVarValue( $variable, $value );
			}
		}
	}


	private function _categoriesminmax( $option ) {
		if ( is_numeric( $option[0] ) ) {
			$this->addWhere( intval( $option[0] ) . ' <= (SELECT count(*) FROM ' . $this->tableNames['categorylinks'] . ' WHERE ' . $this->tableNames['categorylinks'] . '.cl_from=page_id)' );
		}
		if ( is_numeric( $option[1] ) ) {
			$this->addWhere( intval( $option[1] ) . ' >= (SELECT count(*) FROM ' . $this->tableNames['categorylinks'] . ' WHERE ' . $this->tableNames['categorylinks'] . '.cl_from=page_id)' );
		}
	}


	private function _allrevisionsbefore( $option ) {
		$this->addTable( 'revision_actor_temp', 'rev' );
		$this->addSelect(
			[
				'rev.revactor_rev',
				'rev.revactor_timestamp'
			]
		);
		$this->addOrderBy( 'rev.revactor_rev' );
		$this->setOrderDir( 'DESC' );
		$this->addWhere(
			[
				$this->tableNames['page'] . '.page_id = rev.revactor_page',
				'rev.revactor_timestamp < ' . $this->convertTimestamp( $option )
			]
		);
	}


	private function _adduser( $option, $tableAlias = '' ) {
		$tableAlias = ( !empty( $tableAlias ) ? $tableAlias . '.' : '' );
		$this->addSelect(
			[
				$tableAlias . 'revactor_actor',
			]
		);
	}


			$this->where = array_merge( $this->where, $where );
		} else {
			throw new \MWException( __METHOD__ . ': An invalid where clause was passed.' );
			return false;
		}
		return true;
	}


	private function _notcreatedby( $option ) {
		$this->addTable( 'revision', 'no_creation_rev' );
		$this->addTable( 'revision_actor_temp', 'no_creation_rev_actor' );
		$user = new \User;

		$this->addWhere( $this->DB->addQuotes( $user->newFromName( $option )->getActorId() ) . ' != no_creation_rev_actor.revactor_actor AND no_creation_rev_actor.revactor_page = page_id AND no_creation_rev.rev_parent_id = 0' );
	}


	private function _minrevisions( $option ) {
		$this->addWhere( "((SELECT count(rev_aux2.revactor_page) FROM {$this->tableNames['revision_actor_temp']} AS rev_aux2 WHERE rev_aux2.revactor_page = {$this->tableNames['page']}.page_id) >= {$option})" );
	}


	public function setListAttributes( $attributes ) {
		$this->listAttributes = \Sanitizer::fixTagAttributes( $attributes, 'ul' );
	}


	public static function newFromStyle( $style, \DPL\Parameters $parameters, \Parser $parser ) {
		$style = strtolower( $style );
		switch ( $style ) {
			case 'category':
				$class = 'CategoryList';
				break;
			case 'definition':
				$class = 'DefinitionList';
				break;
			case 'gallery':
				$class = 'GalleryList';
				break;
			case 'inline':
				$class = 'InlineList';
				break;
			case 'ordered':
				$class = 'OrderedList';
				break;
			case 'subpage':
				$class = 'SubPageList';
				break;
			default:
			case 'unordered':
				$class = 'UnorderedList';
				break;
			case 'userformat':
				$class = 'UserFormatList';
				break;
		}
		$class = '\DPL\Lister\\' . $class;

		return new $class( $parameters, $parser );
	}


	public function __construct( \DPL\Parameters $parameters, \Parser $parser ) {
		$this->setHeadListAttributes( $parameters->getParameter( 'hlistattr' ) );
		$this->setHeadItemAttributes( $parameters->getParameter( 'hitemattr' ) );
		$this->setListAttributes( $parameters->getParameter( 'listattr' ) );
		$this->setItemAttributes( $parameters->getParameter( 'itemattr' ) );
		$this->setDominantSectionCount( $parameters->getParameter( 'dominantsection' ) );
		$this->setTemplateSuffix( $parameters->getParameter( 'defaulttemplatesuffix' ) );
		$this->setTrimIncluded( $parameters->getParameter( 'includetrim' ) );
		$this->setTableSortColumn( $parameters->getParameter( 'tablesortcol' ) );
		$this->setTableSortMethod($parameters->getParameter('tablesortmethod'));
		$this->setTitleMaxLength( $parameters->getParameter( 'titlemaxlen' ) );
		$this->setEscapeLinks( $parameters->getParameter( 'escapelinks' ) );
		$this->setSectionSeparators( $parameters->getParameter( 'secseparators' ) );
		$this->setMultiSectionSeparators( $parameters->getParameter( 'multisecseparators' ) );
		$this->setIncludePageText( $parameters->getParameter( 'incpage' ) );
		$this->setIncludePageMaxLength( $parameters->getParameter( 'includemaxlen' ) );
		$this->setPageTextMatch( (array)$parameters->getParameter( 'seclabels' ) );
		$this->setPageTextMatchRegex( (array)$parameters->getParameter( 'seclabelsmatch' ) );
		$this->setPageTextMatchNotRegex( (array)$parameters->getParameter( 'seclabelsnotmatch' ) );
		$this->setIncludePageParsed( $parameters->getParameter( 'incparsed' ) );
		$this->parameters = $parameters;
		$this->parser = clone $parser;
	}


	public function formatItem( Article $article, $pageText = null ) {
		$item = '';

		if ( $pageText !== null ) {
			//Include parsed/processed wiki markup content after each item before the closing tag.
			$item .= $pageText;
		}

		$item = $this->getItemStart() . $item . $this->getItemEnd();

		$item = $this->replaceTagParameters( $item, $article );

		return $item;
	}


    private static function retrieveClosurePattern($pure, $closureName)
    {
        $pattern = '/';
        if (!$pure) {
            $pattern .= preg_quote(self::$registeredDelimiters[0]) . "\s*";
        }
        $pattern .= "$closureName\(([a-z0-9,\.\s]+)\)";
        if (!$pure) {
            $pattern .= "\s*" . preg_quote(self::$registeredDelimiters[1]);
        }
        return $pattern . "/i";
    }


    public static function getUploadFileFromPost($siteID, $subDirectory, $id)
    {
        if (isset($_FILES[$id]))
        {
            if (!@file_exists($_FILES[$id]['tmp_name']))
            {
                // File was removed, accessed from another window, or no longer exists
                return false;
            }

            if (!eval(Hooks::get('FILE_UTILITY_SPACE_CHECK'))) return;

            $uploadPath = FileUtility::getUploadPath($siteID, $subDirectory);
            $newFileName = $_FILES[$id]['name'];

            // Could just while(file_exists) it, but I'm paranoid of infinate loops
            // Shouldn't have 1000 files of the same name anyway
            for ($i = 0; @file_exists($uploadPath . '/' . $newFileName) && $i < 1000; $i++)
            {
                $mp = explode('.', $newFileName);
                $fileNameBase = implode('.', array_slice($mp, 0, count($mp)-1));
                $fileNameExt = $mp[count($mp)-1];

                if (preg_match('/(.*)_Copy([0-9]{1,3})$/', $fileNameBase, $matches))
                {
                    // Copy already appending, increase the #
                    $fileNameBase = sprintf('%s_Copy%d', $matches[1], intval($matches[2]) + 1);
                }
                else
                {
                    $fileNameBase .= '_Copy1';
                }

                $newFileName = $fileNameBase . '.' . $fileNameExt;
            }

            if (@move_uploaded_file($_FILES[$id]['tmp_name'], $uploadPath . '/' . $newFileName) &&
                @chmod($uploadPath . '/' . $newFileName, 0777))
            {
                return $newFileName;
            }
        }

        return false;
    }


    public static function makeSafeFilename($filename)
    {
        /* Strip out *nix directories. */
        $filenameParts = explode('/', $filename);
        $filename = end($filenameParts);

        /* Strip out Windows directories. */
        $filenameParts = explode('\\', $filename);
        $filename = end($filenameParts);

        /* Strip out non-ASCII characters. */
        for ($i = 0; $i < strlen($filename); $i++)
        {
            if (ord($filename[$i]) >= 128 || ord($filename[$i]) < 32)
            {
                $filename[$i] = '_';
            }
        }

        /* Is the file extension safe? */
        $fileExtension = self::getFileExtension($filename);
        if (in_array($fileExtension, $GLOBALS['badFileExtensions']))
        {
            $filename .= '.txt';
        }

        return $filename;
    }


    public function create($data)
    {
        if ($this->securityController->isWikiHibernated()) {
            throw new \Exception(_t('WIKI_IN_HIBERNATION'));
        }
        // If ID is not set or if it is already used, find a new ID
        if (!$data['bn_id_nature'] || $this->getOne($data['bn_id_nature'])) {
            $data['bn_id_nature'] = $this->findNewId();
        }

        return $this->dbService->query('INSERT INTO ' . $this->dbService->prefixTable('nature')
            . '(`bn_id_nature` ,`bn_ce_i18n` ,`bn_label_nature` ,`bn_template` ,`bn_description` ,`bn_sem_context` ,`bn_sem_type` ,`bn_sem_use_template` ,`bn_condition`)'
            . ' VALUES (' . $data['bn_id_nature'] . ', "fr-FR", "'
            . addslashes(_convert($data['bn_label_nature'], YW_CHARSET, true)) . '","'
            . addslashes(_convert($data['bn_template'], YW_CHARSET, true)) . '", "'
            . addslashes(_convert($data['bn_description'], YW_CHARSET, true)) . '", "'
            . addslashes(_convert($data['bn_sem_context'], YW_CHARSET, true)) . '", "'
            . addslashes(_convert($data['bn_sem_type'], YW_CHARSET, true)) . '", '
            . (isset($data['bn_sem_use_template']) ? '1' : '0') . ', "'
            . addslashes(_convert($data['bn_condition'], YW_CHARSET, true)) . '")');


	function handleFormSubmission(&$request, &$output, &$session) {
		if ($request->getText('action')) {
			handleRequestActionSubmission('admin', $this, $session);
		} else if ($request->getText('blockSubmit')) {
			$this->handleBlockFormSubmission($request, $output, $session);
		} else if ($request->getText('unblockSubmit')) {
			$this->handleUnblockFormSubmission($request, $output, $session);
		} else if ($request->getText('bypassAddUsername') || $request->getText('bypassRemoveUsername')) { //TODO: refactor to move all the subpages into their own files
			$bypassPage = new RequirementsBypassPage($this);
			$bypassPage->handleFormSubmission();
		}
	}


function append_token_to_url()
{
	return '/&token_submit=' . $_SESSION['Token'];
}


	public function getNbOfVisibleMenuEntries()
	{
		$nb = 0;
		foreach ($this->liste as $val) {
			//if (dol_eval($val['enabled'], 1)) $nb++;
			if (!empty($val['enabled'])) {
				$nb++; // $val['enabled'] is already evaluated to 0 or 1, no need for dol_eval()
			}
		}
		return $nb;
	}


    private function invertedSection($nodes, $id, $filters, $level)
    {
        $method  = $this->getFindMethod($id);
        $id      = var_export($id, true);
        $filters = $this->getFilters($filters, $level);

        return sprintf($this->prepare(self::INVERTED_SECTION, $level), $id, $method, $id, $filters, $this->walk($nodes, $level));
    }


            $schedules[$scheduleCode] = $this->model->createScheduleItem($scheduleCode);
        }

        return $this->schedulesCache = $schedules;
    }


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


	public function approvedFileExtension($filename, $type = 'image')
	{
		$ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
		if ($type == 'image') {
			switch ($ext) {
				case 'gif':
				case 'png':
				case 'jpeg':
				case 'jpg':
				case 'svg':
					return true;
				default:
					return false;
			}
		} elseif ($type == 'cert') {
			switch ($ext) {
				case 'pem':
					return true;
				default:
					return false;
			}
		}
	}


function get_rsvpversion() {
	return '9.2.5';
}


    private function userAuth()
    {
        $user = new User();
        $nick = $this->request->request->get('fsNick', '');
        if ($nick === '') {
            return $this->cookieAuth($user);
        }

        if ($user->loadFromCode($nick) && $user->enabled) {
            if ($user->verifyPassword($this->request->request->get('fsPassword'))) {
                // Execute actions from User model extensions
                $user->pipe('login');

                $this->updateCookies($user, true);
                ToolBox::ipFilter()->clear();
                ToolBox::i18nLog()->debug('login-ok', ['%nick%' => $user->nick]);
                ToolBox::log()::setContext('nick', $user->nick);
                return $user;
            }

            $this->ipWarning();
            ToolBox::i18nLog()->warning('login-password-fail');
            return false;
        }

        $this->ipWarning();
        ToolBox::i18nLog()->warning('login-user-not-found', ['%nick%' => $nick]);
        return false;
    }


    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 rules()
    {
        return [
            'name' => 'required',
            'email' => 'required|email',
            'address' => '',
            'primary_number' => 'numeric',
            'secondary_number' => 'numeric',
            'password' => 'required|min:5|confirmed',
            'password_confirmation' => 'required|min:5',
            'image_path' => '',
            'roles' => 'required',
            'departments' => 'required'
        ];
    }


	public function &storeicms_ipf_ObjectD() {
		return $this->storeicms_ipf_Object(true);
	}


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

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


	public function __construct($handler) {
		$this->handler=$handler;
	}


				$this->run('rm', $item, '-r');
			}

			return $this;
		}


				$this->run('mv', $from, $to);
			}

			return $this;
		}


    public function testNotRemoveAuthorizationHeaderOnRedirect()
    {
        $mock = new MockHandler([
            new Response(302, ['Location' => 'http://example.com/2']),
            static function (RequestInterface $request) {
                self::assertTrue($request->hasHeader('Authorization'));
                return new Response(200);
            }
        ]);
        $handler = HandlerStack::create($mock);
        $client = new Client(['handler' => $handler]);
        $client->get('http://example.com?a=b', ['auth' => ['testuser', 'testpass']]);
    }


function update_config() {
    var conf_ignore = "binlog_ignore_db=";
    var conf_do = "binlog_do_db=";
    var database_list = $('#db_select option:selected:first').val();
    $('#db_select option:selected:not(:first)').each(function() {
        database_list += ',' + $(this).val();
    });

    if ($('#db_select option:selected').size() == 0) {
        $('#rep').html(conf_prefix);
    } else if ($('#db_type option:selected').val() == 'all') {
        $('#rep').html(conf_prefix + conf_ignore + database_list);
    } else {
        $('#rep').html(conf_prefix + conf_do + database_list);
    }
}


function PMA_current_version()
{
    var current = parseVersionString(pmaversion);
    var latest = parseVersionString(PMA_latest_version);
    var version_information_message = PMA_messages['strLatestAvailable'] + ' ' + PMA_latest_version;
    if (latest > current) {
        var message = $.sprintf(PMA_messages['strNewerVersion'], PMA_latest_version, PMA_latest_date);
        if (Math.floor(latest / 10000) == Math.floor(current / 10000)) {
            /* Security update */
            klass = 'error';
        } else {
            klass = 'notice';
        }
        $('#maincontainer').after('
' + message + '
');
    }
    if (latest == current) {
        version_information_message = ' (' + PMA_messages['strUpToDate'] + ')';
    }
    $('#li_pma_version').append(version_information_message);
}


function goToFinish1NF()
{
    if (normalizeto !== '1nf') {
        goTo2NFStep1();
        return true;
    }
    $("#mainContent legend").html(PMA_messages.strEndStep);
    $("#mainContent h4").html(
        "<h3>" + PMA_sprintf(PMA_messages.strFinishMsg, PMA_commonParams.get('table')) + "</h3>"
    );
    $("#mainContent p").html('');
    $("#mainContent #extra").html('');
    $("#mainContent #newCols").html('');
    $('.tblFooters').html('');
}


  this.switch_task = function(task)
  {
    if (this.task === task && task != 'mail')
      return;

    var url = this.get_task_url(task);

    if (task == 'mail')
      url += '&_mbox=INBOX';
    else if (task == 'logout' && !this.env.server_error) {
      url += '&_token=' + this.env.request_token;
      this.clear_compose_data();
    }

    this.redirect(url);
  };


Installer.prototype.readGlobalPackageData = function (cb) {
  validate('F', arguments)
  log.silly('install', 'readGlobalPackageData')
  var self = this
  this.loadArgMetadata(iferr(cb, function () {
    correctMkdir(self.where, iferr(cb, function () {
      var pkgs = {}
      self.args.forEach(function (pkg) {
        pkgs[pkg.name] = true
      })
      readPackageTree(self.where, function (ctx, kid) { return ctx.parent || pkgs[kid] }, iferr(cb, function (currentTree) {
        self.currentTree = currentTree
        return cb()
      }))
    }))
  }))
}


  function restoreOldNodeModules () {
    if (!movedDestAway) return
    return readdir(path.join(delpath, 'node_modules')).catch(() => []).then((modules) => {
      if (!modules.length) return
      return correctMkdir(path.join(pkg.realpath, 'node_modules')).then(() => Bluebird.map(modules, (file) => {
        const from = path.join(delpath, 'node_modules', file)
        const to = path.join(pkg.realpath, 'node_modules', file)
        return move(from, to, moveOpts)
      }))
    })
  }


		format: function (element, content) {
			var author = '',
				$elm = $(element),
				$cite = $elm.children('cite').first();
			$cite.html($cite.text());

			if ($cite.length === 1 || $elm.data('author')) {
				author = $cite.text() || $elm.data('author');

				$elm.data('author', author);
				$cite.remove();

				content = this.elementToBbcode(element);
				author = '=' + author.replace(/(^\s+|\s+$)/g, '');

				$elm.prepend($cite);
			}

			if ($elm.data('pid'))
				author += " pid='" + $elm.data('pid') + "'";

			if ($elm.data('dateline'))
				author += " dateline='" + $elm.data('dateline') + "'";

			return '[quote' + author + ']' + content + '[/quote]';
		},


link: function(scope, element, attrs) {

          var width = 120;
          var height = 39;

          var div = $('
A
').css({
            position: 'absolute',
            left: -1000,
            top: -1000,
            display: 'block',
            padding: 0,
            margin: 0,
            'font-family': 'monospace'
          }).appendTo($('body'));

          var charWidth = div.width();
          var charHeight = div.height();

          div.remove();

          // compensate for internal horizontal padding
          var cssWidth = width * charWidth + 20;
          // Add an extra line for the status bar and divider
          var cssHeight = (height * charHeight) + charHeight + 2;

          log.debug("desired console size in characters, width: ", width, " height: ", height);
          log.debug("console size in pixels, width: ", cssWidth, " height: ", cssHeight);
          log.debug("character size in pixels, width: ", charWidth, " height: ", charHeight);

          element.css({
            width: cssWidth,
            height: cssHeight,
            'min-width': cssWidth,
            'min-height': cssHeight
          });

          var authHeader = Core.getBasicAuthHeader(userDetails.username, userDetails.password);

          gogo.Terminal(element.get(0), width, height, authHeader);

          scope.$on("$destroy", function(e) {
            document.onkeypress = null;
            document.onkeydown = null;
          });

        }


module.exports = function (src, file) {
    if (typeof src !== 'string') src = String(src);

    try {
        Function(src);
        return;
    }
    catch (err) {
        if (err.constructor.name !== 'SyntaxError') throw err;
        return errorInfo(src, file);
    }
};


    resolve: function resolve(hostname) {
        var output,
            nodeBinary = process.execPath,
            scriptPath = path.join(__dirname, "../scripts/dns-lookup-script"),
            response,
            cmd = util.format('"%s" "%s" %s', nodeBinary, scriptPath, hostname);

        response = shell.exec(cmd, {silent: true});
        if (response && response.code === 0) {
            output = response.output;
            if (output && net.isIP(output)) {
                return output;
            }
        }
        debug('hostname', "fail to resolve hostname " + hostname);
        return null;
    }


	_create: function() {

		if ( this.options.helper === "original" ) {
			this._setPositionRelative();
		}
		if (this.options.addClasses){
			this.element.addClass("ui-draggable");
		}
		if (this.options.disabled){
			this.element.addClass("ui-draggable-disabled");
		}
		this._setHandleClassName();

		this._mouseInit();
	},


	_getItemsAsjQuery: function(connected) {

		var i, j, cur, inst,
			items = [],
			queries = [],
			connectWith = this._connectWith();

		if(connectWith && connected) {
			for (i = connectWith.length - 1; i >= 0; i--){
				cur = $(connectWith[i], this.document[0]);
				for ( j = cur.length - 1; j >= 0; j--){
					inst = $.data(cur[j], this.widgetFullName);
					if(inst && inst !== this && !inst.options.disabled) {
						queries.push([$.isFunction(inst.options.items) ? inst.options.items.call(inst.element) : $(inst.options.items, inst.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"), inst]);
					}
				}
			}
		}

		queries.push([$.isFunction(this.options.items) ? this.options.items.call(this.element, null, { options: this.options, item: this.currentItem }) : $(this.options.items, this.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"), this]);

		function addItems() {
			items.push( this );
		}
		for (i = queries.length - 1; i >= 0; i--){
			queries[i][0].each( addItems );
		}

		return $(items);

	},


function _c(a,b,c){var d={mm:"munutenn",MM:"miz",dd:"devezh"};return a+" "+cd(d[c],a)}function ad(a){switch(bd(a)){case 1:case 3:case 4:case 5:case 9:return a+" bloaz";default:return a+" vloaz"}}function bd(a){return a>9?bd(a%10):a}function cd(a,b){return 2===b?dd(a):a}function dd(a){var b={m:"v",b:"v",d:"z"};return void 0===b[a.charAt(0)]?a:b[a.charAt(0)]+a.substring(1)}


function Zc(a,b){var c=a.split("_");return b%10===1&&b%100!==11?c[0]:b%10>=2&&4>=b%10&&(10>b%100||b%100>=20)?c[1]:c[2]}function $c(a,b,c){var d={mm:b?"хвіліна_хвіліны_хвілін":"хвіліну_хвіліны_хвілін",hh:b?"гадзіна_гадзіны_гадзін":"гадзіну_гадзіны_гадзін",dd:"дзень_дні_дзён",MM:"месяц_месяцы_месяцаў",yy:"год_гады_гадоў"};return"m"===c?b?"хвіліна":"хвіліну":"h"===c?b?"гадзіна":"гадзіну":a+" "+Zc(d[c],+a)}


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


function md(a,b,c){var d=a+" ";switch(c){case"m":return b?"jedna minuta":"jedne minute";case"mm":return d+=1===a?"minuta":2===a||3===a||4===a?"minute":"minuta";case"h":return b?"jedan sat":"jednog sata";case"hh":return d+=1===a?"sat":2===a||3===a||4===a?"sata":"sati";case"dd":return d+=1===a?"dan":"dana";case"MM":return d+=1===a?"mjesec":2===a||3===a||4===a?"mjeseca":"mjeseci";case"yy":return d+=1===a?"godina":2===a||3===a||4===a?"godine":"godina"}}function nd(a,b,c,d){var e=a;switch(c){case"s":return d||b?"néhány másodperc":"néhány másodperce";case"m":return"egy"+(d||b?" perc":" perce");case"mm":return e+(d||b?" perc":" perce");case"h":return"egy"+(d||b?" óra":" órája");case"hh":return e+(d||b?" óra":" órája");case"d":return"egy"+(d||b?" nap":" napja");case"dd":return e+(d||b?" nap":" napja");case"M":return"egy"+(d||b?" hónap":" hónapja");case"MM":return e+(d||b?" hónap":" hónapja");case"y":return"egy"+(d||b?" év":" éve");case"yy":return e+(d||b?" év":" éve")}return""}function od(a){return(a?"":"[múlt] ")+"["+ug[this.day()]+"] LT[-kor]"}


	function _fnBindAction( n, oData, fn )
	{
		$(n)
			.bind( 'click.DT', oData, function (e) {
					n.blur(); // Remove focus outline for mouse users
					fn(e);
				} )
			.bind( 'keypress.DT', oData, function (e){
				if ( e.which === 13 ) {
					fn(e);
				} } )
			.bind( 'selectstart.DT', function () {
				/* Take the brutal approach to cancelling text selection */
				return false;
				} );
	}


if(i===k)return a.iDrawError!=e&&null===j&&(K(a,0,"Requested unknown parameter "+("function"==typeof f.mData?"{function}":"'"+f.mData+"'")+" for row "+b+", column "+c,4),a.iDrawError=e),j;if((i===g||null===i)&&null!==j)i=j;else if("function"===typeof i)return i.call(g);return null===i&&"display"==d?"":i}function jb(a,b,c,d){a.aoColumns[c].fnSetData(a.aoData[b]._aData,d,{settings:a,row:b,col:c})}function La(a){return h.map(a.match(/(\\.|[^\.])+/g)||[""],function(a){return a.replace(/\\./g,".")})}function Q(a){if(h.isPlainObject(a)){var b=


    function parseErrors(series, i){

        var points = series.datapoints.points;

        // read errors from points array
        var exl = null,
                exu = null,
                eyl = null,
                eyu = null;
        var xerr = series.points.xerr,
                yerr = series.points.yerr;

        var eb = series.points.errorbars;
        // error bars - first X
        if (eb == 'x' || eb == 'xy') {
            if (xerr.asymmetric) {
                exl = points[i + 2];
                exu = points[i + 3];
                if (eb == 'xy')
                    if (yerr.asymmetric){
                        eyl = points[i + 4];
                        eyu = points[i + 5];
                    } else eyl = points[i + 4];
            } else {
                exl = points[i + 2];
                if (eb == 'xy')
                    if (yerr.asymmetric) {
                        eyl = points[i + 3];
                        eyu = points[i + 4];
                    } else eyl = points[i + 3];
            }
        // only Y
        } else if (eb == 'y')
            if (yerr.asymmetric) {
                eyl = points[i + 2];
                eyu = points[i + 3];
            } else eyl = points[i + 2];

        // symmetric errors?
        if (exu == null) exu = exl;
        if (eyu == null) eyu = eyl;

        var errRanges = [exl, exu, eyl, eyu];
        // nullify if not showing
        if (!xerr.show){
            errRanges[0] = null;
            errRanges[1] = null;
        }
        if (!yerr.show){
            errRanges[2] = null;
            errRanges[3] = null;
        }
        return errRanges;
    }


Mocha.prototype.grep = function(re){
  this.options.grep = 'string' == typeof re
    ? new RegExp(utils.escapeRegexp(re))
    : re;
  return this;
};


exports.parseQuery = function(qs){
  return exports.reduce(qs.replace('?', '').split('&'), function(obj, pair){
    var i = pair.indexOf('=')
      , key = pair.slice(0, i)
      , val = pair.slice(++i);

    obj[key] = decodeURIComponent(val);
    return obj;
  }, {});
};


Hook.prototype.error = function(err){
  if (0 == arguments.length) {
    var err = this._error;
    this._error = null;
    return err;
  }

  this._error = err;
};


function Base(runner) {
  var self = this
    , stats = this.stats = { suites: 0, tests: 0, passes: 0, pending: 0, failures: 0 }
    , failures = this.failures = [];

  if (!runner) return;
  this.runner = runner;

  runner.stats = stats;

  runner.on('start', function(){
    stats.start = new Date;
  });

  runner.on('suite', function(suite){
    stats.suites = stats.suites || 0;
    suite.root || stats.suites++;
  });

  runner.on('test end', function(test){
    stats.tests = stats.tests || 0;
    stats.tests++;
  });

  runner.on('pass', function(test){
    stats.passes = stats.passes || 0;

    var medium = test.slow() / 2;
    test.speed = test.duration > test.slow()
      ? 'slow'
      : test.duration > medium
        ? 'medium'
        : 'fast';

    stats.passes++;
  });

  runner.on('fail', function(test, err){
    stats.failures = stats.failures || 0;
    stats.failures++;
    test.err = err;
    failures.push(test);
  });

  runner.on('end', function(){
    stats.end = new Date;
    stats.duration = new Date - stats.start;
  });

  runner.on('pending', function(){
    stats.pending++;
  });
}


function NyanCat(runner) {
  Base.call(this, runner);
  var self = this
    , stats = this.stats
    , width = Base.window.width * .75 | 0
    , rainbowColors = this.rainbowColors = self.generateColors()
    , colorIndex = this.colorIndex = 0
    , numerOfLines = this.numberOfLines = 4
    , trajectories = this.trajectories = [[], [], [], []]
    , nyanCatWidth = this.nyanCatWidth = 11
    , trajectoryWidthMax = this.trajectoryWidthMax = (width - nyanCatWidth)
    , scoreboardWidth = this.scoreboardWidth = 5
    , tick = this.tick = 0
    , n = 0;

  runner.on('start', function(){
    Base.cursor.hide();
    self.draw();
  });

  runner.on('pending', function(test){
    self.draw();
  });

  runner.on('pass', function(test){
    self.draw();
  });

  runner.on('fail', function(test, err){
    self.draw();
  });

  runner.on('end', function(){
    Base.cursor.show();
    for (var i = 0; i < self.numberOfLines; i++) write('\n');
    self.epilogue();
  });
}


Mocha.prototype.reporter = function(reporter){
  if ('function' == typeof reporter) {
    this._reporter = reporter;
  } else {
    reporter = reporter || 'dot';
    var _reporter;
    try { _reporter = require('./reporters/' + reporter); } catch (err) {};
    if (!_reporter) try { _reporter = require(reporter); } catch (err) {};
    if (!_reporter && reporter === 'teamcity')
      console.warn('The Teamcity reporter was moved to a package named ' +
        'mocha-teamcity-reporter ' +
        '(https://npmjs.org/package/mocha-teamcity-reporter).');
    if (!_reporter) throw new Error('invalid reporter "' + reporter + '"');
    this._reporter = _reporter;
  }
  return this;
};


    context.describe.skip = function(title, fn){
      var suite = Suite.create(suites[0], title);
      suite.pending = true;
      suites.unshift(suite);
      fn.call(suite);
      suites.shift();
    };


Mocha.prototype.run = function(fn){
  if (this.files.length) this.loadFiles();
  var suite = this.suite;
  var options = this.options;
  var runner = new exports.Runner(suite);
  var reporter = new this._reporter(runner);
  runner.ignoreLeaks = false !== options.ignoreLeaks;
  runner.asyncOnly = options.asyncOnly;
  if (options.grep) runner.grep(options.grep, options.invert);
  if (options.globals) runner.globals(options.globals);
  if (options.growl) this._growl(runner, reporter);
  exports.reporters.Base.useColors = options.useColors;
  exports.reporters.Base.inlineDiffs = options.useInlineDiffs;
  return runner.run(fn);
};


  function next(err, errSuite) {
    // if we bail after first err
    if (self.failures && suite._bail) return fn();

    if (self._abort) return fn();

    if (err) return hookErr(err, errSuite, true);

    // next test
    test = tests.shift();

    // all done
    if (!test) return fn();

    // grep
    var match = self._grep.test(test.fullTitle());
    if (self._invert) match = !match;
    if (!match) return next();

    // pending
    if (test.pending) {
      self.emit('pending', test);
      self.emit('test end', test);
      return next();
    }

    // execute test and hook(s)
    self.emit('test', self.test = test);
    self.hookDown('beforeEach', function(err, errSuite){

      if (err) return hookErr(err, errSuite, false);

      self.currentRunnable = self.test;
      self.runTest(function(err){
        test = self.test;

        if (err) {
          self.fail(test, err);
          self.emit('test end', test);
          return self.hookUp('afterEach', next);
        }

        test.state = 'passed';
        self.emit('pass', test);
        self.emit('test end', test);
        self.hookUp('afterEach', next);
      });
    });
  }


Runnable.prototype.globals = function(arr){
  var self = this;
  this._allowedGlobals = arr;
};


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


Suite.prototype.bail = function(bail){
  if (0 == arguments.length) return this._bail;
  debug('bail %s', bail);
  this._bail = bail;
  return this;
};


exports.files = function(dir, ret){
  ret = ret || [];

  fs.readdirSync(dir)
  .filter(ignored)
  .forEach(function(path){
    path = join(dir, path);
    if (fs.statSync(path).isDirectory()) {
      exports.files(path, ret);
    } else if (path.match(/\.(js|coffee|litcoffee|coffee.md)$/)) {
      ret.push(path);
    }
  });

  return ret;
};


function fragment(html) {
  var args = arguments
    , div = document.createElement('div')
    , i = 1;

  div.innerHTML = html.replace(/%([se])/g, function(_, type){
    switch (type) {
      case 's': return String(args[i++]);
      case 'e': return escape(args[i++]);
    }
  });

  return div.firstChild;
}


  show: function(){
    isatty && process.stdout.write('\u001b[?25h');
  },


Mocha.prototype.slow = function(slow){
  this.suite.slow(slow);
  return this;
};


require.register = function (path, fn){
    require.modules[path] = fn;
  };


Mocha.prototype.addFile = function(file){
  this.files.push(file);
  return this;
};


help = function() {
			// help tab
			html.push('
');
			html.push('DON\'T PANIC');
			html.push('
');
			// end help
		},


	this.hideinfo = function() {
		this.info.stop(true).hide();
	}


			item = function(label, icon, callback) {
				return $(tpl.replace('{icon}', icon ? 'elfinder-button-icon-'+icon : '').replace('{label}', label))
					.click(function(e) {
						e.stopPropagation();
						e.preventDefault();
						callback();
					})
			},


			unselectAll = function() {
				if (selectedFiles.length) {
					selectLock = false;
					selectedFiles = [];
					cwd.find('[id].'+clSelected).trigger(evtUnselect);
					trigger();
				}
			},


	isPerm = function(perm){
		return (!isNaN(parseInt(perm, 8) && parseInt(perm, 8) <= 511) || perm.match(/^([r-][w-][x-]){3}$/i));
	};


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

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

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

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

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

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

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

}


	this.autoSync = function(stop) {
		var sync;
		if (self.options.sync >= 1000) {
			if (syncInterval) {
				clearTimeout(syncInterval);
				syncInterval = null;
				self.trigger('autosync', {action : 'stop'});
			}
			if (stop || !self.options.syncStart) {
				return;
			}
			// run interval sync
			sync = function(start){
				var timeout;
				if (cwdOptions.syncMinMs && (start || syncInterval)) {
					start && self.trigger('autosync', {action : 'start'});
					timeout = Math.max(self.options.sync, cwdOptions.syncMinMs);
					syncInterval && clearTimeout(syncInterval);
					syncInterval = setTimeout(function() {
						var dosync = true, hash = cwd, cts;
						if (cwdOptions.syncChkAsTs && (cts = files[hash].ts)) {
							self.request({
								data           : {cmd : 'info', targets : [hash], compare : cts, reload : 1},
								preventDefault : true
							})
							.done(function(data){
								var ts;
								dosync = true;
								if (data.compare) {
									ts = data.compare;
									if (ts == cts) {
										dosync = false;
									}
								}
								if (dosync) {
									self.sync(hash).always(function(){
										if (ts) {
											// update ts for cache clear etc.
											files[hash].ts = ts;
										}
										sync();
									});
								} else {
									sync();
								}
							})
							.fail(function(error){
								if (error && error != 'errConnect') {
									self.error(error);
								} else {
									syncInterval = setTimeout(function() {
										sync();
									}, timeout);
								}
							});
						} else {
							self.sync(cwd, true).always(function(){
								sync();
							});
						}
					}, timeout);
				}
			};
			sync(true);
		}
	};


	cookie : function(name, value) {
		var d, o, c, i;

		name = 'elfinder-'+name+this.id;

		if (value === void(0)) {
			if (document.cookie && document.cookie != '') {
				c = document.cookie.split(';');
				name += '=';
				for (i=0; i<c.length; i++) {
					c[i] = $.trim(c[i]);
					if (c[i].substring(0, name.length) == name) {
						return decodeURIComponent(c[i].substring(name.length));
					}
				}
			}
			return '';
		}

		o = $.extend({}, this.options.cookie);
		if (value === null) {
			value = '';
			o.expires = -1;
		}
		if (typeof(o.expires) == 'number') {
			d = new Date();
			d.setTime(d.getTime()+(o.expires * 86400000));
			o.expires = d;
		}
		document.cookie = name+'='+encodeURIComponent(value)+'; expires='+o.expires.toUTCString()+(o.path ? '; path='+o.path : '')+(o.domain ? '; domain='+o.domain : '')+(o.secure ? '; secure' : '');
		return value;
	},


			scrollToView = function(o) {
				var ftop    = o.position().top,
					fheight = o.outerHeight(true),
					wtop    = wrapper.scrollTop(),
					wheight = wrapper.innerHeight();

				if (ftop + fheight > wtop + wheight) {
					wrapper.scrollTop(parseInt(ftop + fheight - wheight));
				} else if (ftop < wtop) {
					wrapper.scrollTop(ftop);
				}
			},


	this.isCommandEnabled = function(name, dstHash) {
		var disabled;
		if (dstHash && self.root(dstHash) !== cwd) {
			disabled = [];
			$.each(self.disabledCmds, function(i, v){
				if (dstHash.indexOf(i, 0) == 0) {
					disabled = v;
					return false;
				}
			});
		} else {
			disabled = cwdOptions.disabled;
		}
		return this._commands[name] ? $.inArray(name, disabled) === -1 : false;
	}


	this.restoreSize = function() {
		this.resize(width, 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();
					});
				}


					rotateable = function(destroy) {
						if ($.fn.draggable && $.fn.resizable) {
							if (destroy) {
								imgr.hide();
							}
							else {
								imgr.show()
									.width(rwidth)
									.height(rheight)
									.css('margin-top', (pheight-rheight)/2 + 'px')
									.css('margin-left', (pwidth-rwidth)/2 + 'px');

							}
						}
					},


			geturl = function(hash){
				var turl = '';
				$.each(self.tmbUrls, function(i, u){
					if (hash.indexOf(i) === 0) {
						turl = self.tmbUrls[i];
						return false;
					}
				});
				return turl;
			},


		var IETransform = function(element,transform){

			var r;
			var m11 = 1;
			var m12 = 1;
			var m21 = 1;
			var m22 = 1;

			if (typeof element.style['msTransform'] != 'undefined'){
				return true;
			}

			StaticToAbsolute(element);

			r = transform.match(/rotate\((.*?)\)/);
			var rotate =  ( r && r[1])	?	parseInt(r[1])	:	0;

			rotate = rotate % 360;
			if (rotate < 0) rotate = 360 + rotate;

			var radian= rotate * Math.PI / 180;
			var cosX =Math.cos(radian);
			var sinY =Math.sin(radian);

			m11 *= cosX;
			m12 *= -sinY;
			m21 *= sinY;
			m22 *= cosX;

			element.style.filter =  (element.style.filter || '').replace(/progid:DXImageTransform\.Microsoft\.Matrix\([^)]*\)/, "" ) +
				("progid:DXImageTransform.Microsoft.Matrix(" +
					 "M11=" + m11 +
					",M12=" + m12 +
					",M21=" + m21 +
					",M22=" + m22 +
					",FilterType='bilinear',sizingMethod='auto expand')")
				;

	  		var ow = parseInt(element.style.width || element.width || 0 );
	  		var oh = parseInt(element.style.height || element.height || 0 );

			var radian = rotate * Math.PI / 180;
			var absCosX =Math.abs(Math.cos(radian));
			var absSinY =Math.abs(Math.sin(radian));

			var dx = (ow - (ow * absCosX + oh * absSinY)) / 2;
			var dy = (oh - (ow * absSinY + oh * absCosX)) / 2;

			element.style.marginLeft = Math.floor(dx) + "px";
			element.style.marginTop  = Math.floor(dy) + "px";

			return(true);
		};


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


					.attr({title: fm.i18n('autoSync')})
					.on('click', function(e){
						e.stopPropagation();
						e.preventDefault();
						node.parent()
							.toggleClass('ui-state-disabled', fm.options.syncStart)
							.parent().removeClass('ui-state-hover');
						fm.options.syncStart = !fm.options.syncStart;
						fm.autoSync(fm.options.syncStart? null : 'stop');
					})
			};


			createFromRaw = function(raw) {
				$.each(raw, function(i, data) {
					var node;

					if (data === '|') {
						menu.append('<div class="elfinder-contextmenu-separator"/>');
					} else if (data.label && typeof data.callback == 'function') {
						node = item(data.label, data.icon, function() {
							!data.remain && close();
							data.callback();
						});
						menu.append(node);
					}
				});
			};


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

	}


$.fn.hideWidgetRight = function() {
    $(this).each(function() {
        var widget = $(this);

        // slice of the "x2widget_" from the id to get widget name
        var widgetName = $(this).attr('id').slice(7);
        $.post(
            yii.scriptUrl+'/site/hideWidget',
            {name: widgetName},
            function(response) {

                widget.slideUp(function() {
                    widget.remove();
                    $('#x2-hidden-widgets-menu').replaceWith(response);
                //    $('.x2-widget-menu-item').draggable({revert: 'invalid', helper:'clone', revertDuration:200, appendTo:'#x2-hidden-widgets-menu',iframeFix:true});
                    $('.x2-hidden-widgets-menu-item.widget-center').click(function() {
                        return handleWidgetMenuItemClick($(this));
                    });
                    $('.x2-hidden-widgets-menu-item.widget-right').click(function() {
                        return handleWidgetRightMenuItemClick($(this));
                    });
                    if($('#sidebar-right .portlet').length == 0 && window.fullscreen == false) {
                        $('#fullscreen-button').trigger('click');
                    }
                });
            });
    });
};


	wp.updates.updateSuccess = function( response ) {
		var $updateMessage, name, $pluginRow, newText;
		if ( 'plugins' === pagenow || 'plugins-network' === pagenow ) {
			$pluginRow = $( '[data-plugin="' + response.plugin + '"]' ).first();
			$updateMessage = $pluginRow.next().find( '.update-message' );
			$pluginRow.addClass( 'updated' ).removeClass( 'update' );

			// Update the version number in the row.
			newText = $pluginRow.find('.plugin-version-author-uri').html().replace( response.oldVersion, response.newVersion );
			$pluginRow.find('.plugin-version-author-uri').html( newText );

			// Add updated class to update message parent tr
			$pluginRow.next().addClass( 'updated' );
		} else if ( 'plugin-install' === pagenow ) {
			$updateMessage = $( '.plugin-card-' + response.slug ).find( '.update-now' );
			$updateMessage.addClass( 'button-disabled' );
			name = $updateMessage.data( 'name' );
			$updateMessage.attr( 'aria-label', wp.updates.l10n.updatedLabel.replace( '%s', name ) );
		}

		$updateMessage.removeClass( 'updating-message' ).addClass( 'updated-message' );
		$updateMessage.text( wp.updates.l10n.updated );
		wp.a11y.speak( wp.updates.l10n.updatedMsg );

		wp.updates.decrementCount( 'plugin' );

		wp.updates.updateDoneSuccessfully = true;

		/*
		 * The lock can be released since the update was successful,
		 * and any other updates can commence.
		 */
		wp.updates.updateLock = false;

		$(document).trigger( 'wp-plugin-update-success', response );

		wp.updates.queueChecker();
	};


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


function submitEventDeletion() {
	var formData = $('#PromptForm').serialize();
	$.ajax({
		beforeSend: function (XMLHttpRequest) {
			$(".loading").show();
		},
		data: formData,
		success:function (data, textStatus) {
			updateIndex(context_id, context);
			handleGenericAjaxResponse(data);
		},
		complete:function() {
			$(".loading").hide();
			$("#confirmation_box").fadeOut();
			$("#gray_out").fadeOut();
		},
		type:"post",
		cache: false,
		url:"/" + type + "/" + action + "/" + id,
	});
}


	constructor(options) {
		this.__globalCounter = 0;
		this.options = options;
		this.id = options.id;
		this.container = options.container;
		this.classes = options.classes;
		this.table_title = options.title;
		this.header = options.header;
		this.onAddition = options.onAddition;
		this.onRemove = options.onRemove;
		this.header.push("Action");
		this.row_num = this.header.length;
		this.data = options.data === undefined ? [] : options.data;
		this.tr_id_mapping = {};
		this.control_items = options.control_items;
		this.header_action_button = options.header_action_button === undefined ? {} : options.header_action_button;
		if (options.header_action_button !== undefined) {
			this.header_action_button_style = this.header_action_button.style === undefined ? {} : this.header_action_button.style;
			this.additionEnabled = this.header_action_button.additionEnabled === undefined ? true : this.header_action_button.additionEnabled;
			this.additionButtonDisabled = this.header_action_button.disabled === undefined ? false : this.header_action_button.disabled;
		} else {
			this.header_action_button_style = {};
			this.additionEnabled = true;
			this.additionButtonDisabled = false;
		}

		this.row_action_button = options.row_action_button === undefined ? {} : options.row_action_button;
		if (options.row_action_button !== undefined) {
			this.row_action_button_style = this.row_action_button.style === undefined ? {} : this.row_action_button.style;
			this.removalEnabled = this.row_action_button.removalEnabled === undefined ? true : this.row_action_button.removalEnabled;
		} else {
			this.row_action_button_style = {};
			this.removalEnabled = true;
		}

		this.selects = {};

		this.__create_table();
	}


  handleSequelizeMethod(smth, tableName, factory, options, prepend) {
    if (smth instanceof Utils.Json) {
      // Parse nested object
      if (smth.conditions) {
        const conditions = this.parseConditionObject(smth.conditions).map(condition =>
          `${this.jsonPathExtractionQuery(condition.path[0], _.tail(condition.path))} = '${condition.value}'`
        );

        return conditions.join(' AND ');
      }
      if (smth.path) {
        let str;

        // Allow specifying conditions using the sqlite json functions
        if (this._checkValidJsonStatement(smth.path)) {
          str = smth.path;
        } else {
          // Also support json property accessors
          const paths = _.toPath(smth.path);
          const column = paths.shift();
          str = this.jsonPathExtractionQuery(column, paths);
        }

        if (smth.value) {
          str += util.format(' = %s', this.escape(smth.value));
        }

        return str;
      }
    } else if (smth instanceof Utils.Cast) {
      if (/timestamp/i.test(smth.type)) {
        smth.type = 'datetime';
      }
    }

    return AbstractQueryGenerator.prototype.handleSequelizeMethod.call(this, smth, tableName, factory, options, prepend);
  }


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


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


    ontext: function(text) {
      if (skipText) {
        return;
      }
      var lastFrame = stack[stack.length-1];
      var tag;

      if (lastFrame) {
        tag = lastFrame.tag;
        // If inner text was set by transform function then let's use it
        text = lastFrame.innerText !== undefined ? lastFrame.innerText : text;
      }

      if (nonTextTagsArray.indexOf(tag) !== -1) {
        result += text;
      } else {
        var escaped = escapeHtml(text);
        if (options.textFilter) {
          result += options.textFilter(escaped);
        } else {
          result += escaped;
        }
      }
      if (stack.length) {
           var frame = stack[stack.length - 1];
           frame.text += text;
      }
    },


function _onVersionValidationChanged() {
    // we want to reload all extensions, but only enable
    // extensions when allowed by the sessionMode, so
    // temporarily disable them all
    enabledExtensions = [];
    for (let uuid in ExtensionUtils.extensions)
        reloadExtension(ExtensionUtils.extensions[uuid]);
    enabledExtensions = getEnabledExtensions();

    if (Main.sessionMode.allowExtensions) {
        enabledExtensions.forEach(function(uuid) {
            enableExtension(uuid);
        });
    }
}


    $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.initialize = function() {
      growl.success('Retrieving definition for requisition ' + $scope.foreignSource + '...');
      RequisitionsService.getForeignSourceDefinition($scope.foreignSource).then(
        function(foreignSourceDef) { // success
          $scope.foreignSourceDef = foreignSourceDef;
          // Updating pagination variables for detectors.
          $scope.filteredDetectors = $scope.foreignSourceDef.detectors;
          $scope.updateFilteredDetectors();
          // Updating pagination variables for policies.
          $scope.filteredPolicies = $scope.foreignSourceDef.policies;
          $scope.updateFilteredPolicies();
        },
        $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.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.removeAllNodes = function(foreignSource) {
      bootbox.confirm('Are you sure you want to remove all the nodes from ' + foreignSource + '?', function(ok) {
        if (ok) {
          RequisitionsService.startTiming();
          RequisitionsService.removeAllNodesFromRequisition(foreignSource).then(
            function() { // success
              growl.success('All the nodes from ' + foreignSource + ' have been removed, and the requisition has been synchronized.');
              var req = $scope.requisitionsData.getRequisition(foreignSource);
              req.reset();
            },
            $scope.errorHandler
          );
        }
      });
    };


    $scope.save = function() {
      var form = this.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.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.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
          );
        });
      });
    };


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


                title: "<img src=\"img/icons/silk/information.png\" align=\"absmiddle\"> " + $("#navigrid-extension-information").attr("title")
            }).dialogExtend(
            {
                maximizable: true
            });
    });