public static function parseAndTrimImport($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); //do this no matter what...in case someone added a quote in a non HTML field
        if (!$isHTML) {
            //if HTML, then leave the single quotes alone, otheriwse replace w/ special Char
            $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 PMA_secureSession()
{
    // prevent session fixation and XSS
    // (better to use session_status() if available)
    if ((PMA_PHP_INT_VERSION >= 50400 && session_status() === PHP_SESSION_ACTIVE)
        || (PMA_PHP_INT_VERSION < 50400 && session_id() !== '')
    ) {
        session_regenerate_id(true);
    }
    $_SESSION[' PMA_token '] = md5(uniqid(rand(), true));
}


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

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


    public function confirm() {
        global $db;

        // make sure we have what we need.
        if (empty($this->params['key'])) expQueue::flashAndFlow('error', gt('The security key for account was not supplied.'));
        if (empty($this->params['id'])) expQueue::flashAndFlow('error', gt('The subscriber id for account was not supplied.'));

        // verify the id/key pair
        $id = $db->selectValue('subscribers','id', 'id='.$this->params['id'].' AND hash="'.$this->params['key'].'"');
        if (empty($id)) expQueue::flashAndFlow('error', gt('We could not find any subscriptions matching the ID and Key you provided.'));

        // activate this users pending subscriptions
        $sub = new stdClass();
        $sub->enabled = 1;
        $db->updateObject($sub, 'expeAlerts_subscribers', 'subscribers_id='.$id);

        // find the users active subscriptions
        $ealerts = expeAlerts::getBySubscriber($id);
        assign_to_template(array(
            'ealerts'=>$ealerts
        ));
    }


function PMA_linkURL($url)
{
    if (!preg_match('#^https?://#', $url) || defined('PMA_SETUP')) {
        return $url;
    }

    if (!function_exists('PMA_URL_getCommon')) {
        include_once './libraries/url_generating.lib.php';
    }
    $params = array();
    $params['url'] = $url;

    $url = PMA_URL_getCommon($params);
    //strip off token and such sensitive information. Just keep url.
    $arr = parse_url($url);
    parse_str($arr["query"], $vars);
    $query = http_build_query(array("url" => $vars["url"]));
    $url = './url.php?' . $query;

    return $url;
}


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


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

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


    public function putAction(Request $request)
    {
        $this->checkArguments($request);
        $user = $this->tokenStorage->getToken()->getUser();
        $this->userManager->save($request->request->all(), $request->get('locale'), $user->getId(), true);

        $user->setFirstName($request->get('firstName'));
        $user->setLastName($request->get('lastName'));

        $this->objectManager->flush();

        $view = View::create($user);

        $context = new Context();
        $context->setGroups(['profile']);

        $view->setContext($context);

        return $this->viewHandler->handle($view);
    }


	public function setHeadItemAttributes( $attributes ) {
		$this->headItemAttributes = \Sanitizer::fixTagAttributes( $attributes, 'li' );
	}


	public function formatTemplateArg( $arg, $s, $argNr, $firstCall, $maxLength, Article $article ) {
		$tableFormat = $this->getParameters()->getParameter( 'tablerow' );
		// we could try to format fields differently within the first call of a template
		// currently we do not make such a difference

		// if the result starts with a '-' we add a leading space; thus we avoid a misinterpretation of |- as
		// a start of a new row (wiki table syntax)
		if ( array_key_exists( "$s.$argNr", $tableFormat ) ) {
			$n = -1;
			if ( $s >= 1 && $argNr == 0 && !$firstCall ) {
				$n = strpos( $tableFormat["$s.$argNr"], '|' );
				if ( $n === false || !( strpos( substr( $tableFormat["$s.$argNr"], 0, $n ), '{' ) === false ) || !( strpos( substr( $tableFormat["$s.$argNr"], 0, $n ), '[' ) === false ) ) {
					$n = -1;
				}
			}
			$result = str_replace( '%%', $arg, substr( $tableFormat["$s.$argNr"], $n + 1 ) );
			$result = str_replace( '%PAGE%', $article->mTitle->getPrefixedText(), $result );
			$result = str_replace( '%IMAGE%', $this->parseImageUrlWithPath( $arg ), $result ); //@TODO: This just blindly passes the argument through hoping it is an image.  --Alexia
			$result = $this->cutAt( $maxLength, $result );
			if ( strlen( $result ) > 0 && $result[0] == '-' ) {
				return ' ' . $result;
			} else {
				return $result;
			}
		}
		$result = $this->cutAt( $maxLength, $arg );
		if ( strlen( $result ) > 0 && $result[0] == '-' ) {
			return ' ' . $result;
		} else {
			return $result;
		}
	}


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


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


	public static function getSetting( $setting ) {
		return ( array_key_exists( $setting, self::$settings ) ? self::$settings[$setting] : null );
	}


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


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


function captureAuthorization() {
        //eDebug($this->params,true);
        $order = new order($this->params['id']);
        /*eDebug($this->params);
        //eDebug($order,true);*/
        //eDebug($order,true);
        //$billing = new billing();

        //eDebug($billing, true);
        //$billing->calculator = new $calcname($order->billingmethod[0]->billingcalculator_id);
        $calc         = $order->billingmethod[0]->billingcalculator->calculator;
        $calc->config = $order->billingmethod[0]->billingcalculator->config;

        //$calc = new $calc-
        //eDebug($calc,true);
        if (!method_exists($calc, 'delayed_capture')) {
            flash('error', gt('The Billing Calculator does not support delayed capture'));
            expHistory::back();
        }

        $result = $calc->delayed_capture($order->billingmethod[0], $this->params['capture_amt'], $order);

        if (empty($result->errorCode)) {
            flash('message', gt('The authorized payment was successfully captured'));
            expHistory::back();

        } else {
            flash('error', gt('An error was encountered while capturing the authorized payment.') . '

' . $result->message);
            expHistory::back();
        }
    }


foreach ($elem[2] as $field) {
            echo '

                           '.$field[1].' :
                        ';
            if ($field[3] === "masked") {
                echo '

<input type="hidden" id="hid_field_'.htmlspecialchars($field[0]).'_'.$elem[0].'" class="fields" />';
            } else {
                echo '

<input type="hidden" id="hid_field_'.htmlspecialchars($field[0]).'_'.$elem[0].'" class="fields" />';
            }
            echo '

';
        }


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

		if(isset($this->params['id'])) {
			$vendor = $vendor->find('first', 'id =' .$this->params['id']);
			assign_to_template(array(
                'vendor'=>$vendor
            ));
		}
	}


  public function __construct() {
    $this->smtp_conn = 0;
    $this->error = null;
    $this->helo_rply = null;

    $this->do_debug = 0;
  }


	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 showall() {
	    expHistory::set('viewable', $this->params);
	    $hv = new help_version();
	    //$current_version = $hv->find('first', 'is_current=1');
	    $ref_version = $hv->find('first', 'version=\''.$this->help_version.'\'');

        // pagination parameter..hard coded for now.
		$where = $this->aggregateWhereClause();
	    $where .= 'AND help_version_id='.(empty($ref_version->id)?'0':$ref_version->id);


	public function formatItem( Article $article, $pageText = null ) {
		global $wgLang;

		$item = '';

		// DPL Article, not MediaWiki.
		$date = $article->getDate();
		if ( $date !== null ) {
			$item .= $date . ' ';
			if ( $article->mRevision !== null ) {
				$item .= '[{{fullurl:' . $article->mTitle . '|oldid=' . $article->mRevision . '}} ' . htmlspecialchars( $article->mTitle ) . ']';
			} else {
				$item .= $article->mLink;
			}
		} else {
			// output the link to the article
			$item .= $article->mLink;
		}

		if ( $article->mSize != null ) {
			$byte = 'B';
			$pageLength = $wgLang->formatNum( $article->mSize );
			$item .= " [{$pageLength} {$byte}]";
		}

		if ( $article->mCounter !== null ) {
			$contLang = MediaWikiServices::getInstance()->getContentLanguage();

			$item .= ' ' . $contLang->getDirMark() . '(' . wfMessage( 'hitcounters-nviews', $wgLang->formatNum( $article->mCounter ) )->escaped() . ')';
		}

		if ( $article->mUserLink !== null ) {
			$item .= ' . . [[User:' . $article->mUser . '|' . $article->mUser . ']]';
			if ( $article->mComment != '' ) {
				$item .= ' { ' . $article->mComment . ' }';
			}
		}

		if ( $article->mContributor !== null ) {
			$item .= ' . . [[User:' . $article->mContributor . '|' . $article->mContributor . " $article->mContrib]]";
		}

		if ( !empty( $article->mCategoryLinks ) ) {
			$item .= ' . . <small>' . wfMessage( 'categories' ) . ': ' . implode( ' | ', $article->mCategoryLinks ) . '</small>';
		}

		if ( $this->getParameters()->getParameter( 'addexternallink' ) && $article->mExternalLink !== null ) {
			$item .= ' → ' . $article->mExternalLink;
		}

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

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

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

		return $item;
	}


    public function fromFile($filePath)
    {
        if ($filePath === null) {
            return;
        }

        $file = new FileObj($filePath);
        $this->file_name = $file->getFilename();
        $this->file_size = $file->getSize();
        $this->content_type = $file->getMimeType();
        $this->disk_name = $this->getDiskName();

        $this->putFile($file->getRealPath(), $this->disk_name);

        return $this;
    }


                    foreach ($day as $extevent) {
                        $event_cache = new stdClass();
                        $event_cache->feed = $extgcalurl;
                        $event_cache->event_id = $extevent->event_id;
                        $event_cache->title = $extevent->title;
                        $event_cache->body = $extevent->body;
                        $event_cache->eventdate = $extevent->eventdate->date;
                        if (isset($extevent->dateFinished) && $extevent->dateFinished != -68400)
                            $event_cache->dateFinished = $extevent->dateFinished;
                        if (isset($extevent->eventstart))
                            $event_cache->eventstart = $extevent->eventstart;
                        if (isset($extevent->eventend))
                            $event_cache->eventend = $extevent->eventend;
                        if (isset($extevent->is_allday))
                            $event_cache->is_allday = $extevent->is_allday;
                        $found = false;
                        if ($extevent->eventdate->date < $start)   // prevent duplicating events crossing month boundaries
                            $found = $db->selectObject('event_cache','feed="'.$extgcalurl.'" AND event_id="'.$event_cache->event_id.'" AND eventdate='.$event_cache->eventdate);
                        if (!$found)
                            $db->insertObject($event_cache,'event_cache');
                    }


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

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


    public function actionGetItems($modelType){

            $sql = 'SELECT id, name as value FROM x2_campaigns WHERE name LIKE :qterm ORDER BY name 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 __construct() {
		$this->setRichness( Config::getSetting( 'functionalRichness' ) );

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


	private function _addauthor( $option ) {
		//Addauthor can not be used with addlasteditor.
		if ( !isset( $this->parametersProcessed['addlasteditor'] ) || !$this->parametersProcessed['addlasteditor'] ) {
			$this->addTable( 'revision_actor_temp', 'rev' );
			$this->addWhere(
				[
					$this->tableNames['page'] . '.page_id = rev.revactor_page',
					'rev.revactor_timestamp = (SELECT MIN(rev_aux_min.revactor_timestamp) FROM ' . $this->tableNames['revision_actor_temp'] . ' AS rev_aux_min WHERE rev_aux_min.revactor_page = rev.revactor_page)'
				]
			);
			$this->_adduser( null, 'rev' );
		}
	}


  public function Turn() {
    $this->error = array("error" => "This method, TURN, of the SMTP ".
                                    "is not implemented");
    if($this->do_debug >= 1) {
      $this->edebug("SMTP -> NOTICE: " . $this->error["error"] . $this->CRLF . '<br />');
    }
    return false;
  }


    public function __construct(
        GlyphFinder $glyph_finder,
        ProjectXMLMerger $project_xml_merger,
        ConsistencyChecker $consistency_checker,
        TemplateDao $template_dao,
        ProjectManager $project_manager,
        EventDispatcherInterface $event_dispatcher,
    ) {
        $this->template_dao    = $template_dao;
        $this->templates       = [
            AgileALMTemplate::NAME => new AgileALMTemplate($glyph_finder, $project_xml_merger, $consistency_checker),
            ScrumTemplate::NAME => new ScrumTemplate($glyph_finder, $project_xml_merger, $consistency_checker),
            KanbanTemplate::NAME => new KanbanTemplate($glyph_finder, $project_xml_merger, $consistency_checker),
            IssuesTemplate::NAME => new IssuesTemplate($glyph_finder, $consistency_checker, $event_dispatcher),
            EmptyTemplate::NAME => new EmptyTemplate($glyph_finder),
        ];
        $this->project_manager = $project_manager;
        $this->glyph_finder    = $glyph_finder;

        $this->external_templates = self::getExternalTemplatesByName($event_dispatcher);
    }


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

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


			array_push($newgroupprivs, $type);
	}
	if(empty($newgroupprivs) || (count($newgroupprivs) == 1 &&
           in_array("cascade", $newgroupprivs))) {
		return array('status' => 'error',
                    'errorcode' => 53,
                    'errormsg' => 'Invalid or missing permissions list supplied');
	}
    updateUserOrGroupPrivs($groupid, $nodeid, $newgroupprivs, array(), "group");
	return array('status' => 'success');
}


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


public function Reset() {
    $this->error = null; // so no confusion is caused

    if(!$this->connected()) {
      $this->error = array(
              "error" => "Called Reset() without being connected");
      return false;
    }

    fputs($this->smtp_conn,"RSET" . $this->CRLF);

    $rply = $this->get_lines();
    $code = substr($rply,0,3);

    if($this->do_debug >= 2) {
      $this->edebug("SMTP -> FROM SERVER:" . $rply . $this->CRLF . '
');
    }

    if($code != 250) {
      $this->error =
        array("error" => "RSET failed",
              "smtp_code" => $code,
              "smtp_msg" => substr($rply,4));
      if($this->do_debug >= 1) {
        $this->edebug("SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '
');
      }
      return false;
    }

    return true;
  }


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

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

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


    public function testXForwarderForHeaderForForwardedRequests($xForwardedFor, $expected)
    {
        $this->setNextResponse();
        $server = array('REMOTE_ADDR' => '10.0.0.1');
        if (false !== $xForwardedFor) {
            $server['HTTP_X_FORWARDED_FOR'] = $xForwardedFor;
        }
        $this->request('GET', '/', $server);

        $this->assertEquals($expected, $this->kernel->getBackendRequest()->headers->get('X-Forwarded-For'));
    }


		public function merge($branch, $options = NULL)
		{
			$this->run('merge', $options, $branch);
			return $this;
		}


    public function __get($var) {

        switch ($var) {

            case 'configuration_array':
                $this->configuration_array = array();
                if ($this->configuration != ''){
                    $jsonData = json_decode($this->configuration,true);
                    if ($jsonData !== null) {
                        $this->configuration_array = $jsonData;
                    } else {
                        $this->configuration_array = array();
                    }
                }
                return $this->configuration_array;
                break;

            case 'name_support':
                return $this->name_support = $this->nick;
                break;

            case 'has_photo':
                return $this->filename != '';
                break;

            case 'has_photo_avatar':
                return $this->filename != '' || $this->avatar != '';
                break;

            case 'photo_path':
                $this->photo_path = ($this->filepath != '' ? '//' . $_SERVER['HTTP_HOST'] . erLhcoreClassSystem::instance()->wwwDir() : erLhcoreClassSystem::instance()->wwwImagesDir() ) .'/'. $this->filepath . $this->filename;
                return $this->photo_path;
                break;

            case 'file_path_server':
                return $this->filepath . $this->filename;
                break;

            default:
                break;
        }
    }


    function edit_order_item() {
        $oi = new orderitem($this->params['id'], true, true);
        if (empty($oi->id)) {
            flash('error', gt('Order item doesn\'t exist.'));
            expHistory::back();
        }
        $oi->user_input_fields = expUnserialize($oi->user_input_fields);
        $params['options'] = $oi->opts;
        $params['user_input_fields'] = $oi->user_input_fields;
        $oi->product           = new product($oi->product->id, true, true);
        if ($oi->product->parent_id != 0) {
            $parProd = new product($oi->product->parent_id);
            //$oi->product->optiongroup = $parProd->optiongroup;
            $oi->product = $parProd;
        }
        //FIXME we don't use selectedOpts?
//        $oi->selectedOpts = array();
//        if (!empty($oi->opts)) {
//            foreach ($oi->opts as $opt) {
//                $option = new option($opt[0]);
//                $og     = new optiongroup($option->optiongroup_id);
//                if (!isset($oi->selectedOpts[$og->id]) || !is_array($oi->selectedOpts[$og->id]))
//                    $oi->selectedOpts[$og->id] = array($option->id);
//                else
//                    array_push($oi->selectedOpts[$og->id], $option->id);
//            }
//        }
        //eDebug($oi->selectedOpts);

        assign_to_template(array(
            'oi' => $oi,
            'params' => $params
        ));
    }


                array_push($stack, $node);
            }
        }
        return array(
            'status' => 'success',
            'nodes' => $nodes);
    } else {
        return array(
            'status' => 'error',
            'errorcode' => 56,
            'errormsg' => 'User cannot access node content');
    }
}


    public function beforeAction($action)
    {
        // Bypass when not installed for installer
        if (empty(Yii::$app->params['installed']) &&
                  Yii::$app->controller->module != null &&
                  Yii::$app->controller->module->id == 'installer') {
            return true;
        }

        $this->handleDeprecatedSettings();
        $this->controllerAccess = $this->getControllerAccess($this->rules);

        if (!$this->controllerAccess->run()) {
            if (isset($this->controllerAccess->codeCallback) &&
                method_exists($this, $this->controllerAccess->codeCallback)) {
                // Call a specific function for current action filter,
                // may be used to filter a logged in user for some restriction e.g. "must change password"
                return call_user_func([$this, $this->controllerAccess->codeCallback]);
            } else if ($this->controllerAccess->code == 401) {
                return $this->loginRequired();
            } else {
                $this->forbidden();
            }
        }

        return parent::beforeAction($action);
    }


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


    function configure() {
        expHistory::set('editable', $this->params);
        // little bit of trickery so that that categories can have their own configs

        $this->loc->src = "@globalstoresettings";
        $config = new expConfig($this->loc);
        $this->config = $config->config;
        $pullable_modules = expModules::listInstalledControllers($this->baseclassname, $this->loc);
        $views = expTemplate::get_config_templates($this, $this->loc);

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

        $gr = new geoRegion();
        $regions = $gr->find('all');

        assign_to_template(array(
            'config'=>$this->config,
            'pullable_modules'=>$pullable_modules,
            'views'=>$views,
            'countries'=>$countries,
            'regions'=>$regions,
            'title'=>static::displayname()
        ));
    }


    public function testCookiePathWithEmptySetCookiePath($uriPath, $cookiePath)
    {
        $response = (new Response(200))
            ->withAddedHeader(
                'Set-Cookie',
                "foo=bar; expires={$this->futureExpirationDate()}; domain=www.example.com; path=;"
            )
            ->withAddedHeader(
                'Set-Cookie',
                "bar=foo; expires={$this->futureExpirationDate()}; domain=www.example.com; path=foobar;"
            )
        ;
        $request = (new Request('GET', $uriPath))->withHeader('Host', 'www.example.com');
        $this->jar->extractCookies($request, $response);

        self::assertSame($cookiePath, $this->jar->toArray()[0]['Path']);
        self::assertSame($cookiePath, $this->jar->toArray()[1]['Path']);
    }


    public function crossOriginRedirectProvider()
    {
        return [
            ['http://example.com?a=b', 'http://test.com/', false],
            ['https://example.com?a=b', 'https://test.com/', false],
            ['http://example.com?a=b', 'https://test.com/', false],
            ['https://example.com?a=b', 'http://test.com/', false],
            ['http://example.com?a=b', 'http://example.com/', true],
            ['https://example.com?a=b', 'https://example.com/', true],
            ['http://example.com?a=b', 'https://example.com/', true],
            ['https://example.com?a=b', 'http://example.com/', false],
        ];
    }


    public function __construct(
        CartService $cartService,
        int $defaultTtl,
        bool $httpCacheEnabled,
        MaintenanceModeResolver $maintenanceModeResolver
    ) {
        $this->cartService = $cartService;
        $this->defaultTtl = $defaultTtl;
        $this->httpCacheEnabled = $httpCacheEnabled;
        $this->maintenanceResolver = $maintenanceModeResolver;
    }


    public function safePath($filename = 'data.csv'){
        return implode(DIRECTORY_SEPARATOR, array(
                    Yii::app()->basePath,
                    'data',
                    $filename
                ));
    }


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

        $this->checkPermission($project, $filter);

        if ($this->customFilterModel->remove($filter['id'])) {
            $this->flash->success(t('Custom filter removed successfully.'));
        } else {
            $this->flash->failure(t('Unable to remove this custom filter.'));
        }

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


	public function paramRules() {
		return array(
			'title' => Yii::t('studio',$this->title),
			'info' => Yii::t('studio',$this->info),
			'modelRequired' => 'Contacts',
			'options' => array(
				array(
                    'name'=>'listId',
                    'label'=>Yii::t('studio','List'),
                    'type'=>'link',
                    'linkType'=>'X2List',
                    'linkSource'=>Yii::app()->createUrl(
					    CActiveRecord::model('X2List')->autoCompleteSource
				    )
                ),
			));
	}


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

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

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


    function showByModel() {
        global $order, $template, $db;

        expHistory::set('viewable', $this->params);
        $product = new product();
        $model = $product->find("first", 'model="' . $this->params['model'] . '"');
        //eDebug($model);
        $product_type = new $model->product_type($model->id);
        //eDebug($product_type);
        $tpl = $product_type->getForm('show');
        if (!empty($tpl)) $template = new controllertemplate($this, $tpl);
        //eDebug($template);
        $this->grabConfig(); // grab the global config
        assign_to_template(array(
            'config'        => $this->config,
            'product'       => $product_type,
            'last_category' => $order->lastcat
        ));
    }


    public function getBranches()
    {
        if (null === $this->branches) {
            $branches = array();
            $bookmarks = array();

            $this->process->execute('hg branches', $output, $this->repoDir);
            foreach ($this->process->splitLines($output) as $branch) {
                if ($branch && Preg::isMatch('(^([^\s]+)\s+\d+:([a-f0-9]+))', $branch, $match)) {
                    $branches[$match[1]] = $match[2];
                }
            }

            $this->process->execute('hg bookmarks', $output, $this->repoDir);
            foreach ($this->process->splitLines($output) as $branch) {
                if ($branch && Preg::isMatch('(^(?:[\s*]*)([^\s]+)\s+\d+:(.*)$)', $branch, $match)) {
                    $bookmarks[$match[1]] = $match[2];
                }
            }

            // Branches will have preference over bookmarks
            $this->branches = array_merge($bookmarks, $branches);
        }

        return $this->branches;
    }


    public function saveConfig() {
        if (!empty($this->params['aggregate']) || !empty($this->params['pull_rss'])) {
            if ($this->params['order'] == 'rank ASC') {
                expValidator::failAndReturnToForm(gt('User defined ranking is not allowed when aggregating or pull RSS data feeds.'), $this->params);
            }
        }

        parent::saveConfig();
    }


