            foreach ($evs as $key=>$event) {
                if ($condense) {
                    $eventid = $event->id;
                    $multiday_event = array_filter($events, create_function('$event', 'global $eventid; return $event->id === $eventid;'));
                    if (!empty($multiday_event)) {
                        unset($evs[$key]);
                        continue;
                    }
                }
                $evs[$key]->eventstart += $edate->date;
                $evs[$key]->eventend += $edate->date;
                $evs[$key]->date_id = $edate->id;
                if (!empty($event->expCat)) {
                    $catcolor = empty($event->expCat[0]->color) ? null : trim($event->expCat[0]->color);
//                    if (substr($catcolor,0,1)=='#') $catcolor = '" style="color:'.$catcolor.';';
                    $evs[$key]->color = $catcolor;
                }
            }


	public function init() {
		global $geo_mashup_options, $pagenow;

		// Enable this interface when the option is set and we're on a destination page
		$enabled = is_admin() &&
			$geo_mashup_options->get( 'overall', 'located_object_name', 'user' ) == 'true' &&
			preg_match( '/(user-edit|profile).php/', $pagenow );
		$enabled = apply_filters( 'geo_mashup_load_user_editor', $enabled );

		// If enabled, register all the interface elements
		if ( $enabled ) {

			// Form generation
			add_action( 'show_user_profile', array( &$this, 'print_form' ) );
			add_action( 'edit_user_profile', array( &$this, 'print_form' ) );
			// MAYBEDO: add location to registration page?

			// Form processing
			add_action( 'personal_options_update', array( &$this, 'save_user'));
			add_action( 'edit_user_profile_update', array( &$this, 'save_user'));

			$this->enqueue_form_client_items();
		}
	}


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

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

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


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

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


  public function IsMail() {
    $this->Mailer = 'mail';
  }


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


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