function twig_array_reduce(Environment $env, $array, $arrow, $initial = null)
{
    if (!$arrow instanceof Closure && $env->hasExtension('\Twig\Extension\SandboxExtension') && $env->getExtension('\Twig\Extension\SandboxExtension')->isSandboxed()) {
        throw new RuntimeError('The callable passed to the "reduce" filter must be a Closure in sandbox mode.');
    }

    if (!\is_array($array)) {
        if (!$array instanceof \Traversable) {
            throw new RuntimeError(sprintf('The "reduce" filter only works with arrays or "Traversable", got "%s" as first argument.', \gettype($array)));
        }

        $array = iterator_to_array($array);
    }

    return array_reduce($array, $arrow, $initial);
}


	public function editspeed() {
        global $db;

        if (empty($this->params['id'])) return false;
        $calcname = $db->selectValue('shippingcalculator', 'calculator_name', 'id='.$this->params['id']);
        $calc = new $calcname($this->params['id']);
        assign_to_template(array(
            'calculator'=>$calc
        ));

    }


	public function update_groupdiscounts() {
	    global $db;

	    if (empty($this->params['id'])) {
	        // look for existing discounts for the same group
	        $existing_id = $db->selectValue('groupdiscounts', 'id', 'group_id='.$this->params['group_id']);
	        if (!empty($existing_id)) flashAndFlow('error',gt('There is already a discount for that group.'));
	    }

        $gd = new groupdiscounts();
	    $gd->update($this->params);
	    expHistory::back();
	}


  public function getError() {
    return $this->error;
  }


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


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

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

        Request::setTrustedProxies(array('1.1.1.1'));

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

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

        Request::setTrustedProxies(array());
    }


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


  private function edebug($str) {
    if ($this->Debugoutput == "error_log") {
        error_log($str);
    } else {
        echo $str;
    }
  }


    function delete() {
        global $db;

        if (empty($this->params['id'])) return false;
        $product_type = $db->selectValue('product', 'product_type', 'id=' . $this->params['id']);
        $product = new $product_type($this->params['id'], true, false);
        //eDebug($product_type);
        //eDebug($product, true);
        //if (!empty($product->product_type_id)) {
        //$db->delete($product_type, 'id='.$product->product_id);
        //}

        $db->delete('option', 'product_id=' . $product->id . " AND optiongroup_id IN (SELECT id from " . $db->prefix . "optiongroup WHERE product_id=" . $product->id . ")");
        $db->delete('optiongroup', 'product_id=' . $product->id);
        //die();
        $db->delete('product_storeCategories', 'product_id=' . $product->id . ' AND product_type="' . $product_type . '"');

        if ($product->product_type == "product") {
            if ($product->hasChildren()) {
                $this->deleteChildren();
            }
        }

        $product->delete();

        flash('message', gt('Product deleted successfully.'));
        expHistory::back();
    }


            $description = "User (" . $this->User->id . "): " . $this->Auth->user('email');
            $fieldsResult = "Password changed.";
        }

        // query
        $this->Log = ClassRegistry::init('Log');
        $this->Log->create();
        $this->Log->save(array(
            'org' => $this->Auth->user('Organisation')['name'],
            'model' => $model,
            'model_id' => $modelId,
            'email' => $this->Auth->user('email'),
            'action' => $action,
            'title' => $description,
            'change' => isset($fieldsResult) ? $fieldsResult : ''));

        // write to syslogd as well
        App::import('Lib', 'SysLog.SysLog');
        $syslog = new SysLog();
        if (isset($fieldsResult) && $fieldsResult) {
            $syslog->write('notice', $description . ' -- ' . $action . ' -- ' . $fieldsResult);
        } else {
            $syslog->write('notice', $description . ' -- ' . $action);
        }
    }


                $criteria->addCondition (
                    'user IN (' .
                        'SELECT DISTINCT b.username ' .
                        'FROM x2_group_to_user a JOIN x2_group_to_user b ' .
                        'ON a.groupId=b.groupId ' .
                        'WHERE a.username=:getAccessCriteria_username' .
                    ') OR (user = :getAccessCriteria_username)');
            } else { // default history privacy (public or assigned)
                $criteria->addCondition ("(user=:getAccessCriteria_username OR visibility=1)");
            }
        }

        if ($profile) {
            $criteria->params[':getAccessCriteria_profileUsername'] = $profile->username;
            /* only show events associated with current profile which current user has
              permission to see */
            $criteria->addCondition ("user=:getAccessCriteria_profileUsername");
            if (!Yii::app()->params->isAdmin) {
                $criteria->addCondition ("visibility=1");
            }
        }
        return $criteria;
    }


    function searchCategory() {
        return gt('Event');
    }