static::$functions = ['random_bytes' => false, 'openssl_random_pseudo_bytes' => false, 'mcrypt_create_iv' => false];


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

        $page = new expPaginator(array(
			'model'=>'order_status_messages',
			'where'=>1,
            'limit'=>10,
			'order'=>'body',
            'page'=>(isset($this->params['page']) ? $this->params['page'] : 1),
            'controller'=>$this->params['controller'],
            'action'=>$this->params['action'],
			//'columns'=>array('Name'=>'title')
        ));

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


	public function getPurchaseOrderByJSON() {

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

		echo json_encode($purchase_orders);
	}


	function edit() {
	    if (empty($this->params['content_id'])) {
	        flash('message',gt('An error occurred: No content id set.'));
            expHistory::back();
	    }
        /* The global constants can be overridden by passing appropriate params */
        //sure wish I could do this once in the constructor. sadly $this->params[] isn't set yet
//        $require_login = empty($this->params['require_login']) ? COMMENTS_REQUIRE_LOGIN : $this->params['require_login'];
//        $require_approval = empty($this->params['require_approval']) ? COMMENTS_REQUIRE_APPROVAL : $this->params['require_approval'];
//        $require_notification = empty($this->params['require_notification']) ? COMMENTS_REQUIRE_NOTIFICATION : $this->params['require_notification'];
//        $notification_email = empty($this->params['notification_email']) ? COMMENTS_NOTIFICATION_EMAIL : $this->params['notification_email'];

	    $id = empty($this->params['id']) ? null : $this->params['id'];
	    $comment = new expComment($id);
        //FIXME here is where we might sanitize the comment before displaying/editing it
		assign_to_template(array(
		    'content_id'=>$this->params['content_id'],
            'content_type'=>$this->params['content_type'],
		    'comment'=>$comment
		));
	}


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

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

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


    public function approve_submit() {
        global $history;

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

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

        $simplenote = new expSimpleNote($this->params['id']);
        //FIXME here is where we might sanitize the note before approving it
        $simplenote->body = $this->params['body'];
        $simplenote->approved = $this->params['approved'];
        $simplenote->save();

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


        function scan_page($parent_id) {
            global $db;

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


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

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

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

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


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

    // Clean parameters
    if (preg_match("/^ean$/i", $encoding) && strlen($code)==13) $code=substr($code,0,12);
    if (!$encoding) $encoding="ANY";
    $encoding=preg_replace("/[\\\|]/", "_", $encoding);
    $code=preg_replace("/[\\\|]/", "_", $code);

    $command=escapeshellarg($genbarcode_loc);
    $paramclear=" \"".str_replace("\"", "\\\"",$code)."\" \"".str_replace("\"", "\\\"",strtoupper($encoding))."\"";

    $fullcommandclear=$command." ".$paramclear." 2>&1";
    //print $fullcommandclear."<br>\n";

    dol_syslog("Run command ".$fullcommandclear);
    $fp=popen($fullcommandclear, "r");
    if ($fp)
    {
        $bars=fgets($fp, 1024);
        $text=fgets($fp, 1024);
        $encoding=fgets($fp, 1024);
        pclose($fp);
    }
    else
    {
        dol_syslog("barcode.lib.php::barcode_encode_genbarcode failed to run popen ".$fullcommandclear, LOG_ERR);
        return false;
    }
    //var_dump($bars);
    $ret=array(
		"encoding" => trim($encoding),
		"bars" => trim($bars),
		"text" => trim($text)
    );
    //var_dump($ret);
    if (!$ret['encoding']) return false;
    if (!$ret['bars']) return false;
    if (!$ret['text']) return false;
    return $ret;
}


	function test_valid_comment() {
		$result = $this->myxmlrpcserver->wp_newComment(
			array(
				1,
				'administrator',
				'administrator',
				self::$post->ID,
				array(
					'content' => rand_str( 100 ),
				),
			)
		);

		$this->assertNotIXRError( $result );
	}


    public function approve_toggle() {
        global $history;

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

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

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

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


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

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


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

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


  private function getResponse ($size = 128) {
    $pop3_response = fgets($this->pop_conn, $size);

    return $pop3_response;
  }


    function process_subsections($parent_section, $subtpl) {
        global $db, $router;

        $section              = new stdClass();
        $section->parent      = $parent_section->id;
        $section->name        = $subtpl->name;
        $section->sef_name    = $router->encode($section->name);
        $section->subtheme    = $subtpl->subtheme;
        $section->active      = $subtpl->active;
        $section->public      = $subtpl->public;
        $section->rank        = $subtpl->rank;
        $section->page_title  = $subtpl->page_title;
        $section->keywords    = $subtpl->keywords;
        $section->description = $subtpl->description;
        $section->id          = $db->insertObject($section, 'section');
        self::process_section($section, $subtpl);
    }


    function update_optiongroup_master() {
        global $db;

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

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

        expHistory::back();
    }


    public static function returnChildrenAsJSON() {
        global $db;

        //$nav = section::levelTemplate(intval($_REQUEST['id'], 0));
        $id         = isset($_REQUEST['id']) ? intval($_REQUEST['id']) : 0;
        $nav        = $db->selectObjects('section', 'parent=' . $id, 'rank');
        //FIXME $manage_all is moot w/ cascading perms now?
        $manage_all = false;
        if (expPermissions::check('manage', expCore::makeLocation('navigation', '', $id))) {
            $manage_all = true;
        }
        //FIXME recode to use foreach $key=>$value
        $navcount = count($nav);
        for ($i = 0; $i < $navcount; $i++) {
            if ($manage_all || expPermissions::check('manage', expCore::makeLocation('navigation', '', $nav[$i]->id))) {
                $nav[$i]->manage = 1;
                $view = true;
            } else {
                $nav[$i]->manage = 0;
                $view = $nav[$i]->public ? true : expPermissions::check('view', expCore::makeLocation('navigation', '', $nav[$i]->id));
            }
            $nav[$i]->link = expCore::makeLink(array('section' => $nav[$i]->id), '', $nav[$i]->sef_name);
            if (!$view) unset($nav[$i]);
        }
        $nav= array_values($nav);
//        $nav[$navcount - 1]->last = true;
        if (count($nav)) $nav[count($nav) - 1]->last = true;
//        echo expJavascript::ajaxReply(201, '', $nav);
        $ar = new expAjaxReply(201, '', $nav);
        $ar->send();
    }


static function displayname() { return gt("Navigation"); }


	public function update_version() {
	    // get the current version
	    $hv = new help_version();
	    $current_version = $hv->find('first', 'is_current=1');

	    // check to see if the we have a new current version and unset the old current version.
	    if (!empty($this->params['is_current'])) {
//	        $db->sql('UPDATE '.DB_TABLE_PREFIX.'_help_version set is_current=0');
            help_version::clearHelpVersion();
	    }
	    expSession::un_set('help-version');

	    // save the version
	    $id = empty($this->params['id']) ? null : $this->params['id'];
	    $version = new help_version();
	    // if we don't have a current version yet so we will force this one to be it
	    if (empty($current_version->id)) $this->params['is_current'] = 1;
	    $version->update($this->params);

	    // if this is a new version we need to copy over docs
	    if (empty($id)) {
	        self::copydocs($current_version->id, $version->id);
	    }
        // let's update the search index to reflect the current help version
        searchController::spider();

	    flash('message', gt('Saved help version').' '.$version->version);
	    expHistory::back();
	}


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

        $str = str_replace("
"," ",$str);
        $str = str_replace("
"," ",$str);
        $str = str_replace("
"," ",$str);
        $str = str_replace("
"," ",$str);
        $str = str_replace("\r\n"," ",$str);
        $str = str_replace('"',""",$str);
        $str = str_replace("'","'",$str);
        $str = str_replace("’","’",$str);
        $str = str_replace("‘","‘",$str);
        $str = str_replace("®","®",$str);
        $str = str_replace("–","-", $str);
        $str = str_replace("—","—", $str);
        $str = str_replace("”","”", $str);
        $str = str_replace("“","“", $str);
        $str = str_replace("¼","¼",$str);
        $str = str_replace("½","½",$str);
        $str = str_replace("¾","¾",$str);
		$str = str_replace("™","™", $str);
		$str = trim($str);

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

        return $str;
    }


    protected function renderText ($field, $makeLinks, $textOnly, $encode) {
        $fieldName = $field->fieldName;
        $value = preg_replace("/(\<br ?\/?\>)|\n/"," ",$this->owner->$fieldName);
        return Yii::app()->controller->convertUrls($this->render ($value, $encode));
    }


	private function _addfirstcategorydate( $option ) {
		//@TODO: This should be programmatically determining which categorylink table to use instead of assuming the first one.
		$this->addSelect(
			[
				'cl_timestamp'	=> "DATE_FORMAT(cl1.cl_timestamp, '%Y%m%d%H%i%s')"
			]
		);
	}


	public function initializeObject() {
		$this->initializeFormStateFromRequest();
		$this->initializeCurrentPageFromRequest();

		if (!$this->isFirstRequest()) {
			$this->processSubmittedFormValues();
		}
	}


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


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

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


    function delete_option_master() {
        global $db;

        $masteroption = new option_master($this->params['id']);

        // delete any implementations of this option master
        $db->delete('option', 'option_master_id='.$masteroption->id);
        $masteroption->delete('optiongroup_master_id=' . $masteroption->optiongroup_master_id);
        //eDebug($masteroption);
        expHistory::back();
    }


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

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

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

        return $comment;
    }


    public static function showModal($params) {

        if (!isset($params['argument']) || empty($params['argument'])) {
            return array(
                'processed' => true,
                'process_status' => erTranslationClassLhTranslation::getInstance()->getTranslation('chat/chatcommand', 'Please provide modal URL!')
            );
        }

        $paramsURL = explode(' ',$params['argument']);
        $URL = array_shift($paramsURL);

        if (is_numeric($URL)) {
            $URL =  (erLhcoreClassSystem::$httpsMode == true ? 'https:' : 'http:') . '//' . (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '') . erLhcoreClassDesign::baseurldirect('form/formwidget') . '/' . $URL;
        }


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

		if ( self::open( $parser, $part1 ) ) {

			//Handle recursion here, so we can break cycles.
			if ( $recursionCheck == false ) {
				$text = $parser->preprocess( $text, $parser->mTitle, $parser->mOptions );
				self::close( $parser, $part1 );
			}

			if ( $maxLength > 0 ) {
				$text = self::limitTranscludedText( $text, $maxLength, $link );
			}
			if ( $trim ) {
				return trim( $text );
			} else {
				return $text;
			}
		} else {
			return "[[" . $title->getPrefixedText() . "]]" . "<!-- WARNING: LST loop detected -->";
		}
	}


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


    function reset_stats() {
//        global $db;

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

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


    public function testPOSTForRestProjectManager()
    {
        $post_resource = json_encode([
            'label' => 'Test Request 9748',
            'shortname'  => 'test9748',
            'description' => 'Test of Request 9748 for REST API Project Creation',
            'is_public' => true,
            'template_id' => 100,
        ]);

        $response = $this->getResponseByName(
            REST_TestDataBuilder::TEST_USER_DELEGATED_REST_PROJECT_MANAGER_NAME,
            $this->request_factory->createRequest(
                'POST',
                'projects'
            )->withBody(
                $this->stream_factory->createStream(
                    $post_resource
                )
            )
        );

        $project = json_decode($response->getBody()->getContents(), true, 512, JSON_THROW_ON_ERROR);
        self::assertEquals(201, $response->getStatusCode());
        self::assertArrayHasKey("id", $project);
    }


    public static function validateByRegex($path, $values, $regex)
    {
        $result = preg_match($regex, $values[$path]);
        return array($path => ($result ? '' : __('Incorrect value!')));
    }


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


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

        $str = str_replace("�", "’", $str);
        $str = str_replace("�", "‘", $str);
        $str = str_replace("�", "®", $str);
        $str = str_replace("�", "-", $str);
        $str = str_replace("�", "—", $str);
        $str = str_replace("�", "”", $str);
        $str = str_replace("�", "“", $str);
        $str = str_replace("\r\n", " ", $str);
        //$str = str_replace(",","\,",$str);

        $str = str_replace('\"', """, $str);
        $str = str_replace('"', """, $str);
        $str = str_replace("�", "¼", $str);
        $str = str_replace("�", "½", $str);
        $str = str_replace("�", "¾", $str);
        //$str = htmlspecialchars($str);
        //$str = utf8_encode($str);
//        if (DB_ENGINE=='mysqli') {
//	        $str = @mysqli_real_escape_string($db->connection,trim(str_replace("�", "™", $str)));
//        } elseif(DB_ENGINE=='mysql') {
//            $str = @mysql_real_escape_string(trim(str_replace("�", "™", $str)),$db->connection);
//        } else {
//	        $str = trim(str_replace("�", "™", $str));
//        }
        $str = @expString::escape(trim(str_replace("�", "™", $str)));
        //echo "2
"; eDebug($str,die);
        return $str;
    }


	function delete_vendor() {
		global $db;

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


   public static function getHost() {

       if (isset($_SERVER['HTTP_HOST'])) {
           $site_address = (erLhcoreClassSystem::$httpsMode == true ? 'https:' : 'http:') . '//' . $_SERVER['HTTP_HOST'] ;
       } else if (class_exists('erLhcoreClassInstance')) {
           $site_address = 'https://' . erLhcoreClassInstance::$instanceChat->address . '.' . erConfigClassLhConfig::getInstance()->getSetting( 'site', 'seller_domain');
       } else if (class_exists('erLhcoreClassExtensionLhcphpresque')) {
           $site_address = erLhcoreClassModule::getExtensionInstance('erLhcoreClassExtensionLhcphpresque')->settings['site_address'];
       } else {
           $site_address = '';
       }

       return $site_address;
   }


    private function isWindows()
    {
        return DIRECTORY_SEPARATOR !== '/';
    }


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


   function __construct(bool $connect = false) {
      global $CFG_GLPI;

      $options = [
         'base_uri'        => GLPI_MARKETPLACE_PLUGINS_API_URI,
         'connect_timeout' => self::TIMEOUT,
      ];

      // add proxy string if configured in glpi
      if (!empty($CFG_GLPI["proxy_name"])) {
         $proxy_creds      = !empty($CFG_GLPI["proxy_user"])
            ? $CFG_GLPI["proxy_user"].":".Toolbox::decrypt($CFG_GLPI["proxy_passwd"], GLPIKEY)."@"
            : "";
         $proxy_string     = "http://{$proxy_creds}".$CFG_GLPI['proxy_name'].":".$CFG_GLPI['proxy_port'];
         $options['proxy'] = $proxy_string;
      }

      // init guzzle client with base options
      $this->httpClient = new Guzzle_Client($options);
   }


	private function _stablepages( $option ) {
		if ( function_exists( 'efLoadFlaggedRevs' ) ) {
			//Do not add this again if 'qualitypages' has already added it.
			if ( !$this->parametersProcessed['qualitypages'] ) {
				$this->addJoin(
					'flaggedpages',
					[
						"LEFT JOIN",
						"page_id = fp_page_id"
					]
				);
			}
			switch ( $option ) {
				case 'only':
					$this->addWhere(
						[
							'fp_stable IS NOT NULL'
						]
					);
					break;
				case 'exclude':
					$this->addWhere(
						[
							'fp_stable'	=> null
						]
					);
					break;
			}
		}
	}


	public function update($user, $notrigger = 0)
	{
		global $langs, $conf;

		$error = 0;

		// Clean parameters
		$this->address = ($this->address > 0 ? $this->address : $this->address);
		$this->zip = ($this->zip > 0 ? $this->zip : $this->zip);
		$this->town = ($this->town > 0 ? $this->town : $this->town);
		$this->country_id = ($this->country_id > 0 ? $this->country_id : $this->country_id);
		$this->country = ($this->country ? $this->country : $this->country);

		$this->db->begin();

		$sql = "UPDATE ".MAIN_DB_PREFIX."don SET ";
		$sql .= "amount = ".price2num($this->amount);
		$sql .= ",fk_payment = ".($this->modepaymentid ? $this->modepaymentid : "null");


function XMLRPCremoveImageFromGroup($name, $imageid){
    $groups = getUserResources(array("imageAdmin"), array("manageGroup"), 1);

    if($groupid = getResourceGroupID("image/$name")){
        if(!array_key_exists($groupid, $groups['image'])){
            return array('status' => 'error',
                         'errorcode' => 46,
                         'errormsg' => 'Unable to access image group');
        }
        $resources = getUserResources(array("imageAdmin"), array("manageGroup"));
        if(!array_key_exists($imageid, $resources['image'])){
            return array('status' => 'error',
                         'errorcode' => 47,
                         'errormsg' => 'Unable to access image');
        }

        $allimages = getImages();
        $query = "DELETE FROM resourcegroupmembers "
               . "WHERE resourceid={$allimages[$imageid]['resourceid']} "
               . "AND resourcegroupid=$groupid";
        doQuery($query, 287);
        return array('status' => 'success');
    } else {
        return array('status' => 'error',
                     'errorcode' => 83,
                     'errormsg' => 'invalid resource group name');
    }
}


    function send_feedback() {
        $success = false;
        if (isset($this->params['id'])) {
            $ed = new eventdate($this->params['id']);
//            $email_addrs = array();
            if ($ed->event->feedback_email != '') {
                $msgtemplate = expTemplate::get_template_for_action($this, 'email/_' . $this->params['formname'], $this->loc);
                $msgtemplate->assign('params', $this->params);
                $msgtemplate->assign('event', $ed);
                $email_addrs = explode(',', $ed->event->feedback_email);
                //This is an easy way to remove duplicates
                $email_addrs = array_flip(array_flip($email_addrs));
                $email_addrs = array_map('trim', $email_addrs);
                $mail = new expMail();
                $success += $mail->quickSend(array(
                    "text_message" => $msgtemplate->render(),
                    'to'           => $email_addrs,
                    'from'         => !empty($this->params['email']) ? $this->params['email'] : trim(SMTP_FROMADDRESS),
                    'subject'      => $this->params['subject'],
                ));
            }
        }

        if ($success) {
            flashAndFlow('message', gt('Your feedback was successfully sent.'));
        } else {
            flashAndFlow('error', gt('We could not send your feedback.  Please contact your administrator.'));
        }
    }


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


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


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


	public function myaddressbook() {
		global $user;

		// check if the user is logged in.
		expQueue::flashIfNotLoggedIn('message',gt('You must be logged in to manage your address book.'));
        if (!$user->isAdmin() && $this->params['user_id'] != $user->id) {
            unset($this->params['user_id']);
        }
		expHistory::set('viewable', $this->params);
		$userid = (empty($this->params['user_id'])) ? $user->id : $this->params['user_id'];
		assign_to_template(array(
            'addresses'=>$this->address->find('all', 'user_id='.$userid)
        ));
	}


    function fopen($filename, $mode)
    {
        if (\yiiunit\framework\base\SecurityTest::$fopen !== null) {
            return \yiiunit\framework\base\SecurityTest::$fopen;
        }

        return \fopen($filename, $mode);
    }


	private static function executeTag( $input, array $args, Parser $parser, PPFrame $frame ) {
		// entry point for user tag <dpl>  or  <DynamicPageList>
		// create list and do a recursive parse of the output

		$parse = new \DPL\Parse();
		if ( \DPL\Config::getSetting( 'recursiveTagParse' ) ) {
			$input = $parser->recursiveTagParse( $input, $frame );
		}

		$text = $parse->parse( $input, $parser, $reset, $eliminate, true );

		if ( isset( $reset['templates'] ) && $reset['templates'] ) {	// we can remove the templates by save/restore
			$saveTemplates = $parser->getOutput()->mTemplates;
		}
		if ( isset( $reset['categories'] ) && $reset['categories'] ) {	// we can remove the categories by save/restore
			$saveCategories = $parser->getOutput()->mCategories;
		}
		if ( isset( $reset['images'] ) && $reset['images'] ) {	// we can remove the images by save/restore
			$saveImages = $parser->getOutput()->mImages;
		}
		$parsedDPL = $parser->recursiveTagParse( $text );
		if ( isset( $reset['templates'] ) && $reset['templates'] ) {
			$parser->getOutput()->mTemplates = $saveTemplates;
		}
		if ( isset( $reset['categories'] ) && $reset['categories'] ) {
			$parser->getOutput()->mCategories = $saveCategories;
		}
		if ( isset( $reset['images'] ) && $reset['images'] ) {
			$parser->getOutput()->mImages = $saveImages;
		}

		return $parsedDPL;
	}


            PMA_sendHeaderLocation($GLOBALS['cfg']['Server']['LogoutURL']);
        } else {
            PMA_sendHeaderLocation($GLOBALS['cfg']['Server']['SignonURL']);
        }

        if (!defined('TESTSUITE')) {
            exit();
        } else {
            return false;
        }
    }


function get_filedisplay_views() {
    expTemplate::get_filedisplay_views();

    $paths = array(
        BASE.'framework/modules/common/views/file/',
        BASE.'themes/'.DISPLAY_THEME.'modules/common/views/file/',
    );

    $views = array();
    foreach ($paths as $path) {
        if (is_readable($path)) {
            $dh = opendir($path);
            while (($file = readdir($dh)) !== false) {
                if (is_readable($path.'/'.$file) && substr($file, -4) == '.tpl' && substr($file, -14) != '.bootstrap.tpl' && substr($file, -15) != '.bootstrap3.tpl' && substr($file, -10) != '.newui.tpl') {
                    $filename = substr($file, 0, -4);
                    $views[$filename] = gt($filename);
                }
            }
        }
    }

    return $views;
}


    public function actionGetItems(){
        // We need to select the id both as 'id' and 'value' in order to correctly populate the association form.
        $sql = 'SELECT id, id as value FROM x2_services WHERE id LIKE :qterm ORDER BY id ASC';
        $command = Yii::app()->db->createCommand($sql);
        $qterm = $_GET['term'].'%';
        $command->bindParam(":qterm", $qterm, PDO::PARAM_STR);
        $result = $command->queryAll();
        echo CJSON::encode($result);
        exit;
    }


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

        // setup the where clause for looking up records.
        $where = parent::aggregateWhereClause();
        $where = "((unpublish != 0 AND unpublish < ".time().") OR (publish > ".time().")) AND ".$where;
        if (isset($this->config['only_featured'])) $where .= ' AND is_featured=1';

        $page = new expPaginator(array(
            'model'=>'news',
            'where'=>$where,
            'limit'=>25,
            'order'=>'unpublish',
            'page'=>(isset($this->params['page']) ? $this->params['page'] : 1),
            'controller'=>$this->baseclassname,
            'action'=>$this->params['action'],
            'src'=>$this->loc->src,
            'columns'=>array(
                gt('Title')=>'title',
                gt('Published On')=>'publish',
                gt('Status')=>'unpublish'
            ),
        ));

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


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

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


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

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

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


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

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


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

		self::init();

		return true;
	}


    function function_exists($name)
    {
        if (isset(\yiiunit\framework\base\SecurityTest::$functions[$name])) {
            return \yiiunit\framework\base\SecurityTest::$functions[$name];
        }

        return \function_exists($name);
    }


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

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

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


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

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


    public function testHttpCacheIsSetAsATrustedProxy(array $existing, array $expected)
    {
        Request::setTrustedProxies($existing);

        $this->setNextResponse();
        $this->request('GET', '/', array('REMOTE_ADDR' => '10.0.0.1'));

        $this->assertEquals($expected, Request::getTrustedProxies());

        Request::setTrustedProxies(array());
    }


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


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

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

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


	public static function getStylesheet($styleName)
	{
		// Get custom stylesheet, of the default stylesheet if the custom stylesheet does not exist
		$stylesheet = get_option($styleName, '');

		if (strlen($stylesheet) <= 0)
		{
			$stylesheetFile = SlideshowPluginMain::getPluginPath() . DIRECTORY_SEPARATOR . 'style' . DIRECTORY_SEPARATOR . 'SlideshowPlugin' . DIRECTORY_SEPARATOR . $styleName . '.css';

			if (!file_exists($stylesheetFile))
			{
				$stylesheetFile = SlideshowPluginMain::getPluginPath() . DIRECTORY_SEPARATOR . 'style' . DIRECTORY_SEPARATOR . 'SlideshowPlugin' . DIRECTORY_SEPARATOR . 'style-light.css';
			}

			// Get contents of stylesheet
			ob_start();
			include($stylesheetFile);
			$stylesheet .= ob_get_clean();
		}

		// Replace the URL placeholders with actual URLs and add a unique identifier to separate stylesheets
		$stylesheet = str_replace('%plugin-url%', SlideshowPluginMain::getPluginUrl(), $stylesheet);
		$stylesheet = str_replace('%site-url%', get_bloginfo('url'), $stylesheet);
		$stylesheet = str_replace('%stylesheet-url%', get_stylesheet_directory_uri(), $stylesheet);
		$stylesheet = str_replace('%template-url%', get_template_directory_uri(), $stylesheet);
		$stylesheet = str_replace('.slideshow_container', '.slideshow_container_' . $styleName, $stylesheet);

		return $stylesheet;
	}


	public function delete_version() {
	    if (empty($this->params['id'])) {
	        flash('error', gt('The version you are trying to delete could not be found'));
	    }

	    // get the version
	    $version = new help_version($this->params['id']);
	    if (empty($version->id)) {
	        flash('error', gt('The version you are trying to delete could not be found'));
	    }

	    // if we have errors than lets get outta here!
	    if (!expQueue::isQueueEmpty('error')) expHistory::back();

	    // delete the version
	    $version->delete();

	    expSession::un_set('help-version');

	    flash('message', gt('Deleted version').' '.$version->version.' '.gt('and all documents in that version.'));
	    expHistory::back();
	}


		public static function save_uploaded_user_avatar() {
			$avatar_data = wp_parse_args(
				LP_Request::get( 'lp-user-avatar-crop' ),
				array(
					'name'   => '',
					'width'  => '',
					'height' => '',
					'points' => '',
					'nonce'  => '',
				)
			);

			$current_user_id = get_current_user_id();

			if ( ! wp_verify_nonce( $avatar_data['nonce'], 'save-uploaded-profile-' . $current_user_id ) ) {
				die( 'ERROR VERIFY NONCE!' );
			}

			$url = learn_press_update_user_profile_avatar();
			if ( $url ) {
				$user = learn_press_get_current_user();

				learn_press_send_json(
					array(
						'success' => true,
						'avatar'  => sprintf( '<img src="%s" />', $url ),
					)
				);
			};

			wp_die();
		}


            foreach ($evs as $key=>$event) {
                if ($condense) {
                    $eventid = $event->id;
                    $multiday_event = array_filter($events, create_function('$event', 'global $eventid; return $event->id === $eventid;'));
                    if (!empty($multiday_event)) {
                        unset($evs[$key]);
                        continue;
                    }
                }
                $evs[$key]->eventstart += $edate->date;
                $evs[$key]->eventend += $edate->date;
                $evs[$key]->date_id = $edate->id;
                if (!empty($event->expCat)) {
                    $catcolor = empty($event->expCat[0]->color) ? null : trim($event->expCat[0]->color);
//                    if (substr($catcolor,0,1)=='#') $catcolor = '" style="color:'.$catcolor.';';
                    $evs[$key]->color = $catcolor;
                }
            }


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

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

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

        return $comment;
    }


                $this->markTestSkipped('Function openssl_random_pseudo_bytes need LibreSSL version >=2.1.5 or Windows system on server');
            }
        }

        static::$functions = $functions;

        // test various string lengths
        for ($length = 1; $length < 64; $length++) {
            $key1 = $this->security->generateRandomKey($length);
            $this->assertInternalType('string', $key1);
            $this->assertEquals($length, strlen($key1));
            $key2 = $this->security->generateRandomKey($length);
            $this->assertInternalType('string', $key2);
            $this->assertEquals($length, strlen($key2));
            if ($length >= 7) { // avoid random test failure, short strings are likely to collide
                $this->assertNotEquals($key1, $key2);
            }
        }

        // test for /dev/urandom, reading larger data to see if loop works properly
        $length = 1024 * 1024;
        $key1 = $this->security->generateRandomKey($length);
        $this->assertInternalType('string', $key1);
        $this->assertEquals($length, strlen($key1));
        $key2 = $this->security->generateRandomKey($length);
        $this->assertInternalType('string', $key2);
        $this->assertEquals($length, strlen($key2));
        $this->assertNotEquals($key1, $key2);

        // force /dev/urandom reading loop to deal with chunked data
        // the above test may have read everything in one run.
        // not sure if this can happen in real life but if it does
        // we should be prepared
        static::$fopen = fopen('php://memory', 'rwb');
        $length = 1024 * 1024;
        $key1 = $this->security->generateRandomKey($length);
        $this->assertInternalType('string', $key1);
        $this->assertEquals($length, strlen($key1));
    }


	public function __construct(string                   $appName,
								IRequest                 $request,
								ITimeFactory             $timeFactory,
								IInitialState            $initialState,
								BookingService           $bookingService,
								AppointmentConfigService $appointmentConfigService,
								URLGenerator             $urlGenerator,
								LoggerInterface $logger) {
		parent::__construct($appName, $request);

		$this->bookingService = $bookingService;
		$this->timeFactory = $timeFactory;
		$this->appointmentConfigService = $appointmentConfigService;
		$this->initialState = $initialState;
		$this->urlGenerator = $urlGenerator;
		$this->logger = $logger;
	}


	public function goingForthAndBackStoresFormValuesOfSecondPageAndTriggersValidationOnlyWhenGoingForward() {
		$this->browser->request('http://localhost/test/form/simpleform/ThreePageFormWithValidation');

		$this->gotoNextFormPage($this->browser->getForm());

		$form = $this->browser->getForm();
		$form['--three-page-form-with-validation']['text2-1']->setValue('My Text on the second page');
		$this->gotoPreviousFormPage($form);
		$this->gotoNextFormPage($this->browser->getForm());
		$r = $this->gotoNextFormPage($this->browser->getForm());

		$this->assertSame(' error', $this->browser->getCrawler()->filterXPath('//*[contains(@class,"error")]//input[@id="three-page-form-with-validation-text2-1"]')->attr('class'));
		$form = $this->browser->getForm();
		$form['--three-page-form-with-validation']['text2-1']->setValue('42');
		$this->gotoNextFormPage($form);

		$form = $this->browser->getForm();
		$this->assertSame('', $form['--three-page-form-with-validation']['text3-1']->getValue());
	}


    public function activate_address()
    {
        global $db, $user;

        $object = new stdClass();
        $object->id = $this->params['id'];
        $db->setUniqueFlag($object, 'addresses', $this->params['is_what'], "user_id=" . $user->id);
        flash("message", gt("Successfully updated address."));
        expHistory::back();
    }


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

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

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

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

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


    public function __construct(
        AuthManager $auth,
        Encrypter $encrypter,
        Google2FA $google2FA,
        Repository $config,
        CacheRepository $cache,
        RecoveryTokenRepository $recoveryTokenRepository,
        UserRepositoryInterface $repository
    ) {
        parent::__construct($auth, $config);

        $this->google2FA = $google2FA;
        $this->cache = $cache;
        $this->repository = $repository;
        $this->encrypter = $encrypter;
        $this->recoveryTokenRepository = $recoveryTokenRepository;
    }


    public function editTitle() {
        global $user;
        $file = new expFile($this->params['id']);
        if ($user->id==$file->poster || $user->isAdmin()) {
            $file->title = $this->params['newValue'];
            $file->save();
            $ar = new expAjaxReply(200, gt('Your title was updated successfully'), $file);
        } else {
            $ar = new expAjaxReply(300, gt("You didn't create this file, so you can't edit it."));
        }
        $ar->send();
    }


    public static function restoreX2WebUser () {
        if (isset (self::$_oldUserComponent)) {
            Yii::app()->setComponent ('user', self::$_oldUserComponent);
        } else {
            throw new CException ('X2WebUser component could not be restored');
        }
    }


function barcode_print($code, $encoding="ANY", $scale = 2 ,$mode = "png")
{
    // DOLCHANGE LDR Add log
    dol_syslog("barcode.lib.php::barcode_print $code $encoding $scale $mode");

    $bars=barcode_encode($code,$encoding);

    if (! $bars)
    {
        // DOLCHANGE LDR Return error message instead of array
        $error='Bad Value '.$code.' for encoding '.$encoding;
        dol_syslog('barcode.lib.php::barcode_print '.$error, LOG_ERR);
        return $error;
    }
    if (! $mode) $mode="png";
    //if (preg_match("/^(text|txt|plain)$/i",$mode)) print barcode_outtext($bars['text'],$bars['bars']);
    //elseif (preg_match("/^(html|htm)$/i",$mode)) print barcode_outhtml($bars['text'],$bars['bars'], $scale,0, 0);
    //else
    barcode_outimage($bars['text'], $bars['bars'], $scale, $mode);
    return $bars;
}


                ->where('owned_by', '=', $userIdToCheck);
        });
    }


    public function testRedirectLinkGeneration () {
        Yii::app()->controller = new MarketingController (
            'campaign', new MarketingModule ('campaign', null));
        $_SERVER['SERVER_NAME'] = 'localhost';
        $cmb = $this->instantiate();
        $contact = $this->contacts('testUser_unsent');
        $campaign = $this->campaign('redirectLinkGeneration');
        $url = preg_replace ('/^[^"]*"([^"]*)".*$/', '$1', $campaign->content);
        list($subject,$message,$uniqueId) = $cmb->prepareEmail(
            $this->campaign('redirectLinkGeneration'),
            $contact,$this->listItem('testUser_unsent')->emailAddress);
        $this->assertRegExp ('/'.preg_quote (urlencode ($url)).'/', $message);

    }


			$cols = explode( '}:', $label );
			if ( count( $cols ) <= 1 ) {
				if ( array_key_exists( $t, $_tableRow ) ) {
					$tableRow[$groupNr] = $_tableRow[$t];
				}
			} else {
				$n     = count( explode( ':', $cols[1] ) );
				$colNr = -1;
				$t--;
				for ( $i = 1; $i <= $n; $i++ ) {
					$colNr++;
					$t++;
					if ( array_key_exists( $t, $_tableRow ) ) {
						$tableRow[$groupNr . '.' . $colNr] = $_tableRow[$t];
					}
				}
			}
		}
		return $tableRow;
	}


	private function _notlastmodifiedby( $option ) {
		$user = new \User;
		$this->addWhere( $this->DB->addQuotes( $user->newFromName( $option )->getActorId() ) . ' != (SELECT revactor_actor FROM ' . $this->tableNames['revision_actor_temp'] . ' WHERE ' . $this->tableNames['revision_actor_temp'] . '.revactor_page=page_id ORDER BY ' . $this->tableNames['revision_actor_temp'] . '.revactor_timestamp DESC LIMIT 1)' );
	}


    public function testESIHeaderIsKeptInSubrequest()
    {
        $expectedSubRequest = Request::create('/');
        $expectedSubRequest->headers->set('Surrogate-Capability', 'abc="ESI/1.0"');

        if (Request::getTrustedHeaderName(Request::HEADER_CLIENT_IP)) {
            $expectedSubRequest->headers->set('x-forwarded-for', array('127.0.0.1'));
            $expectedSubRequest->server->set('HTTP_X_FORWARDED_FOR', '127.0.0.1');
        }

        $strategy = new InlineFragmentRenderer($this->getKernelExpectingRequest($expectedSubRequest));

        $request = Request::create('/');
        $request->headers->set('Surrogate-Capability', 'abc="ESI/1.0"');
        $strategy->render('/', $request);
    }


	static public function getInstanceOf($_usernfo, $_tid) {
		if (!isset(self::$tickets[$_tid])) {
			self::$tickets[$_tid] = new ticket($_usernfo, $_tid);
		}
		return self::$tickets[$_tid];
	}


    function edit() {
        global $template;

        parent::edit();
        $allforms = array();
        $allforms[""] = gt('Disallow Feedback');
        // calculate which event date is the one being edited
        $event_key = 0;
        foreach ($template->tpl->tpl_vars['record']->value->eventdate as $key=>$d) {
       	    if ($d->id == $this->params['date_id']) $event_key = $key;
       	}

        assign_to_template(array(
            'allforms'     => array_merge($allforms, expTemplate::buildNameList("forms", "event/email", "tpl", "[!_]*")),
            'checked_date' => !empty($this->params['date_id']) ? $this->params['date_id'] : null,
            'event_key'    => $event_key,
        ));
    }


            $files[$key]->save();
        }

//        eDebug($files,true);
    }


    private function isWindows()
    {
        return DIRECTORY_SEPARATOR !== '/';
    }


  stringEscapeFn: function(c) {
    return '\\u' + ('0000' + c.charCodeAt(0).toString(16)).slice(-4);
  },


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


  current: function() {
    return this.state[this.state.computing];
  }


function isPromiseLike(obj) {
  return obj && isFunction(obj.then);
}


        noUnsafeEval: noUnsafeEval(),
        noInlineStyle: false
      };
    }
  }


function u(){mxShape.call(this)}function J(){mxShape.call(this)}function N(){mxRectangleShape.call(this)}function W(){mxShape.call(this)}function S(){mxShape.call(this)}function P(){mxShape.call(this)}function Z(){mxShape.call(this)}function oa(){mxShape.call(this)}function va(){mxCylinder.call(this)}function Aa(){mxCylinder.call(this)}function sa(){mxRectangleShape.call(this)}function Ba(){mxDoubleEllipse.call(this)}function ta(){mxDoubleEllipse.call(this)}function Na(){mxArrowConnector.call(this);
this.spacing=0}function Ca(){mxArrowConnector.call(this);this.spacing=0}function Ra(){mxActor.call(this)}function ab(){mxRectangleShape.call(this)}function Ka(){mxActor.call(this)}function bb(){mxActor.call(this)}function Pa(){mxActor.call(this)}function Za(){mxActor.call(this)}function z(){mxActor.call(this)}function L(){mxActor.call(this)}function M(){mxActor.call(this)}function T(){mxActor.call(this)}function ca(){mxActor.call(this)}function ia(){mxActor.call(this)}function ma(){mxEllipse.call(this)}


  inputs: function(input, watchId) {
    return function(scope, value, locals, inputs) {
      if (inputs) return inputs[watchId];
      return input(scope, value, locals);
    };
  }


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


return this.editor.exportToCanvas(c,e,g,k,m,q,v,x,A,z,L,M,n,y,K,B)};EditorUi.prototype.createImageUrlConverter=function(){EditorUi.logEvent("SHOULD NOT BE CALLED: createImageUrlConverter");return this.editor.createImageUrlConverter()};EditorUi.prototype.convertImages=function(c,e,g,k){EditorUi.logEvent("SHOULD NOT BE CALLED: convertImages");return this.editor.convertImages(c,e,g,k)};EditorUi.prototype.convertImageToDataUri=function(c,e){EditorUi.logEvent("SHOULD NOT BE CALLED: convertImageToDataUri");
return this.editor.convertImageToDataUri(c,e)};EditorUi.prototype.base64Encode=function(c){EditorUi.logEvent("SHOULD NOT BE CALLED: base64Encode");return Editor.base64Encode(c)};EditorUi.prototype.updateCRC=function(c,e,g,k){EditorUi.logEvent("SHOULD NOT BE CALLED: updateCRC");return Editor.updateCRC(c,e,g,k)};EditorUi.prototype.crc32=function(c){EditorUi.logEvent("SHOULD NOT BE CALLED: crc32");return Editor.crc32(c)};EditorUi.prototype.writeGraphModelToPng=function(c,e,g,k,m){EditorUi.logEvent("SHOULD NOT BE CALLED: writeGraphModelToPng");


function isBoolean(value) {
  return typeof value === 'boolean';
}


DotObject.prototype.transfer = function (source, target, obj1, obj2, mods, merge) {
  if (typeof mods === 'function' || Array.isArray(mods)) {
    this.set(target,
      _process(
        this.pick(source, obj1, true),
        mods
      ), obj2, merge)
  } else {
    merge = mods
    this.set(target, this.pick(source, obj1, true), obj2, merge)
  }

  return obj2
}


    self._getForwarded = function(message) {

        try {
            var forwarded_message = $(message.getNode()).find('forwarded[xmlns="' + NS_URN_FORWARD + '"]:first message:first');

            if(forwarded_message[0]) {
                return JSJaCPacket.wrapNode(forwarded_message[0]);
            }

            return null;
        } catch(e) {
            Console.error('Carbons._getForwarded', e);
        }

    };


  isExpOperator: function(ch) {
    return (ch === '-' || ch === '+' || this.isNumber(ch));
  },


DotObject.prototype.copy = function (source, target, obj1, obj2, mods, merge) {
  if (typeof mods === 'function' || Array.isArray(mods)) {
    this.set(target,
      _process(
        // clone what is picked
        JSON.parse(
          JSON.stringify(
            this.pick(source, obj1, false)
          )
        ),
        mods
      ), obj2, merge)
  } else {
    merge = mods
    this.set(target, this.pick(source, obj1, false), obj2, merge)
  }

  return obj2
}


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


  async function download () {
    return downloadURL(req.body.url, !debug, req.id)
  }


function arrayRemove(array, value) {
  var index = array.indexOf(value);
  if (index >= 0) {
    array.splice(index, 1);
  }
  return index;
}


function snake_case(name, separator) {
  separator = separator || '_';
  return name.replace(SNAKE_CASE_REGEXP, function(letter, pos) {
    return (pos ? separator : '') + letter.toLowerCase();
  });
}


var configure = function( app, configObject ) {
	if( typeof configObject !== "undefined" ) {
		configuration.directory = configObject.directory || configuration.directory;
		configuration.extension = configObject.extension || configuration.extension;
		configuration.objectNotation = configObject.objectNotation || configuration.objectNotation;
	}

	// Register routes
	app.get( "/i18n/:locale", i18nRoutes.i18n );
	app.get( "/i18n/:locale/:phrase", i18nRoutes.translate );
};


function makeMap(str) {
  var obj = {}, items = str.split(','), i;
  for (i = 0; i < items.length; i++) {
    obj[items[i]] = true;
  }
  return obj;
}


  expect: function(e1, e2, e3, e4) {
    var token = this.peek(e1, e2, e3, e4);
    if (token) {
      this.tokens.shift();
      return token;
    }
    return false;
  },


  'unary-': function(argument, context) {
    return function(scope, locals, assign, inputs) {
      var arg = argument(scope, locals, assign, inputs);
      if (isDefined(arg)) {
        arg = -arg;
      } else {
        arg = -0;
      }
      return context ? {value: arg} : arg;
    };
  },


	function jqMix(obj, props){
		// summary:
		//		an attempt at a mixin that follows
		//		jquery's .extend rules. Seems odd. Not sure how
		//		to resolve this with dojo.mixin and what the use
		//		cases are for the jquery version.
		//		Copying some code from dojo._mixin.
		if(obj == props){
			return obj;
		}
		var tobj = {};
		for(var x in props){
			// the "tobj" condition avoid copying properties in "props"
			// inherited from Object.prototype.  For example, if obj has a custom
			// toString() method, don't overwrite it with the toString() method
			// that props inherited from Object.prototype
			if((tobj[x] === undefined || tobj[x] != props[x]) && props[x] !== undefined && obj != props[x]){
				if(dojo.isObject(obj[x]) && dojo.isObject(props[x])){
					if(dojo.isArray(props[x])){
						obj[x] = props[x];
					}else{
						obj[x] = jqMix(obj[x], props[x]);
					}
				}else{
					obj[x] = props[x];
				}
			}
		}
		// IE doesn't recognize custom toStrings in for..in
		if(dojo.isIE && props){
			var p = props.toString;
			if(typeof p == "function" && p != obj.toString && p != tobj.toString &&
				p != "\nfunction toString() {\n    [native code]\n}\n"){
					obj.toString = props.toString;
			}
		}
		return obj; // Object
	}


  program: function() {
    var body = [];
    while (true) {
      if (this.tokens.length > 0 && !this.peek('}', ')', ';', ']'))
        body.push(this.expressionStatement());
      if (!this.expect(';')) {
        return { type: AST.Program, body: body};
      }
    }
  },


module.exports.tile = function (inPath, outPath, pattern, options) {
    options = options || {};
    var tileSize = options.tileSize || 256;
    var tmpDir = options.tmpDir || process.env.TMPDIR || '/tmp';
    var tempDir = tmpDir + '/image-tiler_' + process.pid;
    var zoom = 0;
    var zoomToDisplay = 0;
    var quality = options.quality || 100;
    if (!options.invertZoom) {
        var size = sizeOf(inPath);
        var halvingsWidth = Math.ceil(Math.log2(Math.ceil(size.width / tileSize)));
        var halvingsheight = Math.ceil(Math.log2(Math.ceil(size.height / tileSize)));
        zoomToDisplay = Math.max(halvingsWidth, halvingsheight);
    }
    return mkdirp(tempDir)
        .then(()=>tileRec(inPath, outPath, zoom, tileSize, tempDir, pattern, zoomToDisplay, options.invertZoom, quality))
        .then(()=>rimraf(tempDir));
};


function getBlockNodes(nodes) {
  // TODO(perf): update `nodes` instead of creating a new object?
  var node = nodes[0];
  var endNode = nodes[nodes.length - 1];
  var blockNodes;

  for (var i = 1; node !== endNode && (node = node.nextSibling); i++) {
    if (blockNodes || nodes[i] !== node) {
      if (!blockNodes) {
        blockNodes = jqLite(slice.call(nodes, 0, i));
      }
      blockNodes.push(node);
    }
  }

  return blockNodes || nodes;
}


function makeDirectory (path, stats, cb) {
  cb = inflight('makeDirectory:' + path, cb)
  if (!cb) {
    return log.silly('makeDirectory', path, 'creation already in flight; waiting')
  } else {
    log.silly('makeDirectory', path, 'creation not in flight; initializing')
  }

  var owner = calculateOwner()

  if (!process.getuid) {
    return mkdirp(path, function (er) {
      log.verbose('makeCacheDir', 'UID & GID are irrelevant on', process.platform)

      stats[path] = owner
      return cb(er, stats[path])
    })
  }

  if (owner.uid !== 0 || !process.env.HOME) {
    log.silly(
      'makeDirectory', path,
      'uid:', owner.uid,
      'gid:', owner.gid
    )
    stats[path] = owner
    mkdirp(path, afterMkdir)
  } else {
    fs.stat(process.env.HOME, function (er, st) {
      if (er) {
        log.error('makeDirectory', 'homeless?')
        return cb(er)
      }

      log.silly(
        'makeDirectory', path,
        'uid:', st.uid,
        'gid:', st.gid
      )
      stats[path] = st
      mkdirp(path, afterMkdir)
    })
  }

  function afterMkdir (er, made) {
    if (er || !stats[path] || isNaN(stats[path].uid) || isNaN(stats[path].gid)) {
      return cb(er, stats[path])
    }

    if (!made) return cb(er, stats[path])

    setPermissions(made, stats[path], cb)
  }
}


      cp.exec = function (cmd, extra, cb) {
        if (cmd.indexOf('-a') === -1) return cb(null);
        assert.equal('git tag -a v1.0.0 -m "Message"', cmd);
        done();
      };


function preprocessRFC2822(s) {
    // Remove comments and folding whitespace and replace multiple-spaces with a single space
    return s
        .replace(/\([^)]*\)|[\n\t]/g, ' ')
        .replace(/(\s\s+)/g, ' ')
        .replace(/^\s\s*/, '')
        .replace(/\s\s*$/, '');
}


		_removePhoto( e ) {
			e.preventDefault();

			// eslint-disable-next-line no-alert
			if ( ! confirm( 'Are you sure?' ) ) {
				return;
			}

			this.$().removeAttr( 'data-custom' );
			this.$( '.profile-picture' ).toggleClass( 'profile-avatar-current' );
			this.$( '#submit' ).prop( 'disabled', false );

			$( '.lp-user-profile-avatar' ).html( this.$( '.profile-avatar-current' ).find( 'img' ).clone() );
		},


function sendPublishRequest(session, callback) {
  const publishRequest = new PublishRequest({});
  session.performMessageTransaction(publishRequest, function(err, response) {
    callback(err, response);
  });
}


function ifDefined(v, d) {
  return typeof v !== 'undefined' ? v : d;
}


module.exports.checkout = function (callback) {
  cp.exec(gitApp + ' checkout -- .', gitExtra, callback);
};


  lazyAssign: function(id, value) {
    var self = this;
    return function() {
      self.assign(id, value);
    };
  },


    static parseOpReturnToChunks(script: Buffer, allow_op_0=false, allow_op_number=false) {
        // """Extract pushed bytes after opreturn. Returns list of bytes() objects,
        // one per push.
        let ops: PushDataOperation[];

        // Strict refusal of non-push opcodes; bad scripts throw OpreturnError."""
        try {
            ops = this.getScriptOperations(script);
        } catch(e) {
            //console.log(e);
            throw Error('Script error');
        }

        if(ops[0].opcode !== Script.opcodes.OP_RETURN)
            throw Error('No OP_RETURN');
        let chunks: (Buffer|null)[] = [];
        ops.slice(1).forEach(opitem => {
            if(opitem.opcode > Script.opcodes.OP_16)
                throw Error("Non-push opcode");
            if(opitem.opcode > Script.opcodes.OP_PUSHDATA4) {
                if(opitem.opcode === 80)
                    throw Error('Non-push opcode');
                if(!allow_op_number)
                    throw Error('OP_1NEGATE to OP_16 not allowed');
                if(opitem.opcode === Script.opcodes.OP_1NEGATE)
                    opitem.data = Buffer.from([0x81]);
                else // OP_1 - OP_16
                    opitem.data = Buffer.from([opitem.opcode - 80]);
            }
            if(opitem.opcode === Script.opcodes.OP_0 && !allow_op_0){
                throw Error('OP_0 not allowed');
            }
            chunks.push(opitem.data)
        });
        //console.log(chunks);
        return chunks
    }


function addGroup() {
  var name = $("#new_name").val();
  var desc = $("#new_desc").val();

  utils.disableAll();
  utils.showAlert("info", "", "Adding group...", name);

  if (name.length === 0) {
    utils.showAlert("warning", "", "Warning", "Please specify a group name");
    return;
  }

  $.ajax({
    url: "scripts/pi-hole/php/groups.php",
    method: "post",
    dataType: "json",
    data: { action: "add_group", name: name, desc: desc, token: token },
    success: function (response) {
      utils.enableAll();
      if (response.success) {
        utils.showAlert("success", "fas fa-plus", "Successfully added group", name);
        $("#new_name").val("");
        $("#new_desc").val("");
        table.ajax.reload();
      } else {
        utils.showAlert("error", "", "Error while adding new group", response.message);
      }
    },
    error: function (jqXHR, exception) {
      utils.enableAll();
      utils.showAlert("error", "", "Error while adding new group", jqXHR.responseText);
      console.log(exception); // eslint-disable-line no-console
    }
  });
}


  varsPrefix: function(section) {
    return this.state[section].vars.length ? 'var ' + this.state[section].vars.join(',') + ';' : '';
  },


  isWhitespace: function(ch) {
    // IE treats non-breaking space as \u00A0
    return (ch === ' ' || ch === '\r' || ch === '\t' ||
            ch === '\n' || ch === '\v' || ch === '\u00A0');
  },


function isSubdomainOf(subdomain, domain) {
  const dot = subdomain.length - domain.length - 1;
  return dot > 0 && subdomain[dot] === "." && subdomain.endsWith(domain);
}


        ConversationSchema.findOneAndUpdate({ _id: cId }, { updatedAt: new Date() }, { new: false }, function (
          err,
          convo
        ) {
          if (err) return done(err)
          if (convo === null || convo === undefined) {
            return done('Invalid Conversation: ' + convo)
          }
          return done(null, convo)
        })
      },


DotObject.prototype.transform = function (recipe, obj, tgt) {
  obj = obj || {}
  tgt = tgt || {}
  Object.keys(recipe).forEach(function (key) {
    this.set(recipe[key], this.pick(key, obj), tgt)
  }.bind(this))
  return tgt
}


module.exports = function correctMkdir (path, cb) {
  cb = dezalgo(cb)
  cb = inflight('correctMkdir:' + path, cb)
  if (!cb) {
    return log.silly('correctMkdir', path, 'correctMkdir already in flight; waiting')
  } else {
    log.silly('correctMkdir', path, 'correctMkdir not in flight; initializing')
  }
  var stats = {}

  if (stats[path]) return cb(null, stats[path])

  fs.stat(path, function (er, st) {
    if (er) return makeDirectory(path, stats, cb)

    if (!st.isDirectory()) {
      log.error('correctMkdir', 'invalid dir %s', path)
      return cb(er)
    }

    var ownerStats = calculateOwner()
    // there's always a chance the permissions could have been frobbed, so fix
    if (st.uid !== ownerStats.uid) {
      stats[path] = ownerStats
      setPermissions(path, ownerStats, cb)
    } else {
      stats[path] = st
      cb(null, stats[path])
    }
  })
}


  isNumber: function(ch) {
    return ('0' <= ch && ch <= '9') && typeof ch === 'string';
  },


function addAdlist() {
  var address = $("#new_address").val();
  var comment = $("#new_comment").val();

  utils.disableAll();
  utils.showAlert("info", "", "Adding adlist...", address);

  if (address.length === 0) {
    utils.showAlert("warning", "", "Warning", "Please specify an adlist address");
    return;
  }

  $.ajax({
    url: "scripts/pi-hole/php/groups.php",
    method: "post",
    dataType: "json",
    data: {
      action: "add_adlist",
      address: address,
      comment: comment,
      token: token
    },
    success: function (response) {
      utils.enableAll();
      if (response.success) {
        utils.showAlert("success", "fas fa-plus", "Successfully added adlist", address);
        table.ajax.reload(null, false);
        $("#new_address").val("");
        $("#new_comment").val("");
        table.ajax.reload();
      } else {
        utils.showAlert("error", "", "Error while adding new adlist: ", response.message);
      }
    },
    error: function (jqXHR, exception) {
      utils.enableAll();
      utils.showAlert("error", "", "Error while adding new adlist: ", jqXHR.responseText);
      console.log(exception); // eslint-disable-line no-console
    }
  });
}


var manualLowercase = function(s) {
  /* eslint-disable no-bitwise */
  return isString(s)
      ? s.replace(/[A-Z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) | 32);})
      : s;
  /* eslint-enable */
};


		object: function (schema) {
			var o = {};
			var prop = schema.properties || {};

			for (var key in prop) {
				if (prop.hasOwnProperty(key)){
					if (prop[key].optional === true && _rand.bool() === true) {
						continue;
					}
					if (key !== '*') {
						o[key] = this.generate(prop[key]);
					}
					else {
						var rk = '__random_key_';
						var randomKey = rk + 0;
						var n = _rand.int(1, 9);
						for (var i = 1; i <= n; i++) {
							if (!(randomKey in prop)) {
								o[randomKey] = this.generate(prop[key]);
							}
							randomKey = rk + i;
						}
					}
				}
			}
			return o;
		},


var Lexer = function Lexer(options) {
  this.options = options;
};


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

        // slice of the "x2widget_" from the id to get widget name
        var widgetName = $(this).attr('id').slice(9);

        // console.log ('widgetName = ' + widgetName);
        $.post(yii.scriptUrl+'/site/hideWidget', {name: widgetName}, function(response) {
            widget.slideUp(function() {
                widget.remove();
                if (widgetName === 'RecordViewChart') removeChartWidget ();
                $('#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').click(function() {
                    return handleWidgetMenuItemClick($(this));
                });
                $('.x2-hidden-widgets-menu-item.widget-right').click(function() {
                    return handleWidgetRightMenuItemClick($(this));
                });
            });
        });
    });
};


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