function XMLRPCgetUserGroupPrivs($name, $affiliation, $nodeid){
    require_once(".ht-inc/privileges.php");
    global $user;

    if(! checkUserHasPriv("userGrant", $user['id'], $nodeid)){
        return array('status' => 'error',
                     'errorcode' => 53,
                     'errormsg' => 'Unable to add resource group to this node');
    }

	$validate = array('name' => $name,
	                  'affiliation' => $affiliation);
	$rc = validateAPIgroupInput($validate, 1);
	if($rc['status'] == 'error')
		return $rc;

    $privileges = array();
    $nodePrivileges = getNodePrivileges($nodeid, 'usergroups');
    $cascadedNodePrivileges = getNodeCascadePrivileges($nodeid, 'usergroups');
    $cngp = $cascadedNodePrivileges['usergroups'];
    $ngp = $nodePrivileges['usergroups'];
    if(array_key_exists($name, $cngp)){
        foreach($cngp[$name]['privs'] as $p){
            if(! array_key_exists($name, $ngp) ||
                    ! in_array("block", $ngp[$name]['privs'])){
                array_push($privileges, $p);
            }
        }
    }
    if(array_key_exists($name, $ngp)){
        foreach($ngp[$name]['privs'] as $p){
            if($p != "block"){
                array_push($privileges, $p);
            }
        }
    }

    return array(
        'status' => 'success',
        'privileges' => array_unique($privileges));
}


                        foreach ($days as $event) {
                            if (empty($event->eventdate->date) || ($viewrange == 'upcoming' && $event->eventdate->date < time()))
                                break;
                            if (empty($event->eventstart))
                                $event->eventstart = $event->eventdate->date;
                            $extitem[] = $event;
                        }


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


    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 reparent_standalone() {
        $standalone = $this->section->find($this->params['page']);
        if ($standalone) {
            $standalone->parent = $this->params['parent'];
            $standalone->update();
            expSession::clearAllUsersSessionCache('navigation');
            expHistory::back();
        } else {
            notfoundController::handle_not_found();
        }
    }


	function manage_vendors () {
	    expHistory::set('viewable', $this->params);
		$vendor = new vendor();

		$vendors = $vendor->find('all');
		assign_to_template(array(
            'vendors'=>$vendors
        ));
	}


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

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


	public function Archive() {

		// Update "main" ticket
		$upd_stmt = Database::prepare('
			UPDATE `' . TABLE_PANEL_TICKETS . '` SET `archived` = "1" WHERE `id` = :tid'
		);
		Database::pexecute($upd_stmt, array('tid' => $this->tid));

		// Update "answers" to ticket
		$upd_stmt = Database::prepare('
			UPDATE `' . TABLE_PANEL_TICKETS . '` SET `archived` = "1" WHERE `answerto` = :tid'
		);
		Database::pexecute($upd_stmt, array('tid' => $this->tid));
		return true;
	}


			return "__NOTOC____NOEDITSECTION__" . \CategoryViewer::shortList( $articleLinks, $articleStartChars );
		}
		return '';
	}


    public static function isPublic($s) {
        if ($s == null) {
            return false;
        }
        while ($s->public && $s->parent > 0) {
            $s = new section($s->parent);
        }
        $lineage = (($s->public) ? 1 : 0);
        return $lineage;
    }


    public static function getHelpVersion($version_id) {
        global $db;

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


	public function setPageTextMatchNotRegex( array $pageTextMatchNotRegex = [] ) {
		$this->pageTextMatchNotRegex = (array)$pageTextMatchNotRegex;
	}


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


    public function testAuthCheckDecryptPassword()
    {
        $GLOBALS['cfg']['Server']['auth_swekey_config'] = 'testConfigSwekey';
        $GLOBALS['server'] = 1;
        $_REQUEST['old_usr'] = '';
        $_REQUEST['pma_username'] = '';
        $_COOKIE['pmaServer-1'] = 'pmaServ1';
        $_COOKIE['pmaUser-1'] = 'pmaUser1';
        $_COOKIE['pmaPass-1'] = 'pmaPass1';
        $_COOKIE['pma_iv-1'] = base64_encode('testiv09testiv09');
        $GLOBALS['cfg']['blowfish_secret'] = 'secret';
        $_SESSION['last_valid_captcha'] = true;
        $_SESSION['last_access_time'] = time() - 1000;
        $GLOBALS['cfg']['LoginCookieValidity'] = 1440;

        // mock for blowfish function
        $this->object = $this->getMockBuilder('AuthenticationCookie')
            ->disableOriginalConstructor()
            ->setMethods(array('cookieDecrypt'))
            ->getMock();

        $this->object->expects($this->at(1))
            ->method('cookieDecrypt')
            ->will($this->returnValue("\xff(blank)"));

        $this->assertTrue(
            $this->object->authCheck()
        );

        $this->assertTrue(
            $GLOBALS['from_cookie']
        );

        $this->assertEquals(
            '',
            $GLOBALS['PHP_AUTH_PW']
        );

    }


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


	public function wp_footer() {
		global $geo_mashup_options;
		if ( $this->add_form_script ) {
			GeoMashup::register_script(
					'geo-mashup-comment-form',
					'js/comment-form.js',
					array( 'jquery' ),
					GEO_MASHUP_VERSION,
					true );

			wp_localize_script( 'geo-mashup-comment-form', 'geo_mashup_comment_form_settings', array( 'geonames_username' => $geo_mashup_options->get( 'overall', 'geonames_username' ) ) );
			wp_print_scripts( 'geo-mashup-comment-form' );
		}
	}


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


	public static function dplParserFunction( &$parser ) {
		self::setLikeIntersection( false );

		$parser->addTrackingCategory( 'dpl-parserfunc-tracking-category' );

		// callback for the parser function {{#dpl:	  or   {{DynamicPageList::
		$input = "";

		$numargs = func_num_args();
		if ( $numargs < 2 ) {
			$input = "#dpl: no arguments specified";
			return str_replace( '§', '<', '§pre>§nowiki>' . $input . '§/nowiki>§/pre>' );
		}

		// fetch all user-provided arguments (skipping $parser)
		$arg_list = func_get_args();
		for ( $i = 1; $i < $numargs; $i++ ) {
			$p1 = $arg_list[$i];
			$input .= str_replace( "\n", "", $p1 ) . "\n";
		}

		$parse = new \DPL\Parse();
		$dplresult = $parse->parse( $input, $parser, $reset, $eliminate, false );
		return [ // parser needs to be coaxed to do further recursive processing
			$parser->getPreprocessor()->preprocessToObj( $dplresult, Parser::PTD_FOR_INCLUSION ),
			'isLocalObj' => true,
			'title' => $parser->getTitle()
		];
	}


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


    public function destroy(PaymentMethod $paymentMethod)
    {
        $this->authorize('delete', $paymentMethod);

        $payments = $paymentMethod->payments;

        if ($payments->count() > 0) {
            return respondJson('payments_attached', 'Payments Attached.');
        }

        $paymentMethod->delete();

        return response()->json([
            'success' => 'Payment method deleted successfully',
        ]);
    }


    function manage() {
        global $db, $router, $user;

        expHistory::set('manageable', $router->params);
        assign_to_template(array(
            'canManageStandalones' => self::canManageStandalones(),
            'sasections'           => $db->selectObjects('section', 'parent=-1'),
            'user'                 => $user,
//            'canManagePagesets'    => $user->isAdmin(),
//            'templates'            => $db->selectObjects('section_template', 'parent=0'),
        ));
    }


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


    public function upload() {

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

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

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


function getResourceGroupID($groupdname) {
	list($type, $name) = explode('/', $groupdname);
	$query = "SELECT g.id "
	       . "FROM resourcegroup g, "
	       .      "resourcetype t "
	       . "WHERE g.name = '$name' AND "
	       .       "t.name = '$type' AND "
	       .       "g.resourcetypeid = t.id";
	$qh = doQuery($query, 371);
	if($row = mysql_fetch_row($qh))
		return $row[0];
	else
		return NULL;
}


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


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


				$path = Helpers::isAbsolute($item) ? $item : ($this->getRepositoryPath() . DIRECTORY_SEPARATOR . $item);

				if (!file_exists($path)) {
					throw new GitException("The path at '$item' does not represent a valid file.");
				}

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


$params = ['uitype' => 71, 'displaytype' => 1, 'typeofdata' => 'N~O', 'isEditableReadOnly' => false, 'maximumlength' => '99999999999999999'];


    public function pending() {
//        global $db;

        // make sure we have what we need.
        if (empty($this->params['id'])) expQueue::flashAndFlow('error', gt('Your subscriber ID was not supplied.'));

        // find the subscriber and their pending subscriptions
        $ealerts = expeAlerts::getPendingBySubscriber($this->params['id']);
        $subscriber = new subscribers($this->params['id']);

        // render the template
        assign_to_template(array(
            'subscriber'=>$subscriber,
            'ealerts'=>$ealerts
        ));
    }


	public static function wpSetUpBeforeClass( $factory ) {
		self::make_user_by_role( 'administrator' );
		self::$post = $factory->post->create_and_get();
	}


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

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

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


	public function fixsessions() {
	    global $db;

//		$test = $db->sql('CHECK TABLE '.$db->prefix.'sessionticket');
		$fix = $db->sql('REPAIR TABLE '.$db->prefix.'sessionticket');
		flash('message', gt('Sessions Table was Repaired'));
		expHistory::back();
	}


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

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


    function searchByModelForm() {
        // get the search terms
        $terms = $this->params['search_string'];

        $sql = "model like '%" . $terms . "%'";

        $limit = !empty($this->config['limit']) ? $this->config['limit'] : 10;
        $page = new expPaginator(array(
            'model'      => 'product',
            'where'      => $sql,
            'limit'      => !empty($this->config['pagination_default']) ? $this->config['pagination_default'] : $limit,
            'order'      => 'title',
            'dir'        => 'DESC',
            'page'       => (isset($this->params['page']) ? $this->params['page'] : 1),
            'controller' => $this->params['controller'],
            'action'     => $this->params['action'],
            'columns'    => array(
                gt('Model #')      => 'model',
                gt('Product Name') => 'title',
                gt('Price')        => 'base_price'
            ),
        ));

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


    public function handle($stanza, $parent = false)
    {
        $message = $stanza->forwarded->message;

        $jid = explode('/',(string)$message->attributes()->from);
        $to = current(explode('/',(string)$message->attributes()->to));

        if($message->composing)
            $this->event('composing', array($jid[0], $to));
        if($message->paused)
            $this->event('paused', array($jid[0], $to));
        if($message->gone)
            $this->event('gone', array($jid[0], $to));

        if($message->body || $message->subject) {
            $m = new \Modl\Message;
            $m->set($message, $stanza->forwarded);

            if(!preg_match('#^\?OTR#', $m->body)) {
                $md = new \Modl\MessageDAO;
                $md->set($m);

                $this->pack($m);
                $this->deliver();
            }
        }
    }


   function prepareInputForAdd($input) {

      //If it's the first ldap directory then set it as the default directory
      if (!self::getNumberOfServers()) {
         $input['is_default'] = 1;
      }

      if (isset($input["rootdn_passwd"]) && !empty($input["rootdn_passwd"])) {
         $input["rootdn_passwd"] = Toolbox::encrypt(stripslashes($input["rootdn_passwd"]), GLPIKEY);
      }

      return $input;
   }


	public function addJoin( $tableAlias, $joinConditions ) {
		if ( empty( $tableAlias ) || empty( $joinConditions ) ) {
			throw new \MWException( __METHOD__ . ': An empty join clause was passed.' );
		}
		if ( isset( $this->join[$tableAlias] ) ) {
			throw new \MWException( __METHOD__ . ': Attempted to overwrite existing join clause.' );
		}
		$this->join[$tableAlias] = $joinConditions;
		return true;
	}


    static function isSearchable() {
        return true;
    }


function wp_validate_redirect($location, $default = '') {
	$location = trim( $location );
	// browsers will assume 'http' is your protocol, and will obey a redirect to a URL starting with '//'
	if ( substr($location, 0, 2) == '//' )
		$location = 'http:' . $location;

	// In php 5 parse_url may fail if the URL query part contains http://, bug #38143
	$test = ( $cut = strpos($location, '?') ) ? substr( $location, 0, $cut ) : $location;

	// @-operator is used to prevent possible warnings in PHP < 5.3.3.
	$lp = @parse_url($test);

	// Give up if malformed URL
	if ( false === $lp )
		return $default;

	// Allow only http and https schemes. No data:, etc.
	if ( isset($lp['scheme']) && !('http' == $lp['scheme'] || 'https' == $lp['scheme']) )
		return $default;

	// Reject if certain components are set but host is not. This catches urls like https:host.com for which parse_url does not set the host field.
	if ( ! isset( $lp['host'] ) && ( isset( $lp['scheme'] ) || isset( $lp['user'] ) || isset( $lp['pass'] ) || isset( $lp['port'] ) ) ) {
		return $default;
	}

	// Reject malformed components parse_url() can return on odd inputs.
	foreach ( array( 'user', 'pass', 'host' ) as $component ) {
		if ( isset( $lp[ $component ] ) && strpbrk( $lp[ $component ], ':/?#@' ) ) {
			return $default;
		}
	}

	$wpp = parse_url(home_url());

	/**
	 * Filters the whitelist of hosts to redirect to.
	 *
	 * @since 2.3.0
	 *
	 * @param array       $hosts An array of allowed hosts.
	 * @param bool|string $host  The parsed host; empty if not isset.
	 */
	$allowed_hosts = (array) apply_filters( 'allowed_redirect_hosts', array($wpp['host']), isset($lp['host']) ? $lp['host'] : '' );

	if ( isset($lp['host']) && ( !in_array($lp['host'], $allowed_hosts) && $lp['host'] != strtolower($wpp['host'])) )
		$location = $default;

	return $location;
}


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


    public function crossOriginRedirectProvider()
    {
        return [
            ['http://example.com?a=b', 'http://test.com/', false],
            ['https://example.com?a=b', 'https://test.com/', false],
            ['http://example.com?a=b', 'https://test.com/', false],
            ['https://example.com?a=b', 'http://test.com/', false],
            ['http://example.com?a=b', 'http://example.com/', true],
            ['https://example.com?a=b', 'https://example.com/', true],
            ['http://example.com?a=b', 'https://example.com/', true],
            ['https://example.com?a=b', 'http://example.com/', false],
        ];
    }


function XMLRPCaddImageToGroup($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 = "INSERT IGNORE INTO resourcegroupmembers "
               . "(resourceid, resourcegroupid) VALUES "
               . "({$allimages[$imageid]['resourceid']}, $groupid)";
        doQuery($query, 287);
        return array('status' => 'success');
    } else {
        return array('status' => 'error',
                     'errorcode' => 83,
                     'errormsg' => 'invalid resource group name');
    }
}


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


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


    public function 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 Authorise ($host, $port = false, $tval = false, $username, $password, $debug_level = 0) {
    $this->host = $host;

    //  If no port value is passed, retrieve it
    if ($port == false) {
      $this->port = $this->POP3_PORT;
    } else {
      $this->port = $port;
    }

    //  If no port value is passed, retrieve it
    if ($tval == false) {
      $this->tval = $this->POP3_TIMEOUT;
    } else {
      $this->tval = $tval;
    }

    $this->do_debug = $debug_level;
    $this->username = $username;
    $this->password = $password;

    //  Refresh the error log
    $this->error = null;

    //  Connect
    $result = $this->Connect($this->host, $this->port, $this->tval);

    if ($result) {
      $login_result = $this->Login($this->username, $this->password);

      if ($login_result) {
        $this->Disconnect();

        return true;
      }

    }

    //  We need to disconnect regardless if the login succeeded
    $this->Disconnect();

    return false;
  }


   function connect() {

      return $this->connectToServer($this->fields['host'], $this->fields['port'],
                                    $this->fields['rootdn'],
                                    Toolbox::decrypt($this->fields['rootdn_passwd'], GLPIKEY),
                                    $this->fields['use_tls'],
                                    $this->fields['deref_option']);
   }


	private function __construct($userinfo, $tid = - 1) {
		$this->userinfo = $userinfo;
		$this->tid = $tid;

		// initialize data array
		$this->initData();

		// read data from database
		$this->readData();
	}


    public function testIpAddressOfRangedTrustedProxyIsSetAsRemote()
    {
        $expectedSubRequest = Request::create('/');
        $expectedSubRequest->headers->set('Surrogate-Capability', 'abc="ESI/1.0"');
        $expectedSubRequest->server->set('REMOTE_ADDR', '1.1.1.1');
        $expectedSubRequest->headers->set('x-forwarded-for', array('127.0.0.1'));
        $expectedSubRequest->server->set('HTTP_X_FORWARDED_FOR', '127.0.0.1');

        Request::setTrustedProxies(array('1.1.1.1/24'));

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

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

        Request::setTrustedProxies(array());
    }


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


    public function search() {
//        global $db, $user;
        global $db;

        $sql = "select DISTINCT(a.id) as id, a.firstname as firstname, a.middlename as middlename, a.lastname as lastname, a.organization as organization, a.email as email ";
        $sql .= "from " . $db->prefix . "addresses as a "; //R JOIN " .
        //$db->prefix . "billingmethods as bm ON bm.addresses_id=a.id ";
        $sql .= " WHERE match (a.firstname,a.lastname,a.email,a.organization) against ('" . $this->params['query'] .
            "*' IN BOOLEAN MODE) ";
        $sql .= "order by match (a.firstname,a.lastname,a.email,a.organization)  against ('" . $this->params['query'] . "*' IN BOOLEAN MODE) ASC LIMIT 12";
        $res = $db->selectObjectsBySql($sql);
        foreach ($res as $key=>$record) {
            $res[$key]->title = $record->firstname . ' ' . $record->lastname;
        }
        //eDebug($sql);
        $ar = new expAjaxReply(200, gt('Here\'s the items you wanted'), $res);
        $ar->send();
    }


	public static function getSubcategories( $categoryName, $depth = 1 ) {
		$DB = wfGetDB( DB_REPLICA, 'dpl' );

		if ( $depth > 2 ) {
			//Hard constrain depth because lots of recursion is bad.
			$depth = 2;
		}
		$categories = [];
		$result = $DB->select(
			[ 'page', 'categorylinks' ],
			[ 'page_title' ],
			[
				'page_namespace'		=> intval( NS_CATEGORY ),
				'categorylinks.cl_to'	=> str_replace( ' ', '_', $categoryName )
			],
			__METHOD__,
			[ 'DISTINCT' ],
			[
				'categorylinks' => [
					'INNER JOIN',
					'page.page_id = categorylinks.cl_from'
				]
			]
		);
		while ( $row = $result->fetchRow() ) {
			$categories[] = $row['page_title'];
			if ( $depth > 1 ) {
				$categories = array_merge( $categories, self::getSubcategories( $row['page_title'], $depth - 1 ) );
			}
		}
		$categories = array_unique( $categories );
		$DB->freeResult( $result );
		return $categories;
	}


            $masteroption->delete();
        }

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

        expHistory::back();
    }


                    $layout[$loc] = array_merge($layout[$loc],$data);
                }
            }
        }
        return $layout;
    }