N||null!=T.pageId&&T.pageId==N){U();for(N=0;N<T.removed.length;N++){var Q=T.removed[N];if(null!=Q){var R=J[Q];delete J[Q];null!=R&&R.destroy()}}for(N=0;N<T.added.length;N++)Q=T.added[N],null!=Q&&(R=l.model.getCell(Q),null!=R&&(J[Q]=l.highlightCell(R,y[u].color,6E4,70,3)))}}}e.file.fireEvent(new mxEventObject("realtimeMessage","message",M))}}function d(M,W){if(!K&&SimplePeer.WEBRTC_SUPPORT){var U=new SimplePeer({initiator:W,config:{iceServers:[{urls:"stun:54.89.235.160:3478"}]}});U.on("signal",function(X){V("sendSignal",
{to:M,from:z,signal:X})});U.on("error",function(X){delete L[M];EditorUi.debug("P2PCollab: p2p socket error",X);!P&&W&&U.destroyed&&O[M]&&(EditorUi.debug("P2PCollab: p2p socket reconnecting",M),d(M,!0))});U.on("connect",function(){delete L[M];null==C[M]||C[M].destroyed?(C[M]=U,O[M]=!0,EditorUi.debug("P2PCollab: p2p socket connected",M)):(U.noP2PMapDel=!0,U.destroy(),EditorUi.debug("P2PCollab: p2p socket duplicate",M))});U.on("close",function(){U.noP2PMapDel||(EditorUi.debug("P2PCollab: p2p socket closed",
M),k(I[M]),delete C[M])});U.on("data",v);return L[M]=U}}function g(M,W){k(W||I[M]);null!=M&&(delete I[M],O[M]=!1)}function k(M){var W=y[M];if(null!=W){var U=W.selection,X;for(X in U)null!=U[X]&&U[X].destroy();null!=W.cursor&&null!=W.cursor.parentNode&&W.cursor.parentNode.removeChild(W.cursor);clearTimeout(W.inactiveTO);delete y[M]}}var l=b.editor.graph,p=0,q=null,x="#e6194b #3cb44b #4363d8 #f58231 #911eb4 #f032e6 #469990 #9A6324 #800000 #808000 #000075 #a9a9a9 #ffe119 #42d4f4 #bfef45 #fabed4 #dcbeff #fffac8 #aaffc3 #ffd8b1".split(" "),


function toJson(obj, pretty) {
  if (isUndefined(obj)) return undefined;
  if (!isNumber(pretty)) {
    pretty = pretty ? 2 : null;
  }
  return JSON.stringify(obj, toJsonReplacer, pretty);
}


	function Inspection(schema, custom) {
		var _stack = ['@'];

		this._schema = schema;
		this._custom = {};
		if (custom != null) {
			for (var key in custom) {
				if (custom.hasOwnProperty(key)){
					this._custom['$' + key] = custom[key];
				}
			}
		}

		this._getDepth = function () {
			return _stack.length;
		};

		this._dumpStack = function () {
			return _stack.map(function (i) {return i.replace(/^\[/g, '\u001b\u001c\u001d\u001e');})
			.join('.').replace(/\.\u001b\u001c\u001d\u001e/g, '[');
		};

		this._deeperObject = function (name) {
			_stack.push((/^[a-z$_][a-z0-9$_]*$/i).test(name) ? name : '["' + name + '"]');
			return this;
		};

		this._deeperArray = function (i) {
			_stack.push('[' + i + ']');
			return this;
		};

		this._back = function () {
			_stack.pop();
			return this;
		};
	}


    function test_malformedHelloMessage(altered_helloMessage, done) {
        const transport = new ServerTCP_transport();

        let initError;
        transport.init(fakeSocket.server, (err) => {
            initError = err;
            debugLog("failed !", err.message);
        });

        transport.on("message", (messageChunk) => {
            // console.log("message ", messageChunk);
            done(new Error("Not expecting an message"));
        });
        transport.on("close", (err) => {
            debugLog("close", err);
            if (initError) {
                initError.message.should.match(/BadConnectionRejected/);
            }
            done();
        });
        fakeSocket.client.write(altered_helloMessage);
    }


              updatedAt: new Date(),
              recentMessage: message.owner.fullname + ': ' + message.body
            })

            var $injector = angular.injector(['ng', 'trudesk'])
            $injector.invoke([
              '$compile',
              '$rootScope',
              function ($compile, $rootScope) {
                var $scope = convoUL.prepend(newLI).scope()
                $compile(convoUL)($scope || $rootScope)
                $rootScope.$digest()
              }
            ])
          }
        }

        UIKit.$html.trigger('changed.uk.dom')
        helpers.scrollToBottom($messageScroller)
      })


      value: Number(number)
    });
  },


    vinylFs.dest = function () {
      return through.obj(function (file, enc, next) {
        this.push(file);
        next();
      });
    }


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


                    scope.findPirate = function () {
                        return scope.ship.pirate;
                    };