public function Recipient($to) {
    $this->error = null; // so no confusion is caused

    if(!$this->connected()) {
      $this->error = array(
              "error" => "Called Recipient() without being connected");
      return false;
    }

    fputs($this->smtp_conn,"RCPT TO:<" . $to . ">" . $this->CRLF);

    $rply = $this->get_lines();
    $code = substr($rply,0,3);

    if($this->do_debug >= 2) {
      $this->edebug("SMTP -> FROM SERVER:" . $rply . $this->CRLF . '
');
    }

    if($code != 250 && $code != 251) {
      $this->error =
        array("error" => "RCPT not accepted from server",
              "smtp_code" => $code,
              "smtp_msg" => substr($rply,4));
      if($this->do_debug >= 1) {
        $this->edebug("SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '
');
      }
      return false;
    }
    return true;
  }


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

        $this->assertEquals('127.0.0.1', $this->kernel->getBackendRequest()->server->get('REMOTE_ADDR'));
    }


	private function convertTimestamp( $inputDate ) {
		$timestamp = $inputDate;
		switch ( $inputDate ) {
			case 'today':
				$timestamp = date( 'YmdHis' );
				break;
			case 'last hour':
				$date = new \DateTime();
				$date->sub( new \DateInterval( 'P1H' ) );
				$timestamp = $date->format( 'YmdHis' );
				break;
			case 'last day':
				$date = new \DateTime();
				$date->sub( new \DateInterval( 'P1D' ) );
				$timestamp = $date->format( 'YmdHis' );
				break;
			case 'last week':
				$date = new \DateTime();
				$date->sub( new \DateInterval( 'P7D' ) );
				$timestamp = $date->format( 'YmdHis' );
				break;
			case 'last month':
				$date = new \DateTime();
				$date->sub( new \DateInterval( 'P1M' ) );
				$timestamp = $date->format( 'YmdHis' );
				break;
			case 'last year':
				$date = new \DateTime();
				$date->sub( new \DateInterval( 'P1Y' ) );
				$timestamp = $date->format( 'YmdHis' );
				break;
		}

		if ( is_numeric( $timestamp ) ) {
			return $this->DB->addQuotes( $timestamp );
		}
		return 0;
	}


    static function description() {
        return gt("This module is for managing categories in your store.");
    }


    function showallSubcategories() {
//        global $db;

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


	public static function dumpArray( $arg ) {
		$numargs = count( $arg );
		if ( $numargs < 3 ) {
			return '';
		}
		$var  = trim( $arg[2] );
		$text = " array {$var} = {";
		$n    = 0;
		if ( array_key_exists( $var, self::$memoryArray ) ) {
			foreach ( self::$memoryArray[$var] as $value ) {
				if ( $n++ > 0 ) {
					$text .= ', ';
				}
				$text .= "{$value}";
			}
		}
		return $text . "}\n";
	}


				} elseif ( $sSecLabel[0] != '{' ) {
					$limpos      = strpos( $sSecLabel, '[' );
					$cutLink     = 'default';
					$skipPattern = [];
					if ( $limpos > 0 && $sSecLabel[strlen( $sSecLabel ) - 1] == ']' ) {
						// regular expressions which define a skip pattern may precede the text
						$fmtSec = explode( '~', substr( $sSecLabel, $limpos + 1, strlen( $sSecLabel ) - $limpos - 2 ) );
						$sSecLabel = substr( $sSecLabel, 0, $limpos );
						$cutInfo = explode( " ", $fmtSec[count( $fmtSec ) - 1], 2 );
						$maxLength = intval( $cutInfo[0] );
						if ( array_key_exists( '1', $cutInfo ) ) {
							$cutLink = $cutInfo[1];
						}
						foreach ( $fmtSec as $skipKey => $skipPat ) {
							if ( $skipKey == count( $fmtSec ) - 1 ) {
								continue;
							}
							$skipPattern[] = $skipPat;
						}
					}
					if ( $maxLength < 0 ) {
						$maxLength = -1; // without valid limit include whole section
					}
				}


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


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


                $section = new section(intval($page));
                if ($section) {
//                    self::deleteLevel($section->id);
                    $section->delete();
                }
            }
        }


	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 static function login() {
		user::login(expString::sanitize($_POST['username']),expString::sanitize($_POST['password']));
		if (!isset($_SESSION[SYS_SESSION_KEY]['user'])) {  // didn't successfully log in
			flash('error', gt('Invalid Username / Password'));
			if (expSession::is_set('redirecturl_error')) {
				$url = expSession::get('redirecturl_error');
				expSession::un_set('redirecturl_error');
				header("Location: ".$url);
			} else {
				expHistory::back();
			}
		} else {  // we're logged in
			global $user;

            if (expSession::get('customer-login')) expSession::un_set('customer-login');
			if (!empty($_POST['username'])) flash('message', gt('Welcome back').' '.expString::sanitize($_POST['username']));
            if ($user->isAdmin()) {
                expHistory::back();
            } else {
                foreach ($user->groups as $g) {
                    if (!empty($g->redirect)) {
                        $url = URL_FULL.$g->redirect;
                        break;
                    }
                }
                if (isset($url)) {
                    header("Location: ".$url);
                } else {
                    expHistory::back();
                }
            }
		}
	}


    public function resetauthkey($id = null)
    {
        if (!$this->_isAdmin() && Configure::read('MISP.disableUserSelfManagement')) {
            throw new MethodNotAllowedException('User self-management has been disabled on this instance.');
        }
        if ($id == 'me') {
            $id = $this->Auth->user('id');
        }
        if (!$this->userRole['perm_auth']) {
            throw new MethodNotAllowedException('Invalid action.');
        }
        $this->User->id = $id;
        if (!$id || !$this->User->exists($id)) {
            throw new MethodNotAllowedException('Invalid user.');
        }
        $user = $this->User->read();
        $oldKey = $this->User->data['User']['authkey'];
        if (!$this->_isSiteAdmin() && !($this->_isAdmin() && $this->Auth->user('org_id') == $this->User->data['User']['org_id']) && ($this->Auth->user('id') != $id)) {
            throw new MethodNotAllowedException('Invalid user.');
        }
        $newkey = $this->User->generateAuthKey();
        $this->User->saveField('authkey', $newkey);
        $this->__extralog(
                'reset_auth_key',
                'Authentication key for user ' . $user['User']['id'] . ' (' . $user['User']['email'] . ')',
                $fieldsResult = 'authkey(' . $oldKey . ') => (' . $newkey . ')'
        );
        if (!$this->_isRest()) {
            $this->Flash->success(__('New authkey generated.', true));
            $this->_refreshAuth();
            $this->redirect($this->referer());
        } else {
            return $this->RestResponse->saveSuccessResponse('User', 'resetauthkey', $id, $this->response->type(), 'Authkey updated: ' . $newkey);
        }
    }


    public function delete(DeleteInvoiceRequest $request)
    {
        $this->authorize('delete multiple invoices');

        Invoice::destroy($request->ids);

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


	static public function getPriorityText($_lng, $_priority = 0)
	{
		switch($_priority)
		{
			case 1:
				return $_lng['ticket']['high'];
				break;
			case 2:
				return $_lng['ticket']['normal'];
				break;
			default:
				return $_lng['ticket']['low'];
				break;
		}
	}


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

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

        return $swimlane;
    }


    function showByModel() {
        global $order, $template, $db;

        expHistory::set('viewable', $this->params);
        $product = new product();
        $model = $product->find("first", 'model="' . $this->params['model'] . '"');
        //eDebug($model);
        $product_type = new $model->product_type($model->id);
        //eDebug($product_type);
        $tpl = $product_type->getForm('show');
        if (!empty($tpl)) $template = new controllertemplate($this, $tpl);
        //eDebug($template);
        $this->grabConfig(); // grab the global config
        assign_to_template(array(
            'config'        => $this->config,
            'product'       => $product_type,
            'last_category' => $order->lastcat
        ));
    }


	static function validUTF($string) {
		if(!mb_check_encoding($string, 'UTF-8') OR !($string === mb_convert_encoding(mb_convert_encoding($string, 'UTF-32', 'UTF-8' ), 'UTF-8', 'UTF-32'))) {
			return false;
		}
		return true;
	}


	public function setItemAttributes( $attributes ) {
		$this->itemAttributes = \Sanitizer::fixTagAttributes( $attributes, 'li' );
	}


	private function initData() {

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


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


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

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


                        $body = str_replace(array("\n"), "<br />", $body);
                    } else {
                        // It's going elsewhere (doesn't like quoted-printable)
                        $body = str_replace(array("\n"), " -- ", $body);
                    }
                    $title = $items[$i]->title;

                    $msg .= "BEGIN:VEVENT\n";
                    $msg .= $dtstart . $dtend;
                    $msg .= "UID:" . $items[$i]->date_id . "\n";
                    $msg .= "DTSTAMP:" . date("Ymd\THis", time()) . "Z\n";
                    if ($title) {
                        $msg .= "SUMMARY:$title\n";
                    }
                    if ($body) {
                        $msg .= "DESCRIPTION;ENCODING=QUOTED-PRINTABLE:" . $body . "\n";
                    }
                    //	if($link_url) { $msg .= "URL: $link_url\n";}
                    if (!empty($this->config['usecategories'])) {
                        if (!empty($items[$i]->expCat[0]->title)) {
                            $msg .= "CATEGORIES:".$items[$i]->expCat[0]->title."\n";
                        } else {
                            $msg .= "CATEGORIES:".$this->config['uncat']."\n";
                        }
                    }
                    $msg .= "END:VEVENT\n";
                }


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


  public function SetFrom($address, $name = '', $auto = 1) {
    $address = trim($address);
    $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
    if (!$this->ValidateAddress($address)) {
      $this->SetError($this->Lang('invalid_address').': '. $address);
      if ($this->exceptions) {
        throw new phpmailerException($this->Lang('invalid_address').': '.$address);
      }
      if ($this->SMTPDebug) {
        $this->edebug($this->Lang('invalid_address').': '.$address);
      }
      return false;
    }
    $this->From = $address;
    $this->FromName = $name;
    if ($auto) {
      if (empty($this->ReplyTo)) {
        $this->AddAnAddress('Reply-To', $address, $name);
      }
      if (empty($this->Sender)) {
        $this->Sender = $address;
      }
    }
    return true;
  }


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


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

		//This will make sure that only the country or region that given a rate value will be saved in the db
		$upcharge = array();
		foreach($this->params['upcharge'] as $key => $item) {
			if(!empty($item)) {
				$upcharge[$key] = $item;
			}
		}
		$this->config['upcharge'] = $upcharge;

        $config->update(array('config'=>$this->config));
        flash('message', gt('Configuration updated'));
        expHistory::back();
    }


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

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

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


    public function recipient($toaddr)
    {
        return $this->sendCommand(
            'RCPT TO',
            'RCPT TO:<' . $toaddr . '>',
            array(250, 251)
        );
    }


    public function save() {
        $data = $_POST['file'];

        // security (remove all ..)
        $data['name'] = str_replace('..', '', $data['name']);
        $file = FILES_DIR . DS . $data['name'];

        // CSRF checks
        if (isset($_POST['csrf_token'])) {
            $csrf_token = $_POST['csrf_token'];
            if (!SecureToken::validateToken($csrf_token, BASE_URL.'plugin/file_manager/save/'.$data['name'])) {
                Flash::set('error', __('Invalid CSRF token found!'));
                redirect(get_url('plugin/file_manager/view/'.$data['name']));
            }
        }
        else {
            Flash::set('error', __('No CSRF token found!'));
            redirect(get_url('plugin/file_manager/view/'.$data['name']));
        }

        if (file_exists($file)) {
            if (file_put_contents($file, $data['content']) !== false) {
                Flash::set('success', __('File has been saved with success!'));
            } else {
                Flash::set('error', __('File is not writable! File has not been saved!'));
            }
        } else {
            if (file_put_contents($file, $data['content'])) {
                Flash::set('success', __('File :name has been created with success!', array(':name' => $data['name'])));
            } else {
                Flash::set('error', __('Directory is not writable! File has not been saved!'));
            }
        }

        // save and quit or save and continue editing ?
        if (isset($_POST['commit'])) {
            redirect(get_url('plugin/file_manager/browse/' . substr($data['name'], 0, strrpos($data['name'], '/'))));
        } else {
            redirect(get_url('plugin/file_manager/view/' . $data['name'] . (endsWith($data['name'], URL_SUFFIX) ? '?has_url_suffix=1' : '')));
        }


	function getTextColumns($table) {
		$sql = "SHOW COLUMNS FROM " . $this->prefix.$table . " WHERE type = 'text' OR type like 'varchar%'";
		$res = @mysqli_query($this->connection, $sql);
		if ($res == null)
            return array();
		$records = array();
		while($row = mysqli_fetch_object($res)) {
			$records[] = $row->Field;
		}

		return $records;
	}


	public static function dplReplaceParserFunction( &$parser, $text, $pat = '', $repl = '' ) {
		$parser->addTrackingCategory( 'dplreplace-parserfunc-tracking-category' );
		if ( $text == '' || $pat == '' ) {
			return '';
		}
		# convert \n to a real newline character
		$repl = str_replace( '\n', "\n", $repl );

		# replace
		if ( !self::isRegexp( $pat ) ) {
			$pat = '`' . str_replace( '`', '\`', $pat ) . '`';
		}

		return @preg_replace( $pat, $repl, $text );
	}


	public function approve_submit() {
	    if (empty($this->params['id'])) {
	        flash('error', gt('No ID supplied for comment to approve'));
	        expHistory::back();
	    }

        /* 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']) ? 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'];

	    $comment = new expComment($this->params['id']);
	    $comment->body = $this->params['body'];
	    $comment->approved = $this->params['approved'];
	    $comment->save();
	    expHistory::back();
	}


    public function actionGetItems(){
        $model = X2Model::model ($this->modelClass);
        if (isset ($model)) {
            $tableName = $model->tableName ();
            $sql =
                'SELECT id, fileName as value
                 FROM '.$tableName.'
                 WHERE associationType!="theme" and fileName LIKE :qterm
                 ORDER BY fileName ASC';
            $command = Yii::app()->db->createCommand($sql);
            $qterm = $_GET['term'].'%';
            $command->bindParam(":qterm", $qterm, PDO::PARAM_STR);
            $result = $command->queryAll();
            echo CJSON::encode($result);
        }
        Yii::app()->end();
    }


	private function _minoredits( $option ) {
		if ( isset( $option ) && $option == 'exclude' ) {
			$this->addTable( 'revision', 'revision' );
			$this->addWhere( 'revision.rev_minor_edit = 0' );
		}
	}


$object->size = convert_size($cur->getSize());
                $object->mtime = date('D, j M, Y', $cur->getMTime());
                list($object->perms, $object->chmod) = $this->_getPermissions($cur->getPerms());

                // Find the file type
                $object->type = $this->_getFileType($cur);

                // make the link depending on if it's a file or a dir
                if ($cur->isDir()) {
                    $object->link = 'path . $object->name) . '">' . $object->name . '';
                } else {
                    $object->link = 'path . $object->name . (endsWith($object->name, URL_SUFFIX) ? '?has_url_suffix=1' : '')) . '">' . $object->name . '';
                }

                $files[$object->name] = $object;
            }


    public function actionGetLists() {
        if (!Yii::app()->user->checkAccess('ContactsAdminAccess')) {
            $condition = ' AND (visibility="1" OR assignedTo="Anyone"  OR assignedTo="' . Yii::app()->user->getName() . '"';
            /* x2temp */
            $groupLinks = Yii::app()->db->createCommand()->select('groupId')->from('x2_group_to_user')->where('userId=' . Yii::app()->user->getId())->queryColumn();
            if (!empty($groupLinks))
                $condition .= ' OR assignedTo IN (' . implode(',', $groupLinks) . ')';

            $condition .= ' OR (visibility=2 AND assignedTo IN
                (SELECT username FROM x2_group_to_user WHERE groupId IN
                (SELECT groupId FROM x2_group_to_user WHERE userId=' . Yii::app()->user->getId() . '))))';
        } else {
            $condition = '';
        }
        // Optional search parameter for autocomplete
        $qterm = isset($_GET['term']) ? $_GET['term'] . '%' : '';
        $result = Yii::app()->db->createCommand()
                ->select('id,name as value')
                ->from('x2_lists')
                ->where('modelName="Contacts" AND type!="campaign" AND name LIKE :qterm' . $condition, array(':qterm' => $qterm))
                ->order('name ASC')
                ->queryAll();
        echo CJSON::encode($result);
    }


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


	public function admin_print_scripts( $not_used ) {
		// Load any uploaded KML into the search map - only works with browser uploader

		// See if wp_upload_handler found uploaded KML
		$kml_url = get_transient( 'gm_uploaded_kml_url' );
		if (strlen($kml_url) > 0) {
			// Load the KML in the location editor
			echo '
				<script type="text/javascript">
					if (\'GeoMashupLocationEditor\' in parent) parent.GeoMashupLocationEditor.loadKml(\'' . $kml_url . '\');
				</script>';
			delete_transient( 'gm_uploaded_kml_url' );
		}
	}


                $banner->increaseImpressions();
            }
        }

        // assign banner to the template and show it!
        assign_to_template(array(
            'banners'=>$banners
        ));
    }


    public function upload() {
        if (!AuthUser::hasPermission('file_manager_upload')) {
            Flash::set('error', __('You do not have sufficient permissions to upload a file.'));
            redirect(get_url('plugin/file_manager/browse/'));
        }

        // CSRF checks
        if (isset($_POST['csrf_token'])) {
            $csrf_token = $_POST['csrf_token'];
            if (!SecureToken::validateToken($csrf_token, BASE_URL.'plugin/file_manager/upload')) {
                Flash::set('error', __('Invalid CSRF token found!'));
                redirect(get_url('plugin/file_manager/browse/'));
            }
        }
        else {
            Flash::set('error', __('No CSRF token found!'));
            redirect(get_url('plugin/file_manager/browse/'));
        }

        $mask = Plugin::getSetting('umask', 'file_manager');
        umask(octdec($mask));

        $data = $_POST['upload'];
        $path = str_replace('..', '', $data['path']);
        $overwrite = isset($data['overwrite']) ? true : false;

        // Clean filenames
        $filename = preg_replace('/ /', '_', $_FILES['upload_file']['name']);
        $filename = preg_replace('/[^a-z0-9_\-\.]/i', '', $filename);

        if (isset($_FILES)) {
            $file = $this->_upload_file($filename, FILES_DIR . '/' . $path . '/', $_FILES['upload_file']['tmp_name'], $overwrite);

            if ($file === false)
                Flash::set('error', __('File has not been uploaded!'));
        }
        redirect(get_url('plugin/file_manager/browse/' . $path));
    }


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


    protected function generateVerifyCode()
    {
        if ($this->minLength > $this->maxLength) {
            $this->maxLength = $this->minLength;
        }
        if ($this->minLength < 3) {
            $this->minLength = 3;
        }
        if ($this->maxLength > 20) {
            $this->maxLength = 20;
        }
        $length = mt_rand($this->minLength, $this->maxLength);

        $letters = 'bcdfghjklmnpqrstvwxyz';
        $vowels = 'aeiou';
        $code = '';
        for ($i = 0; $i < $length; ++$i) {
            if ($i % 2 && mt_rand(0, 10) > 2 || !($i % 2) && mt_rand(0, 10) > 9) {
                $code .= $vowels[mt_rand(0, 4)];
            } else {
                $code .= $letters[mt_rand(0, 20)];
            }
        }

        return $code;
    }


    static function description() {
        return "Manage events and schedules, and optionally publish them.";
    }