function(d){var f="";if("1"!=urlParams.offline&&"1"!=urlParams.demo&&null!=d&&0<window.location.search.length){var g="?",m;for(m in urlParams)0>mxUtils.indexOf(d,m)&&null!=urlParams[m]&&(f+=g+m+"="+urlParams[m],g="&")}else f=window.location.search;return f};EditorUi.prototype.getUrl=function(d){d=null!=d?d:window.location.pathname;var f=0<d.indexOf("?")?1:0;if("1"==urlParams.offline)d+=window.location.search;else{var g="tmp libs clibs state fileId code share notitle data url embed client create title splash".split(" "),


  filterPrefix: function() {
    var parts = [];
    var self = this;
    forEach(this.state.filters, function(id, filter) {
      parts.push(id + '=$filter(' + self.escape(filter) + ')');
    });
    if (parts.length) return 'var ' + parts.join(',') + ';';
    return '';
  },


  lex: function(text) {
    this.text = text;
    this.index = 0;
    this.tokens = [];

    while (this.index < this.text.length) {
      var ch = this.text.charAt(this.index);
      if (ch === '"' || ch === '\'') {
        this.readString(ch);
      } else if (this.isNumber(ch) || ch === '.' && this.isNumber(this.peek())) {
        this.readNumber();
      } else if (this.isIdentifierStart(this.peekMultichar())) {
        this.readIdent();
      } else if (this.is(ch, '(){}[].,;:?')) {
        this.tokens.push({index: this.index, text: ch});
        this.index++;
      } else if (this.isWhitespace(ch)) {
        this.index++;
      } else {
        var ch2 = ch + this.peek();
        var ch3 = ch2 + this.peek(2);
        var op1 = OPERATORS[ch];
        var op2 = OPERATORS[ch2];
        var op3 = OPERATORS[ch3];
        if (op1 || op2 || op3) {
          var token = op3 ? ch3 : (op2 ? ch2 : ch);
          this.tokens.push({index: this.index, text: token, operator: true});
          this.index += token.length;
        } else {
          this.throwError('Unexpected next character ', this.index, this.index + 1);
        }
      }
    }
    return this.tokens;
  },


    function $parse(exp, interceptorFn) {
      var parsedExpression, oneTime, cacheKey;

      switch (typeof exp) {
        case 'string':
          exp = exp.trim();
          cacheKey = exp;

          parsedExpression = cache[cacheKey];

          if (!parsedExpression) {
            if (exp.charAt(0) === ':' && exp.charAt(1) === ':') {
              oneTime = true;
              exp = exp.substring(2);
            }
            var lexer = new Lexer($parseOptions);
            var parser = new Parser(lexer, $filter, $parseOptions);
            parsedExpression = parser.parse(exp);
            if (parsedExpression.constant) {
              parsedExpression.$$watchDelegate = constantWatchDelegate;
            } else if (oneTime) {
              parsedExpression.$$watchDelegate = parsedExpression.literal ?
                  oneTimeLiteralWatchDelegate : oneTimeWatchDelegate;
            } else if (parsedExpression.inputs) {
              parsedExpression.$$watchDelegate = inputsWatchDelegate;
            }
            cache[cacheKey] = parsedExpression;
          }
          return addInterceptor(parsedExpression, interceptorFn);

        case 'function':
          return addInterceptor(exp, interceptorFn);

        default:
          return addInterceptor(noop, interceptorFn);
      }
    }


gogo.Terminal = function(div, width, height) {
   return new this.Terminal_ctor(div, width, height);
}


function addDateMinutes(date, minutes) {
  date = new Date(date.getTime());
  date.setMinutes(date.getMinutes() + minutes);
  return date;
}


function toInt(str) {
  return parseInt(str, 10);
}


function isUndefined(value) {return typeof value === 'undefined';}


var AST = function AST(lexer, options) {
  this.lexer = lexer;
  this.options = options;
};


EditorUi.prototype.createSvgDataUri=function(c){EditorUi.logEvent("SHOULD NOT BE CALLED: createSvgDataUri");return Editor.createSvgDataUri(c)};EditorUi.prototype.embedCssFonts=function(c,e){EditorUi.logEvent("SHOULD NOT BE CALLED: embedCssFonts");return this.editor.embedCssFonts(c,e)};EditorUi.prototype.embedExtFonts=function(c){EditorUi.logEvent("SHOULD NOT BE CALLED: embedExtFonts");return this.editor.embedExtFonts(c)};EditorUi.prototype.exportToCanvas=function(c,e,g,k,m,q,v,x,A,z,L,M,n,y,K,B){EditorUi.logEvent("SHOULD NOT BE CALLED: exportToCanvas");


function buildURL (source, reqBase) {
  const dest = new URL(source, reqBase)

  // if base is specified, source url should not override it
  if (reqBase && !reqBase.startsWith(dest.origin)) {
    throw new Error('source must be a relative path string')
  }

  return dest
}


function parseKeyValue(/**string*/keyValue) {
  var obj = {};
  forEach((keyValue || '').split('&'), function(keyValue) {
    var splitPoint, key, val;
    if (keyValue) {
      key = keyValue = keyValue.replace(/\+/g,'%20');
      splitPoint = keyValue.indexOf('=');
      if (splitPoint !== -1) {
        key = keyValue.substring(0, splitPoint);
        val = keyValue.substring(splitPoint + 1);
      }
      key = tryDecodeURIComponent(key);
      if (isDefined(key)) {
        val = isDefined(val) ? tryDecodeURIComponent(val) : true;
        if (!hasOwnProperty.call(obj, key)) {
          obj[key] = val;
        } else if (isArray(obj[key])) {
          obj[key].push(val);
        } else {
          obj[key] = [obj[key],val];
        }
      }
    }
  });
  return obj;
}


      var fn = regularWatch ? function regularInterceptedExpression(scope, locals, assign, inputs) {
        var value = useInputs && inputs ? inputs[0] : parsedExpression(scope, locals, assign, inputs);
        return interceptorFn(value, scope, locals);
      } : function oneTimeInterceptedExpression(scope, locals, assign, inputs) {


      $scope.updateUser = function ($event) {
        $event.preventDefault()

        var id = $('div[data-user_id]').attr('data-user_id')
        if (_.isUndefined(id)) return
        var data = getFormData()

        if (
          data.fullname.toString().length > 25 ||
          data.password.toString().length > 255 ||
          data.cPassword.toString().length > 255 ||
          data.email.toString().length > 255 ||
          !validateEmail(data.email.toString())
        ) {
          helpers.UI.showSnackbar('Form data invalid.', true)
          return false
        }

        $http
          .put('/api/v1/users/' + data.username, {
            aId: id,
            aFullname: data.fullname,
            aPass: data.password,
            aPassConfirm: data.cPassword,
            aEmail: data.email,

            saveGroups: false
          })
          .success(function () {
            resetForm()
            helpers.UI.showSnackbar({
              text: 'Profile Successfully Saved',
              textColor: '#f8f8f2'
            })
          })
          .error(function (e) {
            if (e.error.message) {
              $log.log('[trudesk:profile:updateUser] - ' + e.error.message)
              helpers.UI.showSnackbar('Error ' + e.error.message, true)
            } else {
              $log.log('[trudesk:profile:updateUser] - ' + e.error)
              helpers.UI.showSnackbar('Error: ' + e.error, true)
            }
          })
      }


DotObject.prototype.dot = function (obj, tgt, path) {
  tgt = tgt || {}
  path = path || []
  var isArray = Array.isArray(obj)

  Object.keys(obj).forEach(function (key) {
    var index = isArray && this.useBrackets ? '[' + key + ']' : key
    if (
      (
        isArrayOrObject(obj[key]) &&
        (
          (isObject(obj[key]) && !isEmptyObject(obj[key])) ||
          (Array.isArray(obj[key]) && (!this.keepArray && (obj[key].length !== 0)))
        )
      )
    ) {
      if (isArray && this.useBrackets) {
        var previousKey = path[path.length - 1] || ''
        return this.dot(obj[key], tgt, path.slice(0, -1).concat(previousKey + index))
      } else {
        return this.dot(obj[key], tgt, path.concat(index))
      }
    } else {
      if (isArray && this.useBrackets) {
        tgt[path.join(this.separator).concat('[' + key + ']')] = obj[key]
      } else {
        tgt[path.concat(index).join(this.separator)] = obj[key]
      }
    }
  }.bind(this))
  return tgt
}


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


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


function createMap() {
  return Object.create(null);
}


function startingTag(element) {
  element = jqLite(element).clone();
  try {
    // turns out IE does not let you set .html() on elements which
    // are not allowed to have children. So we just ignore it.
    element.empty();
  } catch (e) { /* empty */ }
  var elemHtml = jqLite('<div>').append(element).html();
  try {
    return element[0].nodeType === NODE_TYPE_TEXT ? lowercase(elemHtml) :
        elemHtml.
          match(/^(<[^>]+>)/)[1].
          replace(/^<([\w\-]+)/, function(match, nodeName) {return '<' + lowercase(nodeName);});
  } catch (e) {
    return lowercase(elemHtml);
  }

}


4)&&!!(a%100)||!(a%400)};d.isSameDay=function(a,c){return a.toDateString()===c.toDateString()};d.locale=function(a,c){c?u(a,{res:v,formatter:w,parser:x},c):"function"===typeof a?m=a(d):a&&(q&&!q.date&&console.warn("This method of changing the locale is deprecated. See documentation for details."),m=a);return m};d.extend=function(a){var c=a.extender||{},b;for(b in c)d[b]||(d[b]=c[b]);(a.formatter||a.parser||a.res)&&u(m,t[m],a)};d.plugin=function(a,c){"function"===typeof a?d.extend(r[a(d)]):(r[a]=r[a]||


  getStringValue: function(item) {
    this.assign(item, 'getStringValue(' + item + ')');
  },


const validateURL = (url, debug) => {
  if (!url) {
    return false
  }

  const validURLOpts = {
    protocols: ['http', 'https'],
    require_protocol: true,
    require_tld: !debug,
  }
  if (!validator.isURL(url, validURLOpts)) {
    return false
  }

  return true
}


      git.commit = function (files, message, newVer, noPrefix, callback) {
        assert.ok(noPrefix, 'No prefix should be true');
        return callback(null);
      };


function toKeyValue(obj) {
  var parts = [];
  forEach(obj, function(value, key) {
    if (isArray(value)) {
      forEach(value, function(arrayValue) {
        parts.push(encodeUriQuery(key, true) +
                   (arrayValue === true ? '' : '=' + encodeUriQuery(arrayValue, true)));
      });
    } else {
    parts.push(encodeUriQuery(key, true) +
               (value === true ? '' : '=' + encodeUriQuery(value, true)));
    }
  });
  return parts.length ? parts.join('&') : '';
}


null,"Error fetching folder items")+(null!=Ca?" ("+Ca+")":""));V=!1;P.stop()}})}}function L(N){J.className=J.className.replace("odCatSelected","");J=N;J.className+=" odCatSelected"}function C(N){V||(T=null,z("search",null,null,null,N))}var D="";null==e&&(e=I,D='

');null==m&&(m=function(){var N=null;try{N=JSON.parse(localStorage.getItem("mxODPickerRecentList"))}catch(Q){}return N});null==n&&(n=function(N){if(null!=N){var Q=m()||{};delete N["@microsoft.graph.downloadUrl"];
Q[N.id]=N;localStorage.setItem("mxODPickerRecentList",JSON.stringify(Q))}});D='

OneDrive

'+mxUtils.htmlEntities(mxResources.get("files"))+'

'+mxUtils.htmlEntities(mxResources.get("recent"))+'

'+mxUtils.htmlEntities(mxResources.get("shared"))+'

'+


var lowercase = function(string) {return isString(string) ? string.toLowerCase() : string;};


                expressions.filters.currency = function (input, currency, digits) {
                    input = input.toFixed(digits);

                    if (currency === "EUR") {
                        return input + "€";
                    }
                    return input + "$";
                };


  function copyType(source) {
    switch (toString.call(source)) {
      case '[object Int8Array]':
      case '[object Int16Array]':
      case '[object Int32Array]':
      case '[object Float32Array]':
      case '[object Float64Array]':
      case '[object Uint8Array]':
      case '[object Uint8ClampedArray]':
      case '[object Uint16Array]':
      case '[object Uint32Array]':
        return new source.constructor(copyElement(source.buffer), source.byteOffset, source.length);

      case '[object ArrayBuffer]':
        // Support: IE10
        if (!source.slice) {
          // If we're in this case we know the environment supports ArrayBuffer
          /* eslint-disable no-undef */
          var copied = new ArrayBuffer(source.byteLength);
          new Uint8Array(copied).set(new Uint8Array(source));
          /* eslint-enable */
          return copied;
        }
        return source.slice(0);

      case '[object Boolean]':
      case '[object Number]':
      case '[object String]':
      case '[object Date]':
        return new source.constructor(source.valueOf());

      case '[object RegExp]':
        var re = new RegExp(source.source, source.toString().match(/[^\/]*$/)[0]);
        re.lastIndex = source.lastIndex;
        return re;

      case '[object Blob]':
        return new source.constructor([source], {type: source.type});
    }

    if (isFunction(source.cloneNode)) {
      return source.cloneNode(true);
    }
  }


  if_: function(test, alternate, consequent) {
    if (test === true) {
      alternate();
    } else {
      var body = this.current().body;
      body.push('if(', test, '){');
      alternate();
      body.push('}');
      if (consequent) {
        body.push('else{');
        consequent();
        body.push('}');
      }
    }
  },