public function getRequestTarget()
    {
        if ($this->requestTarget === null)
        {
            // Workaround for some servers (IIS) which do not provide
            // $_SERVER['REQUEST_URI']. Taken from
            // http://php.net/manual/en/reserved.variables.server.php#108186
            if(!isset($_SERVER['REQUEST_URI'])) {
                $_SERVER['REQUEST_URI'] = $_SERVER['SCRIPT_NAME'];
                if(isset($_SERVER['QUERY_STRING'])) {
                    $_SERVER['REQUEST_URI'] .= '?' . $_SERVER['QUERY_STRING'];
                }
            }

            if (strpos($_SERVER['REQUEST_URI'], '?') === false)
                $this->requestTarget = $_SERVER['REQUEST_URI'];
            else
            {
                $parts = explode('?', $_SERVER['REQUEST_URI']);
                $this->requestTarget = $parts[0];
            }

            $seoPathPosition = strrpos($this->requestTarget , "/s/");
            if ($seoPathPosition > -1) {
                 $this->requestTarget = substr($this->requestTarget , 0, $seoPathPosition);
            }

            // Use rawurldecode() so that +'s are not converted to spaces.
            $this->requestTarget = rawurldecode($this->requestTarget);
            if ($this->encodingConverter != null)
            {
                $this->requestTarget = $this->encodingConverter ->decodeClientUrlData($this->requestTarget);
            }
        }
        return $this->requestTarget;
    }

Get target of the current request.

@return string request target


public function activateOptions() {
		if (!isset($this->pattern)) {
			throw new LoggerException("Mandatory parameter 'conversionPattern' is not set.");
		}

		$parser = new LoggerPatternParser($this->pattern, $this->converterMap);
		$this->head = $parser->parse();
	}

Processes the conversion pattern and creates a corresponding chain of
pattern converters which will be used to format logging events.

Processes the conversion pattern and creates a corresponding chain of pattern converters which will be used to format logging events .


public function format(LoggerLoggingEvent $event) {
		$sbuf = '';
		$converter = $this->head;
		while ($converter !== null) {
			$converter->format($sbuf, $event);
			$converter = $converter->next;
		}
		return $sbuf;
	}

public function format ( LoggerLoggingEvent $ event ) { $ sbuf = '' ; $ converter = $ this -> head ; while ( $ converter !== null ) { $ converter -> format ( $ sbuf , $ event ) ; $ converter = $ converter -> next ; } return $ sbuf ; }

Produces a formatted string as specified by the conversion pattern.

@param LoggerLoggingEvent $event
@return string

Produces a formatted string as specified by the conversion pattern .


public function addFilter($filter) {
		if($this->filter === null) {
			$this->filter = $filter;
		} else {
			$this->filter->addNext($filter);
		}
	}

public function addFilter ( $ filter ) { if ( $ this -> filter === null ) { $ this -> filter = $ filter ; } else { $ this -> filter -> addNext ( $ filter ) ; } }

Adds a filter to the end of the filter chain.
@param LoggerFilter $filter add a new LoggerFilter

Adds a filter to the end of the filter chain .


public function isAsSevereAsThreshold($level) {
		if($this->threshold === null) {
			return true;
		}
		return $level->isGreaterOrEqual($this->getThreshold());
	}

public function isAsSevereAsThreshold ( $ level ) { if ( $ this -> threshold === null ) { return true ; } return $ level -> isGreaterOrEqual ( $ this -> getThreshold ( ) ) ; }

Checks whether the message level is below the appender's threshold.

If there is no threshold set, then the return value is always <i>true</i>.

@param LoggerLevel $level
@return boolean Returns true if level is greater or equal than
threshold, or if the threshold is not set. Otherwise returns false.

Checks whether the message level is below the appender s threshold .


protected function warn($message) {
		$id = get_class($this) . (empty($this->name) ? '' : ":{$this->name}");
		trigger_error("log4php: [$id]: $message", E_USER_WARNING);
	}

protected
function
warn
(
$
message
)
{
$
id
=
get_class
(
$
this
)
.
(
empty
(
$
this
->
name
)
''
:
":{$this->name}"
)
;
trigger_error
(
"log4php: [$id]: $message"
,
E_USER_WARNING
)
;
}

Triggers a warning for this logger with the given message.

Triggers a warning for this logger with the given message .


public function getSuggestions()
    {
        if (is_null($this->suggestions))
            $this->suggestions = $this->createSuggestions();

        return $this->suggestions;
    }

public function getSuggestions ( ) { if ( is_null ( $ this -> suggestions ) ) $ this -> suggestions = $ this -> createSuggestions ( ) ; return $ this -> suggestions ; }

Get the suggestions from FACT-Finder as an array of SuggestQuery's.

@return FACTFinder\Data\SuggestQuery[]

Get the suggestions from FACT - Finder as an array of SuggestQuery s .


public static function getClassName($name)
    {
        $name = trim(preg_replace('/^FACTFinder\\\\/i', '', $name));

        // check whether there is a custom or lib-unrelated class
        $customClassName     = 'FACTFinder\Custom\\' . $name;
        $factfinderClassName = 'FACTFinder\\' . $name;
        $defaultClassName    = $name;

        if (self::$loadCustomClasses && class_exists($customClassName))
            $className = $customClassName;
        else if (class_exists($factfinderClassName))
            $className = $factfinderClassName;
        else if (class_exists($defaultClassName))
            $className = $defaultClassName;
        else
            throw new \Exception("class '$factfinderClassName' not found");
        return $className;
    }

Expects a fully qualified class name. if the leading namespace is omitted
or "FACTFinder", we first check whether there is a custom class in
namespace "FACTFinder\Custom\", then we look in "FACTFinder\". If none of
them exist, it also checks if the name is the class name itself.
Note that classes in the \Custom namespace should inherit the class they
overwrite - otherwise some of the type hinting within the library might
break.

@param string $name The class name to be resolved.

@return string The class name to be used.

Expects a fully qualified class name . if the leading namespace is omitted or FACTFinder we first check whether there is a custom class in namespace FACTFinder \ Custom \ then we look in FACTFinder \ . If none of them exist it also checks if the name is the class name itself . Note that classes in the \ Custom namespace should inherit the class they overwrite - otherwise some of the type hinting within the library might break .


private function rollOver() {
		// If maxBackups <= 0, then there is no file renaming to be done.
		if($this->maxBackupIndex > 0) {
			// Delete the oldest file, to keep Windows happy.
			$file = $this->file . '.' . $this->maxBackupIndex;

			if (file_exists($file) && !unlink($file)) {
				throw new LoggerException("Unable to delete oldest backup file from [$file].");
			}

			// Map {(maxBackupIndex - 1), ..., 2, 1} to {maxBackupIndex, ..., 3, 2}
			$this->renameArchievedLogs($this->file);

			// Backup the active file
			$this->moveToBackup($this->file);
		}

		// Truncate the active file
		ftruncate($this->fp, 0);
		rewind($this->fp);
	}

Implements the usual roll over behaviour.

If MaxBackupIndex is positive, then files File.1, ..., File.MaxBackupIndex -1 are renamed to File.2, ..., File.MaxBackupIndex.
Moreover, File is renamed File.1 and closed. A new File is created to receive further log output.

If MaxBackupIndex is equal to zero, then the File is truncated with no backup files created.

Rollover must be called while the file is locked so that it is safe for concurrent access.

@throws LoggerException If any part of the rollover procedure fails.

Implements the usual roll over behaviour .


public function activateOptions() {
		try {
			$this->establishConnection();
		} catch (PDOException $e) {
			$this->warn("Failed connecting to database. Closing appender. Error: " . $e->getMessage());
			$this->close();
			return;
		}

		// Parse the insert patterns; pattern parts are comma delimited
		$pieces = explode(',', $this->insertPattern);
		$converterMap = LoggerLayoutPattern::getDefaultConverterMap();
		foreach($pieces as $pattern) {
			$parser = new LoggerPatternParser($pattern, $converterMap);
			$this->converters[] = $parser->parse();
		}

		$this->closed = false;
	}

Acquires a database connection based on parameters.
Parses the insert pattern to create a chain of converters which will be
used in forming query parameters from logging events.

Acquires a database connection based on parameters . Parses the insert pattern to create a chain of converters which will be used in forming query parameters from logging events .


public function append(LoggerLoggingEvent $event) {

		for ($attempt = 1; $attempt <= $this->reconnectAttempts + 1; $attempt++) {
			try {
				// Attempt to write to database
				$this->preparedInsert->execute($this->format($event));
				$this->preparedInsert->closeCursor();
				break;
			} catch (PDOException $e) {
				$this->warn("Failed writing to database: ". $e->getMessage());

				// Close the appender if it's the last attempt
				if ($attempt > $this->reconnectAttempts) {
					$this->warn("Failed writing to database after {$this->reconnectAttempts} reconnect attempts. Closing appender.");
					$this->close();
				// Otherwise reconnect and try to write again
				} else {
					$this->warn("Attempting a reconnect (attempt $attempt of {$this->reconnectAttempts}).");
					$this->establishConnection();
				}
			}
		}
	}

Appends a new event to the database.

If writing to database fails, it will retry by re-establishing the
connection up to $reconnectAttempts times. If writing still fails,
the appender will close.


protected function format(LoggerLoggingEvent $event) {
		$params = array();
		foreach($this->converters as $converter) {
			$buffer = '';
			while ($converter !== null) {
				$converter->format($buffer, $event);
				$converter = $converter->next;
			}
			$params[] = $buffer;
		}
		return $params;
	}

protected function format ( LoggerLoggingEvent $ event ) { $ params = array ( ) ; foreach ( $ this -> converters as $ converter ) { $ buffer = '' ; while ( $ converter !== null ) { $ converter -> format ( $ buffer , $ event ) ; $ converter = $ converter -> next ; } $ params [ ] = $ buffer ; } return $ params ; }

Converts the logging event to a series of database parameters by using
the converter chain which was set up on activation.

Converts the logging event to a series of database parameters by using the converter chain which was set up on activation .


public function generateUrl($parameters, $target = null)
    {
        $parameters = $this->parametersConverter
                           ->convertServerToClientParameters($parameters);

        $parameters = $this->encodingConverter != null ? $this->encodingConverter->encodeClientUrlData($parameters) : $parameters;

        if (!is_string($target))
            $target = $this->requestParser->getRequestTarget();

        if ($parameters->offsetExists('seoPath')) {
            $seoPath = $parameters['seoPath'];
            $parameters->offsetUnset('seoPath');
            $seoPathPosition = strrpos($target, "/s/");
            if ($seoPathPosition > -1) {
                $target = substr($target, 0, $seoPathPosition);
            }
            $url = rtrim($target, '/') . '/s' . urldecode($seoPath) . '?' . $parameters->toPhpQueryString();
        } else {
            $url = $target . '?' . $parameters->toPhpQueryString();
        }
        return $url;
    }

public function generateUrl ( $ parameters , $ target = null ) { $ parameters = $ this -> parametersConverter -> convertServerToClientParameters ( $ parameters ) ; $ parameters = $ this -> encodingConverter != null ? $ this -> encodingConverter -> encodeClientUrlData ( $ parameters ) : $ parameters ; if ( ! is_string ( $ target ) ) $ target = $ this -> requestParser -> getRequestTarget ( ) ; if ( $ parameters -> offsetExists ( 'seoPath' ) ) { $ seoPath = $ parameters [ 'seoPath' ] ; $ parameters -> offsetUnset ( 'seoPath' ) ; $ seoPathPosition = strrpos ( $ target , "/s/" ) ; if ( $ seoPathPosition > - 1 ) { $ target = substr ( $ target , 0 , $ seoPathPosition ) ; } $ url = rtrim ( $ target , '/' ) . '/s' . urldecode ( $ seoPath ) . '?' . $ parameters -> toPhpQueryString ( ) ; } else { $ url = $ target . '?' . $ parameters -> toPhpQueryString ( ) ; } return $ url ; }

Generates a link to be used on the page that leads to the client from a
set of server parameters. Note that the link will still be UTF-8 encoded.
If the page uses a different encoding, conversion to that encoding has to
be done when actually rendering the string to the page.

TODO: Should the signature be more similar to that of \Server\UrlBuilder?

@param FACTFinder\Util\Parameters $parameters The server parameters that
should be retrieved when the link is followed.
@param string $target An optional request target. If omitted, the target
of the current request will be used. For instance, this parameter
can be used if a product detail page needs a different target.

@return string

Generates a link to be used on the page that leads to the client from a set of server parameters . Note that the link will still be UTF - 8 encoded . If the page uses a different encoding conversion to that encoding has to be done when actually rendering the string to the page .


public function getFeedback($label)
    {
        $feedback = array();
        foreach ($this as $campaign)
            if ($campaign->hasFeedback($label))
                $feedback[] = $campaign->getFeedback($label);

        return implode(PHP_EOL, $feedback);
    }

public function getFeedback ( $ label ) { $ feedback = array ( ) ; foreach ( $ this as $ campaign ) if ( $ campaign -> hasFeedback ( $ label ) ) $ feedback [ ] = $ campaign -> getFeedback ( $ label ) ; return implode ( PHP_EOL , $ feedback ) ; }

Returns all feedback texts for the given label, concatenated with
PHP_EOL.

@see Campaign::getFeedback()
@param string $label
@return string

Returns all feedback texts for the given label concatenated with PHP_EOL .


public function getPushedProducts()
    {
        $pushedProducts = array();
        foreach ($this as $campaign)
            if ($campaign->hasPushedProducts())
                foreach ($campaign->getPushedProducts() as $product)
                    $pushedProducts[] = $product;

        return $pushedProducts;
    }

public function getPushedProducts ( ) { $ pushedProducts = array ( ) ; foreach ( $ this as $ campaign ) if ( $ campaign -> hasPushedProducts ( ) ) foreach ( $ campaign -> getPushedProducts ( ) as $ product ) $ pushedProducts [ ] = $ product ; return $ pushedProducts ; }

Returns an array with the pushed products from all campaigns. Note that
if a product shows up in multiple campaigns, it will be duplicated in the
result of this function.

@see Campaign::getPushedProducts()
@return Record[]

Returns an array with the pushed products from all campaigns . Note that if a product shows up in multiple campaigns it will be duplicated in the result of this function .


public function getActiveQuestions()
    {
        $activeQuestions = array();
        foreach ($this as $campaign)
            if ($campaign->hasActiveQuestions())
                foreach ($campaign->getActiveQuestions() as $question)
                    $activeQuestions[] = $question;

        return $activeQuestions;
    }

public function getActiveQuestions ( ) { $ activeQuestions = array ( ) ; foreach ( $ this as $ campaign ) if ( $ campaign -> hasActiveQuestions ( ) ) foreach ( $ campaign -> getActiveQuestions ( ) as $ question ) $ activeQuestions [ ] = $ question ; return $ activeQuestions ; }

Returns an array with the active questions from all campaigns.

@see Campaign::getActiveQuestions()
@return Record[]

Returns an array with the active questions from all campaigns .


public function getAdvisorTree()
    {
        $advisorTree = array();
        foreach ($this as $campaign)
            if ($campaign->hasAdvisorTree())
                foreach ($campaign->getAdvisorTree() as $question)
                    $advisorTree[] = $question;

        return $advisorTree;
    }

public function getAdvisorTree ( ) { $ advisorTree = array ( ) ; foreach ( $ this as $ campaign ) if ( $ campaign -> hasAdvisorTree ( ) ) foreach ( $ campaign -> getAdvisorTree ( ) as $ question ) $ advisorTree [ ] = $ question ; return $ advisorTree ; }

Returns an array with the root questions of the advisor trees from all
campaigns.

@see Campaign::getAdvisorTree()
@return Record[]

Returns an array with the root questions of the advisor trees from all campaigns .


public function activateOptions() {
		parent::activateOptions();

		if (empty($this->datePattern)) {
			$this->warn("Required parameter 'datePattern' not set. Closing appender.");
			$this->closed = true;
			return;
		}
	}

Additional validation for the date pattern.

Additional validation for the date pattern .


public function append(LoggerLoggingEvent $event) {
		$eventDate = $this->getDate($event->getTimestamp());

		// Initial setting of current date
		if (!isset($this->currentDate)) {
			$this->currentDate = $eventDate;
		}

		// Check if rollover is needed
		else if ($this->currentDate !== $eventDate) {
			$this->currentDate = $eventDate;

			// Close the file if it's open.
			// Note: $this->close() is not called here because it would set
			//       $this->closed to true and the appender would not recieve
			//       any more logging requests
			if (is_resource($this->fp)) {
				$this->write($this->layout->getFooter());
				fclose($this->fp);
			}
			$this->fp = null;
		}

		parent::append($event);
	}

Appends a logging event.

If the target file changes because of passage of time (e.g. at midnight)
the current file is closed. A new file, with the new date, will be
opened by the write() method.


public function findById($id)
    {
        if(!$permission = $this->createModel()->newQuery()->find($id)) {
            throw new PermissionNotFoundException("A permission could not be found with ID [$id].");
        }

        return $permission;
    }

Find a permission by the given permission id
@param  int $id
@return Permission


public function findByValue($value)
    {
        if(!$permission = $this->createModel()->newQuery()->where('value', '=', $value)->get()->first()) {
            throw new PermissionNotFoundException("A permission could not be found with Value [$value].");
        }

        return $permission;
    }

Find a permission by the given permission value
@param  string $value
@return Permission


public static function renderItem($item, $active)
    {
        $class = "";
        if($active === true) {
            $class = "current";
        }

        $html = '';
        if($item["icon"] !== '') {
            $html .= '';
        }

        $html .= $item["title"].'';

        return $html;
    }

public
static
function
renderItem
(
$
item
,
$
active
)
{
$
class
=
""
;
if
(
$
active
===
true
)
{
$
class
=
"current"
;
}
$
html
=
''
;
if
(
$
item
[
"icon"
]
!==
''
)
{
$
html
.=
''
;
}
$
html
.=
$
item
[
"title"
]
.
''
;
return
$
html
;
}

Render the current item
@param array $item part of the breadcrumb
@param boolean $active current breadcrumb is active
@return string


protected function setupLayout()
    {
        $this->layout = View::make(Config::get('syntara::views.master'));
        $this->layout->title = 'Syntara - Dashboard';
        $this->layout->breadcrumb = array();
    }

protected
function
setupLayout
(
)
{
$
this
->
layout
=
View
::
make
(
Config
::
get
(
'syntara::views.master'
)
)
;
$
this
->
layout
->
title
=
'Syntara - Dashboard'
;
$
this
->
layout
->
breadcrumb
=
array
(
)
;
}

Setup the layout used by the controller.

@return void

Setup the layout used by the controller .


public function getIndex()
    {
        // get alls users
        $emptyUsers =  Sentry::getUserProvider()->getEmptyUser();

        // users search
        $userId = Input::get('userIdSearch');
        if(!empty($userId)) {
            $emptyUsers = $emptyUsers->where('users.id', $userId);
        }

        $username = Input::get('usernameSearch');
        if(!empty($username)) {
            $emptyUsers = $emptyUsers->where('username', 'LIKE', '%'.$username.'%');
        }

        $firstName = Input::get('firstNameSearch');
        if(!empty($firstName)) {
            $emptyUsers = $emptyUsers->where('first_name', 'LIKE', '%'.$firstName.'%');
        }

        $lastName = Input::get('lastNameSearch');
        if(!empty($lastName)) {
            $emptyUsers = $emptyUsers->where('last_name', 'LIKE', '%'.$lastName.'%');
        }

        $email = Input::get('emailSearch');
        if(!empty($email)) {
            $emptyUsers = $emptyUsers->where('email', 'LIKE', '%'.$email.'%');
        }

        $bannedUsers = Input::get('bannedSearch');
        if(isset($bannedUsers) && $bannedUsers !== "") {
            $emptyUsers = $emptyUsers->join('throttle', 'throttle.user_id', '=', 'users.id')
                ->where('throttle.banned', '=', $bannedUsers)
                ->select('users.id', 'users.username', 'users.last_name', 'users.first_name', 'users.email', 'users.permissions', 'users.activated');
        }

        $emptyUsers->distinct();

        $users = $emptyUsers->paginate(Config::get('syntara::config.item-perge-page'));
        $datas['links'] = $users->links();
        $datas['users'] = $users;

        // ajax request : reload only content container
        if(Request::ajax()) {
            $html = View::make(Config::get('syntara::views.users-list'), array('datas' => $datas))->render();

            return Response::json(array('html' => $html));
        }

        $this->layout = View::make(Config::get('syntara::views.users-index'), array('datas' => $datas));
        $this->layout->title = trans('syntara::users.titles.list');
        $this->layout->breadcrumb = Config::get('syntara::breadcrumbs.users');
    }

Display a list of all users

@return Response


public function getCreate()
    {
        $groups = Sentry::getGroupProvider()->findAll();
        $permissions = PermissionProvider::findAll();

        $this->layout = View::make(Config::get('syntara::views.user-create'), array('groups' => $groups, 'permissions' => $permissions));
        $this->layout->title = trans('syntara::users.titles.new');
        $this->layout->breadcrumb = Config::get('syntara::breadcrumbs.create_user');
    }

public function getCreate ( ) { $ groups = Sentry :: getGroupProvider ( ) -> findAll ( ) ; $ permissions = PermissionProvider :: findAll ( ) ; $ this -> layout = View :: make ( Config :: get ( 'syntara::views.user-create' ) , array ( 'groups' => $ groups , 'permissions' => $ permissions ) ) ; $ this -> layout -> title = trans ( 'syntara::users.titles.new' ) ; $ this -> layout -> breadcrumb = Config :: get ( 'syntara::breadcrumbs.create_user' ) ; }


public function postCreate()
    {
        try {
            $validator = new UserValidator(Input::all(), 'create');

            $permissionsValues = Input::get('permission');
            $permissions = $this->_formatPermissions($permissionsValues);

            if(!$validator->passes()) {
                return Response::json(array('userCreated' => false, 'errorMessages' => $validator->getErrors()));
            }

            // create user
            $user = Sentry::getUserProvider()->create(array(
                'email'    => Input::get('email'),
                'password' => Input::get('pass'),
                'username' => Input::get('username'),
                'last_name' => (string)Input::get('last_name'),
                'first_name' => (string)Input::get('first_name'),
                'permissions' => $permissions
            ));

            // activate user
            $activationCode = $user->getActivationCode();
            if(Config::get('syntara::config.user-activation') === 'auto') {
                $user->attemptActivation($activationCode);
            } elseif(Config::get('syntara::config.user-activation') === 'email') {
                $datas = array(
                    'code' => $activationCode,
                    'username' => $user->username
                );

                // send email
                Mail::queue(Config::get('syntara::mails.user-activation-view'), $datas, function ($message) use ($user) {
                    $message->from(Config::get('syntara::mails.email'), Config::get('syntara::mails.contact'))
                            ->subject(Config::get('syntara::mails.user-activation-object'));
                    $message->to($user->getLogin());
                });
            }

            $groups = Input::get('groups');
            if(isset($groups) && is_array($groups)) {
                foreach($groups as $groupId) {
                    $group = Sentry::getGroupProvider()->findById($groupId);
                    $user->addGroup($group);
                }
            }
        } catch (\Cartalyst\Sentry\Users\LoginRequiredException $e){} // already catch by validators
        catch (\Cartalyst\Sentry\Users\PasswordRequiredException $e){} // already catch by validators
        catch (\Cartalyst\Sentry\Groups\GroupNotFoundException $e){} catch (\Cartalyst\Sentry\Users\UserExistsException $e) {
            return json_encode(array('userCreated' => false, 'message' => trans('syntara::users.messages.user-email-exists'), 'messageType' => 'danger'));
        } catch(\Exception $e) {
            return Response::json(array('userCreated' => false, 'message' => trans('syntara::users.messages.user-name-exists'), 'messageType' => 'danger'));
        }

        return json_encode(array('userCreated' => true, 'redirectUrl' => URL::route('listUsers')));
    }


public function putActivate($userId)
    {
        try {
            $user = Sentry::getUserProvider()->findById($userId);
            $activationCode = $user->getActivationCode();
            $user->attemptActivation($activationCode);
        } catch (\Cartalyst\Sentry\Users\UserNotFoundException $e) {
            return Response::json(array('deletedUser' => false, 'message' => trans('syntara::users.messages.not-found'), 'messageType' => 'danger'));
        } catch (\Cartalyst\Sentry\Users\UserAlreadyActivatedException $e) {
            return Response::json(array('deletedUser' => false, 'message' => trans('syntara::users.messages.activate-already'), 'messageType' => 'danger'));
        }

        return Response::json(array('deletedUser' => true, 'message' => trans('syntara::users.messages.activate-success'), 'messageType' => 'success'));
    }

Activate a user since the dashboard
@param  int $userId
@return Response


public function getShow($userId)
    {
        try {
            $user = Sentry::getUserProvider()->findById($userId);
            $throttle = Sentry::getThrottleProvider()->findByUserId($userId);
            $groups = Sentry::getGroupProvider()->findAll();

            // get user permissions
            $permissions = PermissionProvider::findAll();
            $userPermissions = array();
            foreach($user->getPermissions() as $permissionValue => $key) {
                try {
                    $p = PermissionProvider::findByValue($permissionValue);
                    foreach($permissions as $key => $permission) {
                        if($p->getId() === $permission->getId()) {
                            $userPermissions[] = $permission;
                            unset($permissions[$key]);
                        }
                    }
                } catch(\MrJuliuss\Syntara\Models\Permissions\PermissionNotFoundException $e){}
            }

            // ajax request : reload only content container
            if(Request::ajax()) {
                $html = View::make(Config::get('syntara::views.user-informations'), array('user' => $user, 'throttle' => $throttle))->render();

                return Response::json(array('html' => $html));
            }

            $this->layout = View::make(Config::get('syntara::views.user-profile'), array(
                'user' => $user,
                'throttle' => $throttle,
                'groups' => $groups,
                'ownPermissions' => $userPermissions,
                'permissions' => $permissions
            ));

            $this->layout->title = $user->username;
            $this->layout->breadcrumb = array(
                    array(
                        'title' => trans('syntara::breadcrumbs.users'),
                        'link' => URL::route('listUsers'),
                        'icon' => 'glyphicon-user'
                    ),
                    array(
                     'title' => $user->username,
                     'link' => URL::current(),
                     'icon' => ''
                    )
            );
        } catch (\Cartalyst\Sentry\Users\UserNotFoundException $e) {
            $this->layout = View::make(Config::get('syntara::views.error'), array('message' => trans('syntara::users.messages.not-found')));
        }
    }


public function getIndex()
    {
        $emptyGroup =  Sentry::getGroupProvider()->createModel();

        // Ajax search
        $groupId = Input::get('groupIdSearch');
        if(!empty($groupId)) {
            $emptyGroup = $emptyGroup->where('id', $groupId);
        }
        $groupname = Input::get('groupnameSearch');
        if(!empty($groupname)) {
            $emptyGroup = $emptyGroup->where('name', 'LIKE', '%'.$groupname.'%');
        }

        $groups = $emptyGroup->paginate(Config::get('syntara::config.item-perge-page'));

        // ajax: reload only the content container
        if(Request::ajax()) {
            $html = View::make(Config::get('syntara::views.groups-list'), array('groups' => $groups))->render();

            return Response::json(array('html' => $html));
        }

        $this->layout = View::make(Config::get('syntara::views.groups-index'), array('groups' => $groups));
        $this->layout->title = trans('syntara::groups.titles.list');
        $this->layout->breadcrumb = Config::get('syntara::breadcrumbs.groups');
    }


public function putShow($groupId)
    {
        $groupname = Input::get('groupname');
        $permissions = array();

        $errors = $this->_validateGroup(Input::get('permission'), $groupname, $permissions);
        if(!empty($errors)) {
            return Response::json(array('groupUpdated' => false, 'errorMessages' => $errors));
        } else {
            try {
                $group = Sentry::getGroupProvider()->findById($groupId);
                $group->name = $groupname;
                $group->permissions = $permissions;

                $permissions = (empty($permissions)) ? '' : json_encode($permissions);
                // delete permissions in db
                DB::table('groups')
                    ->where('id', $groupId)
                    ->update(array('permissions' => $permissions));

                if($group->save()) {
                    return Response::json(array('groupUpdated' => true, 'message' => trans('syntara::groups.messages.success'), 'messageType' => 'success'));
                } else {
                    return Response::json(array('groupUpdated' => false, 'message' => trans('syntara::groups.messages.try'), 'messageType' => 'danger'));
                }
            } catch (\Cartalyst\Sentry\Groups\NameRequiredException $e) {} catch (\Cartalyst\Sentry\Groups\GroupExistsException $e) {
                return Response::json(array('groupUpdated' => false, 'message' => trans('syntara::groups.messages.exists'), 'messageType' => 'danger'));
            }
        }
    }

public
function
putShow
(
$
groupId
)
{
$
groupname
=
Input
::
get
(
'groupname'
)
;
$
permissions
=
array
(
)
;
$
errors
=
$
this
->
_validateGroup
(
Input
::
get
(
'permission'
)
,
$
groupname
,
$
permissions
)
;
if
(
!
empty
(
$
errors
)
)
{
return
Response
::
json
(
array
(
'groupUpdated'
=>
false
,
'errorMessages'
=>
$
errors
)
)
;
}
else
{
try
{
$
group
=
Sentry
::
getGroupProvider
(
)
->
findById
(
$
groupId
)
;
$
group
->
name
=
$
groupname
;
$
group
->
permissions
=
$
permissions
;
$
permissions
=
(
empty
(
$
permissions
)
)
''
:
json_encode
(
$
permissions
)
;
// delete permissions in db
DB
::
table
(
'groups'
)
->
where
(
'id'
,
$
groupId
)
->
update
(
array
(
'permissions'
=>
$
permissions
)
)
;
if
(
$
group
->
save
(
)
)
{
return
Response
::
json
(
array
(
'groupUpdated'
=>
true
,
'message'
=>
trans
(
'syntara::groups.messages.success'
)
,
'messageType'
=>
'success'
)
)
;
}
else
{
return
Response
::
json
(
array
(
'groupUpdated'
=>
false
,
'message'
=>
trans
(
'syntara::groups.messages.try'
)
,
'messageType'
=>
'danger'
)
)
;
}
}
catch
(
\
Cartalyst
\
Sentry
\
Groups
\
NameRequiredException
$
e
)
{
}
catch
(
\
Cartalyst
\
Sentry
\
Groups
\
GroupExistsException
$
e
)
{
return
Response
::
json
(
array
(
'groupUpdated'
=>
false
,
'message'
=>
trans
(
'syntara::groups.messages.exists'
)
,
'messageType'
=>
'danger'
)
)
;
}
}
}


public function deleteUserFromGroup($groupId, $userId)
    {
        try {
            $user = Sentry::getUserProvider()->findById($userId);
            $group = Sentry::getGroupProvider()->findById($groupId);
            $user->removeGroup($group);

            return Response::json(array('userDeleted' => true, 'message' => trans('syntara::groups.messages.user-removed-success'), 'messageType' => 'success'));
        } catch (\Cartalyst\Sentry\Users\UserNotFoundException $e) {
            return Response::json(array('userDeleted' => false, 'message' => trans('syntara::users.messages.not-found'), 'messageType' => 'danger'));
        } catch(\Cartalyst\Sentry\Groups\GroupNotFoundException $e) {
            return Response::json(array('userDeleted' => false, 'message' => trans('syntara::groups.messages.not-found'), 'messageType' => 'danger'));
        }
    }

Remove user from group
@param int $groupId
@param int $userId
@return Response


public function addUserInGroup()
    {
        try {
            $user = Sentry::getUserProvider()->findById(Input::get('userId'));
            $group = Sentry::getGroupProvider()->findById(Input::get('groupId'));
            $user->addGroup($group);

            return Response::json(array('userAdded' => true, 'message' => trans('syntara::groups.messages.user-add-success'), 'messageType' => 'success'));
        } catch (\Cartalyst\Sentry\Users\UserNotFoundException $e) {
            return Response::json(array('userAdded' => false, 'message' => trans('syntara::users.messages.not-found'), 'messageType' => 'danger'));
        } catch(\Cartalyst\Sentry\Groups\GroupNotFoundException $e) {
            return Response::json(array('userAdded' => false, 'message' => trans('syntara::groups.messages.not-found'), 'messageType' => 'danger'));
        }
    }


protected function _validateGroup($permissionsValues, $groupname, &$permissions)
    {
        $errors = array();
        // validate permissions
        if(!empty($permissionsValues)) {
            foreach($permissionsValues as $key => $permission) {
               $permissions[$key] = 1;
            }
        }
        // validate group name
        $validator = new GroupValidator(Input::all());

        $gnErrors = array();
        if(!$validator->passes()) {
            $gnErrors = $validator->getErrors();
        }

        return $gnErrors;
    }

protected
function
_validateGroup
(
$
permissionsValues
,
$
groupname
,
&
$
permissions
)
{
$
errors
=
array
(
)
;
// validate permissions
if
(
!
empty
(
$
permissionsValues
)
)
{
foreach
(
$
permissionsValues
as
$
key
=>
$
permission
)
{
$
permissions
[
$
key
]
=
1
;
}
}
// validate group name
$
validator
=
new
GroupValidator
(
Input
::
all
(
)
)
;
$
gnErrors
=
array
(
)
;
if
(
!
$
validator
->
passes
(
)
)
{
$
gnErrors
=
$
validator
->
getErrors
(
)
;
}
return
$
gnErrors
;
}

Validate group informations
@param array $permissionsValues
@param string $groupname
@return array


private function loadIncludes()
    {
        // Add file names without the `php` extension to this list as needed.
        $filesToLoad = array(
            'composers',
            'filters',
            'routes',
        );

        // Run through $filesToLoad array.
        foreach ($filesToLoad as $file) {
            // Add needed database structure and file extension.
            $file = __DIR__ . '/../../' . $file . '.php';
            // If file exists, include.
            if (is_file($file)) include $file;
        }
    }

Include some specific files from the src-root.

@return void

Include some specific files from the src - root .


public function registerHelpers()
    {
        // register breadcrumbs
        $this->app['breadcrumbs'] = $this->app->share(function () {
            return new \MrJuliuss\Syntara\Helpers\Breadcrumbs();
        });

        // shortcut so developers don't need to add an Alias in app/config/app.php
        $this->app->booting(function () {
            $loader = \Illuminate\Foundation\AliasLoader::getInstance();
            $loader->alias('Breadcrumbs', 'MrJuliuss\Syntara\Facades\Breadcrumbs');
        });
    }


public function getIndex()
    {
        $this->layout = View::make(Config::get('syntara::views.dashboard-index'));
        $this->layout->title = trans('syntara::all.titles.index');
        $this->layout->breadcrumb = Config::get('syntara::breadcrumbs.dashboard');
    }

public function getIndex ( ) { $ this -> layout = View :: make ( Config :: get ( 'syntara::views.dashboard-index' ) ) ; $ this -> layout -> title = trans ( 'syntara::all.titles.index' ) ; $ this -> layout -> breadcrumb = Config :: get ( 'syntara::breadcrumbs.dashboard' ) ; }


public function postLogin()
    {
        try {
            $validator = new UserValidator(Input::all(), 'login');
            $loginAttribute = Config::get('cartalyst/sentry::users.login_attribute');

            if(!$validator->passes()) {
                 return Response::json(array('logged' => false, 'errorMessages' => $validator->getErrors()));
            }

            $credentials = array(
                $loginAttribute => Input::get($loginAttribute),
                'password' => Input::get('pass'),
            );

            // authenticate user
            Sentry::authenticate($credentials, (bool)Input::get('remember'));
        } catch(\Cartalyst\Sentry\Throttling\UserBannedException $e) {
            return Response::json(array('logged' => false, 'errorMessage' => trans('syntara::all.messages.banned'), 'errorType' => 'danger'));
        } catch (\RuntimeException $e) {
            return Response::json(array('logged' => false, 'errorMessage' => trans('syntara::all.messages.login-failed'), 'errorType' => 'danger'));
        }

        return Response::json(array('logged' => true));
    }


public function getIndex()
    {
        $permissions = PermissionProvider::createModel();
        $permissionId = Input::get('permissionIdSearch');
        if(!empty($permissionId)) {
            $permissions = $permissions->where('id', $permissionId);
        }
        $permissionName = Input::get('permissionNameSearch');
        if(!empty($permissionName)) {
            $permissions = $permissions->where('name', 'LIKE', '%'.$permissionName.'%');
        }
        $permissionValue = Input::get('permissionValueSearch');
        if(!empty($permissionValue)) {
            $permissions = $permissions->where('value', 'LIKE', '%'.$permissionValue.'%');
        }

        $permissions = $permissions->paginate(Config::get('syntara::config.item-perge-page'));

        // ajax request : reload only content container
        if(Request::ajax()) {
            $html = View::make(Config::get('syntara::views.permissions-list'), array('permissions' => $permissions))->render();

            return Response::json(array('html' => $html));
        }

        $this->layout = View::make(Config::get('syntara::views.permissions-index'), array('permissions' => $permissions));
        $this->layout->title = trans('syntara::permissions.titles.list');
        $this->layout->breadcrumb = Config::get('syntara::breadcrumbs.permissions');
    }


public function postCreate()
    {
        try {
            $validator = new PermissionValidator(Input::all());
            if(!$validator->passes()) {
                return Response::json(array('permissionCreated' => false, 'errorMessages' => $validator->getErrors()));
            }

            // create permission
            $permission = PermissionProvider::createPermission(Input::all());
        } catch (\MrJuliuss\Syntara\Models\Permissions\NameRequiredException $e) {} catch (\MrJuliuss\Syntara\Models\Permissions\ValueRequiredException $e) {} catch (\MrJuliuss\Syntara\Models\Permissions\PermissionExistsException $e) {
            return json_encode(array('permissionCreated' => false, 'message' => trans('syntara::permissions.messages.exists'), 'messageType' => 'danger'));
        }

        return json_encode(array('permissionCreated' => true, 'redirectUrl' => URL::route('listPermissions')));
    }

public
function
postCreate
(
)
{
try
{
$
validator
=
new
PermissionValidator
(
Input
::
all
(
)
)
;
if
(
!
$
validator
->
passes
(
)
)
{
return
Response
::
json
(
array
(
'permissionCreated'
=>
false
,
'errorMessages'
=>
$
validator
->
getErrors
(
)
)
)
;
}
// create permission
$
permission
=
PermissionProvider
::
createPermission
(
Input
::
all
(
)
)
;
}
catch
(
\
MrJuliuss
\
Syntara
\
Models
\
Permissions
\
NameRequiredException
$
e
)
{
}
catch
(
\
MrJuliuss
\
Syntara
\
Models
\
Permissions
\
ValueRequiredException
$
e
)
{
}
catch
(
\
MrJuliuss
\
Syntara
\
Models
\
Permissions
\
PermissionExistsException
$
e
)
{
return
json_encode
(
array
(
'permissionCreated'
=>
false
,
'message'
=>
trans
(
'syntara::permissions.messages.exists'
)
,
'messageType'
=>
'danger'
)
)
;
}
return
json_encode
(
array
(
'permissionCreated'
=>
true
,
'redirectUrl'
=>
URL
::
route
(
'listPermissions'
)
)
)
;
}


public function delete($permissionId)
    {
        try {
            $permission = PermissionProvider::findById($permissionId);
            $permission->delete();
        } catch (\MrJuliuss\Syntara\Models\Permissions\PermissionNotFoundException $e) {
            return Response::json(array('deletePermission' => false, 'message' => trans('syntara::permissions.messages.not-found'), 'messageType' => 'danger'));
        }

        return Response::json(array('deletePermission' => true, 'message' => trans('syntara::permissions.messages.remove-success'), 'messageType' => 'success'));
    }


private function paginate() {
        $canvas = $this->pdf->get_canvas();
        $c = array_merge($this->_pagination, $this->config['paginate']);
        $canvas->page_text($c['x'], $c['y'], $c['text'], $c['font'], $c['size'], $c['color']);
    }

private function paginate ( ) { $ canvas = $ this -> pdf -> get_canvas ( ) ; $ c = array_merge ( $ this -> _pagination , $ this -> config [ 'paginate' ] ) ; $ canvas -> page_text ( $ c [ 'x' ] , $ c [ 'y' ] , $ c [ 'text' ] , $ c [ 'font' ] , $ c [ 'size' ] , $ c [ 'color' ] ) ; }


public function authenticate($username, $password)
    {
        $response = $this->post('Permissions.Authenticate', array(
            'login'    => $username,
            'password' => $password,
        ));

		return $this->returnResponse($response);
    }

public function authenticate ( $ username , $ password ) { $ response = $ this -> post ( 'Permissions.Authenticate' , array ( 'login' => $ username , 'password' => $ password , ) ) ; return $ this -> returnResponse ( $ response ) ; }

Internal method to authenticate a set of credentials
Credentials can be found in the SiteCatalyst Admin Console
Admin > Admin Console > Company > Web Services

@param   array $username  - the web services username
@param   array $password  - the web services shared secret
@return  boolean - whether or not the authentication was successful


Uses UUID Version 4
@see http://en.wikipedia.org/wiki/Universally_unique_identifier


public function __isset($flag)
    {
        try {
            $this->checkFlag($flag);
        } catch (\Exception $e) {
            return false;
        }

        $ruleIndex = $this->_flags[$flag];

        return isset($this->_options[$ruleIndex]);
    }

public function __isset ( $ flag ) { try { $ this -> checkFlag ( $ flag ) ; } catch ( \ Exception $ e ) { return false ; } $ ruleIndex = $ this -> _flags [ $ flag ] ; return isset ( $ this -> _options [ $ ruleIndex ] ) ; }

Returns true if an option for the given flag is set.

@return  bool

Returns true if an option for the given flag is set .


public function getRule($flag)
    {
        try {
            $this->checkFlag($flag);
        } catch (Exception $e) {
            return null;
        }

        $ruleIndex = $this->_flags[$flag];

        return $this->_rules[$ruleIndex];
    }

public function getRule ( $ flag ) { try { $ this -> checkFlag ( $ flag ) ; } catch ( Exception $ e ) { return null ; } $ ruleIndex = $ this -> _flags [ $ flag ] ; return $ this -> _rules [ $ ruleIndex ] ; }

Gets the rule associated with the given flag.

@return  array

Gets the rule associated with the given flag .


public function expectsParameter($flag)
    {
        $rule = $this->getRule($flag);
        return $rule && $rule['required'] !== self::PARAM_NOTREQUIRED;
    }

public function expectsParameter ( $ flag ) { $ rule = $ this -> getRule ( $ flag ) ; return $ rule && $ rule [ 'required' ] !== self :: PARAM_NOTREQUIRED ; }

Returns true if the given flag expects a parameter.

@return  bool

Returns true if the given flag expects a parameter .


public function isRequired($flag)
    {
        $rule = $this->getRule($flag);
        return $rule && $rule['required'] === self::PARAM_REQUIRED;
    }

public function isRequired ( $ flag ) { $ rule = $ this -> getRule ( $ flag ) ; return $ rule && $ rule [ 'required' ] === self :: PARAM_REQUIRED ; }

Returns true if the given flag is required.

@return  bool

Returns true if the given flag is required .


public function isOptional($flag)
    {
        $rule = $this->getRule($flag);
        return $rule && $rule['required'] === self::PARAM_OPTIONAL;
    }

public function isOptional ( $ flag ) { $ rule = $ this -> getRule ( $ flag ) ; return $ rule && $ rule [ 'required' ] === self :: PARAM_OPTIONAL ; }

Returns true if the given flag is optional.

@return  bool

Returns true if the given flag is optional .


public function parse(array &$argv=null)
    {
        $this->_options = array();

        if ($argv === null) {
            if (isset($_SERVER['argv'])) {
                $argv = $_SERVER['argv'];
            } else {
                $argv = array();
            }
        }

        $this->_programName = array_shift($argv);

        for ($i = 0; $i < count($argv); $i++) {
            if (preg_match('/^(--?)([a-z][a-z\-]*)(?:=(.+)?)?$/i', $argv[$i], $matches)) {
                if (isset($matches[3])) {
                    # put parameter back on stack of arguments
                    array_splice($argv, $i, 1, $matches[3]);
                    $paramGiven = true;
                } else {
                    # throw away the flag
                    array_splice($argv, $i, 1);
                    $paramGiven = false;
                }

                $flag = $matches[2];
                if ($this->_config & self::CONF_IGNORECASE) {
                    $flag = strtolower($flag);
                }

                if ($matches[1] == '--') {
                    # long flag
                    $this->parseOption($flag, $argv, $i, $paramGiven);
                } else {
                    # short flag
                    foreach (str_split($flag) as $shortFlag) {
                        $this->parseOption($shortFlag, $argv, $i, $paramGiven);
                    }
                }

                # decrement the index for the flag that was taken
                $i--;
            } elseif ($argv[$i] == '--') {
                if ($this->_config & self::CONF_DASHDASH) {
                    # stop processing arguments
                    break;
                }
            }
        }

        return $argv;
    }

Parses the given arguments according to this parser's rules. An exception will be
thrown if any rule is violated.

Note: This function uses a reference to modify the given $argv array. If no argument
values are provided a copy of the global $argv array will be used.

@param   array   $argv       The command line arguments
@return  array               Anything still present in $argv that wasn't matched by a rule
@throws  Exception

Parses the given arguments according to this parser s rules . An exception will be thrown if any rule is violated .


protected function isParam($string)
    {
        if ($this->_config & self::CONF_DASHDASH && $string == '--') {
            return false;
        }

        return !$this->isFlag($string);
    }

protected function isParam ( $ string ) { if ( $ this -> _config & self :: CONF_DASHDASH && $ string == '--' ) { return false ; } return ! $ this -> isFlag ( $ string ) ; }

Returns true if the given string is considered a parameter.

@param   string
@return  bool

Returns true if the given string is considered a parameter .


protected function orderParameters($parameters, $template)
    {
        foreach ($parameters as $key => $value) {
            // if a parameter appears to be a nested type
            if (is_array($value) && !empty($value) && !isset($value[0])) {
                $parameters[$key] = $this->orderParameters($parameters[$key], $template[$key]);
            }
        }

        $defaults = array();

        foreach ($template as $key => $type) {
            $defaults[$key] = null;
        }

        $parameters = array_merge(
            $defaults,
            $parameters
        );

        // ensure there are no extra parameters
        $parameters = array_intersect_key($parameters, $template);

        return $parameters;
    }

this is necessary because order matters with the PHP SoapClient
Essentially, we fill in all the parameters with null values

this is necessary because order matters with the PHP SoapClient Essentially we fill in all the parameters with null values


public function authenticate()
    {
        $auth = $this->getHttpClient()->getAuthService();

        $args = func_get_args(); // php 5.2 requires this be on a separate line

        call_user_func_array(array($auth, 'authenticate'), $args);

        return $this;
    }

Authenticate a user for all next requests

@param  string         $username      AdobeMarketingCloud Web Services username
@param  string         $secret        AdobeMarketingCloud Web Services secret
@return AdobeMarketingCloud               fluent interface


public function getReportApi($options = array())
    {
        if(!isset($this->apis['report']))
        {
            $this->apis['report'] = new Api\Report($this, $options);
        }

        return $this->apis['report'];
    }

public function getReportApi ( $ options = array ( ) ) { if ( ! isset ( $ this -> apis [ 'report' ] ) ) { $ this -> apis [ 'report' ] = new Api \ Report ( $ this , $ options ) ; } return $ this -> apis [ 'report' ] ; }

Get the report API

@param array $options
@return Api\Report


public function getPermissionsApi($options = array())
    {
        if(!isset($this->apis['permissions']))
        {
            $this->apis['permissions'] = new Api\Permissions($this, $options);
        }

        return $this->apis['permissions'];
    }

public function getPermissionsApi ( $ options = array ( ) ) { if ( ! isset ( $ this -> apis [ 'permissions' ] ) ) { $ this -> apis [ 'permissions' ] = new Api \ Permissions ( $ this , $ options ) ; } return $ this -> apis [ 'permissions' ] ; }

Get the permissions API

@return  Api\Permissions  the permissions API


public function getCompanyApi($options = array())
    {
        if(!isset($this->apis['company']))
        {
            $this->apis['company'] = new Api\Company($this, $options);
        }

        return $this->apis['company'];
    }

public function getCompanyApi ( $ options = array ( ) ) { if ( ! isset ( $ this -> apis [ 'company' ] ) ) { $ this -> apis [ 'company' ] = new Api \ Company ( $ this , $ options ) ; } return $ this -> apis [ 'company' ] ; }

Get the company API

@return  Api\Company  the company API


public function getOAuthApi($options = array())
    {
        if(!isset($this->apis['oauth']))
        {
            $this->apis['oauth'] = new Api\OAuth($this, $options);
        }

        return $this->apis['oauth'];
    }

public function getOAuthApi ( $ options = array ( ) ) { if ( ! isset ( $ this -> apis [ 'oauth' ] ) ) { $ this -> apis [ 'oauth' ] = new Api \ OAuth ( $ this , $ options ) ; } return $ this -> apis [ 'oauth' ] ; }

Get the OAuth API

@return  Api\OAuth  the company API


public function request($path, array $parameters = array(), $httpMethod = 'GET', array $options = array())
    {
        $options = array_merge($this->options, $options);

        // create full url
        $url = strtr($options['url'], array(
          ':api_version' => $this->options['api_version'],
          ':protocol'    => $this->options['protocol'],
          ':endpoint'    => $this->options['endpoint'],
          ':path'        => $path
        ));

        // get encoded response
        $response = $this->doRequest($url, $parameters, $httpMethod, $options);
        $this->lastResponse = $response; // for debugging (see getLastResponse)

        // decode response
        $response = $this->decodeResponse($response, $options);

        return $response;
    }

public
function
request
(
$
path
,
array
$
parameters
=
array
(
)
,
$
httpMethod
=
'GET'
,
array
$
options
=
array
(
)
)
{
$
options
=
array_merge
(
$
this
->
options
,
$
options
)
;
// create full url
$
url
=
strtr
(
$
options
[
'url'
]
,
array
(
':api_version'
=>
$
this
->
options
[
'api_version'
]
,
':protocol'
=>
$
this
->
options
[
'protocol'
]
,
':endpoint'
=>
$
this
->
options
[
'endpoint'
]
,
':path'
=>
$
path
)
)
;
// get encoded response
$
response
=
$
this
->
doRequest
(
$
url
,
$
parameters
,
$
httpMethod
,
$
options
)
;
$
this
->
lastResponse
=
$
response
;
// for debugging (see getLastResponse)
// decode response
$
response
=
$
this
->
decodeResponse
(
$
response
,
$
options
)
;
return
$
response
;
}

Send a request to the server, receive a response,
decode the response and returns an associative array

@param  string   $path           Requested API resource path
@param  array    $parameters     Parameters
@param  string   $httpMethod     HTTP method to use
@param  array    $options        Request options

@return array                    Data

Send a request to the server receive a response decode the response and returns an associative array


public function getElements($reportSuiteID, $returnAsIdArray = false)
    {
        $response = $this->post('Report.GetElements', array('reportSuiteID' => $reportSuiteID));
        if ($returnAsIdArray) {
            $filtered = array();
            foreach ($response as $element) {
                $filtered[$element['id']] = $element['name'];
            }
            return array_unique($filtered);
        }
        return $this->returnResponse($response);
    }

public function getElements ( $ reportSuiteID , $ returnAsIdArray = false ) { $ response = $ this -> post ( 'Report.GetElements' , array ( 'reportSuiteID' => $ reportSuiteID ) ) ; if ( $ returnAsIdArray ) { $ filtered = array ( ) ; foreach ( $ response as $ element ) { $ filtered [ $ element [ 'id' ] ] = $ element [ 'name' ] ; } return array_unique ( $ filtered ) ; } return $ this -> returnResponse ( $ response ) ; }

Retrieve the elements to call from your report suite

@param string $reportSuiteID
@param bool $returnAsIdArray

@return array


public function getMetrics($reportSuiteID, $returnAsIdArray = false)
    {
        $response = $this->post('Report.GetMetrics', array('reportSuiteID' => $reportSuiteID));
        if ($returnAsIdArray) {
            $filtered = array();
            foreach ($response as $metric) {
                $filtered[$metric['id']] = $metric['name'];
            }
            return array_unique($filtered);
        }
        return $this->returnResponse($response);
    }

public function getMetrics ( $ reportSuiteID , $ returnAsIdArray = false ) { $ response = $ this -> post ( 'Report.GetMetrics' , array ( 'reportSuiteID' => $ reportSuiteID ) ) ; if ( $ returnAsIdArray ) { $ filtered = array ( ) ; foreach ( $ response as $ metric ) { $ filtered [ $ metric [ 'id' ] ] = $ metric [ 'name' ] ; } return array_unique ( $ filtered ) ; } return $ this -> returnResponse ( $ response ) ; }

Retrieve events for your report suites

@param string $reportSuiteID
@param bool $returnAsIdArray

@return array


protected function retryWhileNotReady($reportId)
    {
        $attempts = 0;
        do {
            $report = $this->post('Report.Get', array(
                'reportID' => $reportId,
            ));
            $sleep = $this->getSleepSeconds(++$attempts, 50);
            if ($sleep !== false) {
                sleep($sleep);
            }
        } while (isset($report['error']) && $report['error'] == 'report_not_ready');

        if (isset($report['report'])) {
            $report = $report['report'];
        } else {
            throw new ReportError($report['error_description'], null);
        }

        return $report;
    }

protected function retryWhileNotReady ( $ reportId ) { $ attempts = 0 ; do { $ report = $ this -> post ( 'Report.Get' , array ( 'reportID' => $ reportId , ) ) ; $ sleep = $ this -> getSleepSeconds ( ++ $ attempts , 50 ) ; if ( $ sleep !== false ) { sleep ( $ sleep ) ; } } while ( isset ( $ report [ 'error' ] ) && $ report [ 'error' ] == 'report_not_ready' ) ; if ( isset ( $ report [ 'report' ] ) ) { $ report = $ report [ 'report' ] ; } else { throw new ReportError ( $ report [ 'error_description' ] , null ) ; } return $ report ; }

Returns a report synchronously, calling getReport every two seconds until the report is ready

@param $reportId
@return tns|bool

Returns a report synchronously calling getReport every two seconds until the report is ready


protected function getSleepSeconds($attempts, $maxAttempts = null)
    {
        if ($maxAttempts && $attempts >= $maxAttempts) {
            return false;
        }

        // very complex.
        return $attempts * $attempts;
    }

protected
function
getSleepSeconds
(
$
attempts
,
$
maxAttempts
=
)
{
if
(
$
maxAttempts
&&
$
attempts
>=
$
maxAttempts
)
{
return
false
;
}
// very complex.
return
$
attempts
*
$
attempts
;
}

Determines next sleep time for report queue checking.
Uses an incredibly complex backing off algorithm so that long requests don't have to check as often.

@param    $attempts      int    The number of checks so far
@param    $maxAttempts    int User specified maximum number of checks

@return    mixed to stop checking OR the number of seconds for the next sleep

Determines next sleep time for report queue checking . Uses an incredibly complex backing off algorithm so that long requests don t have to check as often .


private function parseOptions(array $options, $resetOptions = false)
    {
        foreach ($this->optionsList as $option) {
            if (isset($options[$option])) {
                $this->options[$option] = $options[$option];
            } elseif ($resetOptions && isset($this->options[$option])) {
                unset($this->options[$option]);
            }
        }
    }

private function parseOptions ( array $ options , $ resetOptions = false ) { foreach ( $ this -> optionsList as $ option ) { if ( isset ( $ options [ $ option ] ) ) { $ this -> options [ $ option ] = $ options [ $ option ] ; } elseif ( $ resetOptions && isset ( $ this -> options [ $ option ] ) ) { unset ( $ this -> options [ $ option ] ) ; } } }

Parse Provided options

@param array $options
@param bool $resetOptions


public function get(array $options = [], $returnObject = false, $resetOptions = false, $segment = self::SEGMENT_IMAGES)
    {
        $this->parseOptions($options, $resetOptions);
        $response = $this->client->request('GET', self::API_ROOT . $segment, ['query' => $this->options]);
        $data = $response->getBody()->getContents();
        return json_decode($data, $returnObject);
    }

public function get ( array $ options = [ ] , $ returnObject = false , $ resetOptions = false , $ segment = self :: SEGMENT_IMAGES ) { $ this -> parseOptions ( $ options , $ resetOptions ) ; $ response = $ this -> client -> request ( 'GET' , self :: API_ROOT . $ segment , [ 'query' => $ this -> options ] ) ; $ data = $ response -> getBody ( ) -> getContents ( ) ; return json_decode ( $ data , $ returnObject ) ; }

Get Data from Pixabay API

@param array  $options
@param bool   $returnObject
@param bool   $resetOptions
@param string $segment
@return mixed


public function getImages(array $options = [], $returnObject = false, $resetOptions = false)
    {
        return $this->get($options, $returnObject, $resetOptions, self::SEGMENT_IMAGES);
    }

public function getImages ( array $ options = [ ] , $ returnObject = false , $ resetOptions = false ) { return $ this -> get ( $ options , $ returnObject , $ resetOptions , self :: SEGMENT_IMAGES ) ; }

Get Images from Pixabay API

@param array $options
@param bool  $returnObject
@param bool  $resetOptions

@return mixed


public function getVideos(array $options = [], $returnObject = false, $resetOptions = false)
    {
        return $this->get($options, $returnObject, $resetOptions, self::SEGMENT_VIDEOS);
    }

public function getVideos ( array $ options = [ ] , $ returnObject = false , $ resetOptions = false ) { return $ this -> get ( $ options , $ returnObject , $ resetOptions , self :: SEGMENT_VIDEOS ) ; }

Get Videos from Pixabay API

@param array $options
@param bool  $returnObject
@param bool  $resetOptions

@return mixed


public static function stdout($string)
    {
        $args = func_get_args();
        array_shift($args);

        if (empty($args)) {
            return Console::stdout($string);
        }

        $string = Console::ansiFormat($string, $args);
        return Console::stdout($string);
    }

public static function stdout ( $ string ) { $ args = func_get_args ( ) ; array_shift ( $ args ) ; if ( empty ( $ args ) ) { return Console :: stdout ( $ string ) ; } $ string = Console :: ansiFormat ( $ string , $ args ) ; return Console :: stdout ( $ string ) ; }

Prints a string to STDOUT

You may optionally format the string with ANSI codes by
passing additional parameters using the constants defined in [[\yii\helpers\Console]].

Example:

```
$this->stdout('This will be red and underlined.', Console::FG_RED, Console::UNDERLINE);
```

@param string $string the string to print
@return int|bool Number of bytes printed or false on error


public function getTable(TableSchema $table, $indent = 0)
    {
        $definition =
            $this->getCreateTable($table->name, $indent)
            . $this->getColumns($table->columns, $indent + 1)
            . $this->getTableOptions($table, $indent)
        ;

        return $definition;
    }

public function getTable ( TableSchema $ table , $ indent = 0 ) { $ definition = $ this -> getCreateTable ( $ table -> name , $ indent ) . $ this -> getColumns ( $ table -> columns , $ indent + 1 ) . $ this -> getTableOptions ( $ table , $ indent ) ; return $ definition ; }

get table safeUp definition with primary key
@param TableSchema $table
@param $indent int text-indent 文本缩进
@return string


public function getDropTable(TableSchema $table, $indent = 0)
    {
        // Do not run this sql: "drop table `tableName`", it will drop the table that has exists before running "./yii migrate"

        $textIndent = $this->textIndent($indent);
        $tableName = static::removePrefix($table->name, $this->db->tablePrefix);

        $definition = <<<DEFINITION
{$textIndent}foreach (\$this->runSuccess as \$keyName => \$value) {
{$textIndent}    if ('createTable' === \$keyName) {
{$textIndent}        \$this->dropTable('{{%$tableName}}');
{$textIndent}    } elseif ('addTableComment' === \$keyName) {
{$textIndent}        \$this->dropCommentFromTable('{{%$tableName}}');
{$textIndent}    } else {
{$textIndent}        throw new \yii\db\Exception('only support "dropTable" and "dropCommentFromTable"');
{$textIndent}    }
{$textIndent}}
DEFINITION;

        return $definition;

    }

get table safeDown definition
@param TableSchema $table
@param $indent int text-indent 文本缩进
@return string


public function getDropTableData(TableSchema $table, $indent = 0)
    {
        // Do not use "truncate tableName", it will delete all data of table, include data before you run "./yii migrate" commond

        $definition = $this->textIndent($indent);
        $definition .= "\$this->_transaction->rollBack();";
        $definition .= self::ENTER;

        return $definition;
    }

truncate table data
@param TableSchema $table
@param $indent int text-indent 文本缩进
@return string


public function getKey(TableSchema $table, $indent = 0)
    {
        $definition = '';
        $textIndent = $this->textIndent($indent);
        $tablePrefix = $this->db->tablePrefix;
        $tableName = static::removePrefix($table->name, $tablePrefix);

        $data = $this->db->createCommand('SHOW KEYS FROM ' . $table->name)->queryAll();
        if (empty($data)) {
            return '';
        }

        // 获取索引数据,包括主键
        $keyData = [];
        foreach ($data as $value) {
            $keyName = static::removePrefix($value['Key_name'], $tablePrefix);
            if (empty($keyData[$keyName])) {
                $keyData[$keyName] = [];
            }

            array_push($keyData[$keyName], [
                'table' => $value['Table'],
                'is_unique' => $value['Non_unique'] ? 0 : 1,
                'column_name' => $value['Column_name'],
                'allow_null' => $value['Null'],
                'comment' => $value['Comment'],
                'index_comment' => $value['Index_comment'],
            ]);
        }

        foreach ($keyData as $keyName => $value) {
            $columns = implode(',', array_column($value,'column_name'));
            $definition .= $textIndent;
            $definition .= "\$this->runSuccess['$keyName'] = "; // record which key add successfully

            // primary key
            if ('PRIMARY' === $keyName) {
                $definition .= "\$this->addPrimaryKey(null, '{{%$tableName}}', '$columns');" . self::ENTER;

                foreach ($keyData['PRIMARY'] as $column) {
                    $column = $column['column_name']; // table column name
                    // auto_increment
                    if ($table->columns[$column]->autoIncrement) {
                        $columnType = $table->columns[$column]->type;
                        $property = $table->columns[$column]->unsigned ? 'unsigned' : '';
                        $auto_increment = $this->getAutoIncrementNumber($table->name);
                        $definition .= $textIndent;
                        $definition .= "\$this->runSuccess['addAutoIncrement'] = ";
                        $definition .= "\$this->addAutoIncrement('{{%$tableName}}', '$column', '$columnType', '$property', $auto_increment);" . self::ENTER;
                    }
                }

            } else {
                // other keys except primary key
                $isUnique = $value[0]['is_unique'];
                $definition .= "\$this->createIndex('$keyName', '{{%$tableName}}', '$columns', {$isUnique});" . self::ENTER;
            }

        }

        return $definition;
    }

// 获取索引数据,包括主键

get column key
@param TableSchema $table
@param $indent int text-indent 文本缩进
@return string


public function getDropKey(TableSchema $table, $indent = 0)
    {
        $textIndent = $this->textIndent($indent);
        $tableName = static::removePrefix($table->name, $this->db->tablePrefix);

        $definition = <<<DEFINITION
{$textIndent}foreach (\$this->runSuccess as \$keyName => \$value) {
{$textIndent}    if ('addAutoIncrement' === \$keyName) {
{$textIndent}        continue;
{$textIndent}    } elseif ('PRIMARY' === \$keyName) {
{$textIndent}        // must be remove auto_increment before drop primary key
{$textIndent}        if (isset(\$this->runSuccess['addAutoIncrement'])) {
{$textIndent}            \$value = \$this->runSuccess['addAutoIncrement'];
{$textIndent}            \$this->dropAutoIncrement("{\$value['table_name']}", \$value['column_name'], \$value['column_type'], \$value['property']);
{$textIndent}        }
{$textIndent}        \$this->dropPrimaryKey(null, '{{%{$tableName}}}');
{$textIndent}    } elseif (!empty(\$keyName)) {
{$textIndent}        \$this->dropIndex("`\$keyName`", '{{%{$tableName}}}');
{$textIndent}    }
{$textIndent}}
DEFINITION;

        return $definition . self::ENTER;

    }

drop column key
@param TableSchema $table
@param $indent int text-indent 文本缩进
@return string


public function getFK(TableSchema $table, $indent = 0)
    {
        if (empty($table->foreignKeys)) {
            return '';
        }

        $string = $this->db->createCommand("SHOW CREATE TABLE {$table->name}")->queryAll();
        $onParams = $this->FKOnParams($string[0]['Create Table']);

        $textIndent = $this->textIndent($indent);
        $definition = $textIndent;
        $definition .= '$tablePrefix = \Yii::$app->getDb()->tablePrefix;' . self::ENTER;
        $tableName = static::removePrefix($table->name, $this->db->tablePrefix);

        foreach ($table->foreignKeys as $fkName => $fk) {
            $refTable = '';
            $refColumns = '';
            $columns = '';
            $delete = isset($onParams[$fkName]['ON DELETE']) ? "'{$onParams[$fkName]['ON DELETE']}'" : 'null';
            $update = isset($onParams[$fkName]['ON UPDATE']) ? "'{$onParams[$fkName]['ON UPDATE']}'" : 'null';
            $fkName = static::removePrefix($fkName, $this->db->tablePrefix);

            foreach ($fk as $k => $v) {
                if (0 === $k) {
                    $refTable = $v;
                } else {
                    $columns = $k;
                    $refColumns = $v;
                }
            }

            $definition .= $textIndent;
            $definition .= "\$this->runSuccess[\$tablePrefix.'{$fkName}'] = ";
            $definition .= sprintf(
                    "\$this->addForeignKey(\$tablePrefix.'%s', '{{%%%s}}', '%s', '{{%%%s}}', '%s', %s, %s);" . self::ENTER,
                    $fkName, // 外健名称
                    $tableName, // 表名
                    $columns, // 列名
                    static::removePrefix($refTable, $this->db->tablePrefix), // 对应外健的表名
                    $refColumns, // 对应外健的列名
                    $delete, // ON DELETE
                    $update // ON UPDATE
                );

        }
        return $definition;
    }

add forengin key
@param TableSchema $table
@param $indent int text-indent 文本缩进
@return string


public function getDropFK(TableSchema $table, $indent = 0)
    {
        if (empty($table->foreignKeys)) {
            return '';
        }

        $textIndent = $this->textIndent($indent);
        $tableName = static::removePrefix($table->name, $this->db->tablePrefix);

        $definition = <<<DEFINITION
{$textIndent}foreach (\$this->runSuccess as \$keyName => \$value) {
{$textIndent}    \$this->dropForeignKey(\$keyName, '{{%$tableName}}');
{$textIndent}}
DEFINITION;

        return $definition . self::ENTER;

    }

drop foreign key
@param TableSchema $table
@param $indent int text-indent 文本缩进
@return string


public function getColumns(array $columns, $indent = 0)
    {
        $definition = '';
        $textIndent = $this->textIndent($indent);
        foreach ($columns as $column) {
            $tmp = sprintf("'%s' => \$this->%s%s," . self::ENTER,
                $column->name, static::getSchemaType($column), static::other($column));

            if (null !== $column->enumValues) {
                $tmp = static::replaceEnumColumn($tmp);
            }
            $definition .= $textIndent . $tmp; // 处理缩进问题
        }
        return $definition;
    }

public
function
getColumns
(
array
$
columns
,
$
indent
=
0
)
{
$
definition
=
''
;
$
textIndent
=
$
this
->
textIndent
(
$
indent
)
;
foreach
(
$
columns
as
$
column
)
{
$
tmp
=
sprintf
(
"'%s' => \$this->%s%s,"
.
self
::
ENTER
,
$
column
->
name
,
static
::
getSchemaType
(
$
column
)
,
static
::
other
(
$
column
)
)
;
if
(
!==
$
column
->
enumValues
)
{
$
tmp
=
static
::
replaceEnumColumn
(
$
tmp
)
;
}
$
definition
.=
$
textIndent
.
$
tmp
;
// 处理缩进问题
}
return
$
definition
;
}

Returns the columns definition.
@param $columns array
@param int $indent the number of text indent
@return string


public function getPrimaryKey(array $pk, array $columns, $indent = 0)
    {
        if (empty($pk)) {
            return '';
        }

        // Composite primary keys
        if (2 <= count($pk)) {
            $compositePk = implode(', ', $pk);
            return $this->textIndent($indent) . "'PRIMARY KEY ($compositePk)'," . self::ENTER;
        }
        // Primary key not an auto-increment
        $flag = false;
        foreach ($columns as $column) {
            if ($column->autoIncrement) {
                $flag = true;
            }
        }
        if (false === $flag) {
            return $this->textIndent($indent) . sprintf("'PRIMARY KEY (%s)'," . self::ENTER, $pk[0]);
        }
        return '';
    }

public
function
getPrimaryKey
(
array
$
pk
,
array
$
columns
,
$
indent
=
0
)
{
if
(
empty
(
$
pk
)
)
{
return
''
;
}
// Composite primary keys
if
(
2
<=
count
(
$
pk
)
)
{
$
compositePk
=
implode
(
', '
,
$
pk
)
;
return
$
this
->
textIndent
(
$
indent
)
.
"'PRIMARY KEY ($compositePk)',"
.
self
::
ENTER
;
}
// Primary key not an auto-increment
$
flag
=
false
;
foreach
(
$
columns
as
$
column
)
{
if
(
$
column
->
autoIncrement
)
{
$
flag
=
true
;
}
}
if
(
false
===
$
flag
)
{
return
$
this
->
textIndent
(
$
indent
)
.
sprintf
(
"'PRIMARY KEY (%s)',"
.
self
::
ENTER
,
$
pk
[
0
]
)
;
}
return
''
;
}

Returns the primary key definition.
@param array $pk
@param array $columns
@param int $indent the number of text indent
@return string the primary key definition


public function getTableComment(TableSchema $table, $indent = 0)
    {

        if (null === $this->_tableStatus) {
            try {
                // 不知 “SHOW TABLE STATUS” sql语句在其他数据库中是否会执行成功，所以用try catch捕获异常
                $this->_tableStatus = $this->db->createCommand('SHOW TABLE STATUS')->queryAll();
            } catch (\Exception $e) {
                return '';
            }
        }

        $textIndent = $this->textIndent($indent);
        $definition = $textIndent . '$this->runSuccess[\'addTableComment\'] = ';
        $tableName = static::removePrefix($table->name, $this->db->tablePrefix);

        foreach ($this->_tableStatus as $value) {
            if ($table->name === $value['Name'] && ! empty($value['Comment'])) {
                $comment = addslashes($value['Comment']);
                return $definition . "\$this->addCommentOnTable('{{%$tableName}}', '{$comment}');";
            }
        }

        return '';
    }

get table comment
@param TableSchema $table
@param int $indent the number of text indent
@return string


public static function getSchemaType(ColumnSchema $column)
    {
        // boolean
        if ('tinyint(1)' === $column->dbType) {
            return 'boolean()';
        }

        // enum
        if (null !== $column->enumValues) {
            // https://github.com/yiisoft/yii2/issues/9797
            $enumValues = array_map('addslashes', $column->enumValues);
            return "enum(['".implode('\', \'', $enumValues)."'])";
        }

        switch ($column->type) {
            case 'smallint':
                $type = 'smallInteger';
                break;

            case 'int':
                $type = 'integer';
                break;

            case 'bigint':
                $type = 'bigInteger';
                break;

            default:
                $type = $column->type;
                break;
        }

        // others
        if (null === $column->size) {
            return "$type()";
        } else {
            return "{$type}({$column->size})";
        }

    }

Returns the schema type.
@param ColumnSchema $column
@return string the schema type


public static function other(ColumnSchema $column)
    {
        $definition = '';

        // unsigned
        if ($column->unsigned) {
            $definition .= '->unsigned()';
        }

        // null
        if ($column->allowNull) {
            $definition .= '->null()';
        } else {
            $definition .= '->notNull()';
        }

        // default value
        if ($column->defaultValue instanceof Expression) {
            $definition .= "->defaultExpression('$column->defaultValue')";

        } elseif (is_int($column->defaultValue)) {
            $definition .= "->defaultValue($column->defaultValue)";

        } elseif (is_bool($column->defaultValue)) {
            $definition .= '->defaultValue('.var_export($column->defaultValue, true).')';

        } elseif (is_string($column->defaultValue)) {
            $definition .= "->defaultValue('".addslashes($column->defaultValue)."')";
        }

        // comment
        if (null !== $column->comment && '' !== $column->comment) {
            $definition .= "->comment('".addslashes($column->comment)."')";
        }

        // append

        return $definition;
    }

Returns the other definition.
@param ColumnSchema $column
@return string the other definition


public function actionList()
    {
        $tableList = $this->schema->getTableList($this->db, $this->sparactor) . "\n";
        return $this->output->stdout($tableList, 0, Console::FG_YELLOW);
    }

public function actionList ( ) { $ tableList = $ this -> schema -> getTableList ( $ this -> db , $ this -> sparactor ) . "\n" ; return $ this -> output -> stdout ( $ tableList , 0 , Console :: FG_YELLOW ) ; }

print all over the table name without table prefix

@return int the status of the action execution


public function actionGenerate()
    {
        $this->output->startPrintf('Process');
        $tableOptions = $this->getOptions($this->table);
        $filterOptions = $this->getOptions($this->filter);
        $info = Yii::t('dump', 'Generate Migration File');

        foreach ($this->db->getSchema()->getTableSchemas() as $table) {
            // filter some table  -filter=...  -table=...
            if ($this->filterTable($table->name, $filterOptions, $tableOptions)) {
                continue;
            }

            switch ($this->type) {
                case '0':
                    $this->generateFile($table, 'table', $info, 2);
                    break;

                case '1':
                    $this->generateFile($table, 'tableData', $info, 2);
                    break;

                case '2':
                    $this->generateFile($table, 'key', $info, 2);
                    break;

                case '3':
                    $this->generateFile($table, 'FK', $info, 2);
                    break;

                default:
                    $this->generateFile($table, 'table', $info, 2);
                    $this->generateFile($table, 'tableData', $info, 2);
                    $this->generateFile($table, 'key', $info, 2);
                    $this->generateFile($table, 'FK', $info, 2);
                    break;
            }

        }

        $this->output->conclusion($this->generations, $this->filters);
        $this->output->endPrintf('Process');
        return 0;
    }

generate migration file -type = 0 generate table, 1 generate table data, 2 generate add key, 3 generate add foreign key
@return int the status of the action execution

generate migration file - type = 0 generate table 1 generate table data 2 generate add key 3 generate add foreign key


public function actionCreate()
    {
        $this->output->startPrintf('Process');
        $tableOptions = $this->getOptions($this->table);
        $filterOptions = $this->getOptions($this->filter);

        $createTableInfo = Yii::t('dump', 'Create Table');
        $insertDataInfo = Yii::t('dump', 'Insert Data Of Table');
        $addKeyInfo = Yii::t('dump', 'Add Key Of Table');
        $addFKInfo = Yii::t('dump', 'Add Foreign Key Of Table');

        foreach ($this->db->getSchema()->getTableSchemas() as $table) {
            // filter some table  -filter=...  -table=...
            if ($this->filterTable($table->name, $filterOptions, $tableOptions)) {
                continue;
            }

            switch ($this->type) {
                case '0':
                    $this->printf($table, 'table', $createTableInfo);
                    break;

                case '1':
                    $this->printf($table, 'tableData', $insertDataInfo);
                    break;

                case '2':
                    $this->printf($table, 'key', $addKeyInfo);
                    break;

                case '3':
                    $this->printf($table, 'FK', $addFKInfo); // foreign key
                    break;

                default:
                    $this->printf($table, 'table', $createTableInfo);
                    $this->printf($table, 'tableData', $insertDataInfo);
                    $this->printf($table, 'key', $addKeyInfo);
                    $this->printf($table, 'FK', $addFKInfo); // foreign key
                    break;
            }

        }

        $this->output->conclusion($this->generations, $this->filters);
        $this->output->endPrintf('Process');
        return 0;
    }

print the 'createTable' code.

@return int the status of the action execution


public function actionDrop()
    {
        $this->output->startPrintf('Process');
        $tableOptions = $this->getOptions($this->table);
        $filterOptions = $this->getOptions($this->filter);

        $dropTableInfo = Yii::t('dump', 'Drop Table');
        $dropDataInfo = Yii::t('dump', 'Drop Data Of Table');
        $dropKeyInfo = Yii::t('dump', 'Drop Key Of Table');
        $dropFKInfo = Yii::t('dump', 'Drop Foreign Key Of Table');

        foreach ($this->db->getSchema()->getTableSchemas() as $table) {
            // filter some table  -filter=...  -table=...
            if ($this->filterTable($table->name, $filterOptions, $tableOptions)) {
                continue;
            }

            switch ($this->type) {
                case '0':
                    $this->printf($table, 'dropTable', $dropTableInfo);
                    break;

                case '1':
                    $this->printf($table, 'dropTableData', $dropDataInfo);
                    break;

                case '2':
                    $this->printf($table, 'dropKey', $dropKeyInfo);
                    break;

                case '3':
                    $this->printf($table, 'dropFK', $dropFKInfo); // foreign key
                    break;

                default:
                    $this->printf($table, 'dropTable', $dropTableInfo);
                    $this->printf($table, 'dropTableData', $dropDataInfo);
                    $this->printf($table, 'dropKey', $dropKeyInfo);
                    $this->printf($table, 'dropFK', $dropFKInfo); // foreign key
                    break;
            }

        }

        $this->output->conclusion($this->generations, $this->filters);
        $this->output->endPrintf('Process');
        return 0;
    }

print the 'dropTable' code.

@return integer the status of the action execution


public function generateFile(TableSchema $table, $functionName, $tip = null, $indent = 0)
    {
        $params = $this->getParams($table, $functionName, $indent);

        if (
            empty($params['safeUp'])   ||
            empty($params['safeDown']) ||
            empty($params['className'])
        ) {
            return false;
        }

        $template = Yii::getAlias($this->templateFile);
        $outputFile = Yii::getAlias($this->generateFilePath) . DIRECTORY_SEPARATOR . $params['className'] . '.php';

        if (! empty($tip)) {
            $this->output->startPrintf($tip); // record start time
            $this->output->stdout($outputFile . "\n");
            $rst = $this->output->generateFile($params, $template, $outputFile);
            $this->output->endPrintf($tip); // record end time
        } else {
            $this->output->stdout($outputFile);
            $rst = $this->output->generateFile($params, $template, $outputFile);
        }

        return $rst;
    }

public
function
generateFile
(
TableSchema
$
table
,
$
functionName
,
$
tip
=
,
$
indent
=
0
)
{
$
params
=
$
this
->
getParams
(
$
table
,
$
functionName
,
$
indent
)
;
if
(
empty
(
$
params
[
'safeUp'
]
)
||
empty
(
$
params
[
'safeDown'
]
)
||
empty
(
$
params
[
'className'
]
)
)
{
return
false
;
}
$
template
=
Yii
::
getAlias
(
$
this
->
templateFile
)
;
$
outputFile
=
Yii
::
getAlias
(
$
this
->
generateFilePath
)
.
DIRECTORY_SEPARATOR
.
$
params
[
'className'
]
.
'.php'
;
if
(
!
empty
(
$
tip
)
)
{
$
this
->
output
->
startPrintf
(
$
tip
)
;
// record start time
$
this
->
output
->
stdout
(
$
outputFile
.
"\n"
)
;
$
rst
=
$
this
->
output
->
generateFile
(
$
params
,
$
template
,
$
outputFile
)
;
$
this
->
output
->
endPrintf
(
$
tip
)
;
// record end time
}
else
{
$
this
->
output
->
stdout
(
$
outputFile
)
;
$
rst
=
$
this
->
output
->
generateFile
(
$
params
,
$
template
,
$
outputFile
)
;
}
return
$
rst
;
}

Unified generate file interface
@param TableSchema $table
@param string $functionName abstract function name
@see \hzhihua\dump\abstracts\AbstractSchema abstract function name
@param null $tip
@param int $indent text-indent 文本缩进
@return bool


public function printf(TableSchema $table, $functionName, $tip = null, $indent = 0)
    {
        $params = [];
        $params[] = &$table;
        $params[] = $indent;
        $functionName = ucfirst($functionName);
        $functionName = 'get' . $functionName;

        if ('getTableData' === $functionName) {
            if ($limit = $this->checkLimit($table->name)) {
                array_pop($params);
                $params[] = $limit;
                $params[] = $indent;
            } else {
                return 0;
            }
        }

        if (! $data = call_user_func_array([$this->schema, $functionName], $params)) {
            return 0;
        }

        if (! empty($tip)) {
            $tip .= ': ' . $this->schema->removePrefix($table->name, $this->db->tablePrefix);
            $this->output->startPrintf($tip); // record start time
            $this->output->stdout($data);
            $this->output->endPrintf($tip); // record end time
        } else {
            $this->output->stdout($data);
        }

        return 0;
    }

public
function
printf
(
TableSchema
$
table
,
$
functionName
,
$
tip
=
,
$
indent
=
0
)
{
$
params
=
[
]
;
$
params
[
]
=
&
$
table
;
$
params
[
]
=
$
indent
;
$
functionName
=
ucfirst
(
$
functionName
)
;
$
functionName
=
'get'
.
$
functionName
;
if
(
'getTableData'
===
$
functionName
)
{
if
(
$
limit
=
$
this
->
checkLimit
(
$
table
->
name
)
)
{
array_pop
(
$
params
)
;
$
params
[
]
=
$
limit
;
$
params
[
]
=
$
indent
;
}
else
{
return
0
;
}
}
if
(
!
$
data
=
call_user_func_array
(
[
$
this
->
schema
,
$
functionName
]
,
$
params
)
)
{
return
0
;
}
if
(
!
empty
(
$
tip
)
)
{
$
tip
.=
': '
.
$
this
->
schema
->
removePrefix
(
$
table
->
name
,
$
this
->
db
->
tablePrefix
)
;
$
this
->
output
->
startPrintf
(
$
tip
)
;
// record start time
$
this
->
output
->
stdout
(
$
data
)
;
$
this
->
output
->
endPrintf
(
$
tip
)
;
// record end time
}
else
{
$
this
->
output
->
stdout
(
$
data
)
;
}
return
0
;
}

Unified printf interface
@param TableSchema $table
@param $functionName string $functionName abstract function name
@see \hzhihua\dump\abstracts\AbstractSchema abstract function name
@param null $tip
@param int $indent text-indent 文本缩进
@return bool|int


public function getParams(TableSchema $table, $functionName, $indent = 0)
    {
        $params = [];
        $params[] = &$table;
        $params[] = $indent;
        $ucFunctionName = ucfirst($functionName);
        $get = 'get' . $ucFunctionName;
        $drop = 'getDrop' . $ucFunctionName;

        $order = $this->changeOrderOfApplyingFile($functionName);

        if ('getTableData' === $get) {
            if ($limit = $this->checkLimit($table->name)) {
                array_pop($params);
                $params[] = $limit;
                $params[] = $indent;
            } else {
                return [];
            }
        }

        $safeUp = call_user_func_array([$this->schema, $get], $params);
        if (3 === count($params)) {
            unset($params[1]); // unser $this->limit
        }
        $safeDown = call_user_func_array([$this->schema, $drop], $params);
        $tableName = $this->schema->removePrefix($table->name, $this->db->tablePrefix);

        return [
            'safeUp' => $safeUp ? "\n" . $safeUp . "\n" : '',
            'safeDown' => $safeDown ? "\n" . $safeDown . "\n" : '',
            'className' => static::getClassName($order . '_' . $functionName . '_' . $tableName, $this->filePrefix),
        ];

    }

public
function
getParams
(
TableSchema
$
table
,
$
functionName
,
$
indent
=
0
)
{
$
params
=
[
]
;
$
params
[
]
=
&
$
table
;
$
params
[
]
=
$
indent
;
$
ucFunctionName
=
ucfirst
(
$
functionName
)
;
$
get
=
'get'
.
$
ucFunctionName
;
$
drop
=
'getDrop'
.
$
ucFunctionName
;
$
order
=
$
this
->
changeOrderOfApplyingFile
(
$
functionName
)
;
if
(
'getTableData'
===
$
get
)
{
if
(
$
limit
=
$
this
->
checkLimit
(
$
table
->
name
)
)
{
array_pop
(
$
params
)
;
$
params
[
]
=
$
limit
;
$
params
[
]
=
$
indent
;
}
else
{
return
[
]
;
}
}
$
safeUp
=
call_user_func_array
(
[
$
this
->
schema
,
$
get
]
,
$
params
)
;
if
(
3
===
count
(
$
params
)
)
{
unset
(
$
params
[
1
]
)
;
// unser $this->limit
}
$
safeDown
=
call_user_func_array
(
[
$
this
->
schema
,
$
drop
]
,
$
params
)
;
$
tableName
=
$
this
->
schema
->
removePrefix
(
$
table
->
name
,
$
this
->
db
->
tablePrefix
)
;
return
[
'safeUp'
=>
$
safeUp
"\n"
.
$
safeUp
.
"\n"
:
''
,
'safeDown'
=>
$
safeDown
"\n"
.
$
safeDown
.
"\n"
:
''
,
'className'
=>
static
::
getClassName
(
$
order
.
'_'
.
$
functionName
.
'_'
.
$
tableName
,
$
this
->
filePrefix
)
,
]
;
}

Get relevant data with array style for generating file function
@param TableSchema $table
@param string $functionName abstract function name
@see \hzhihua\dump\abstracts\AbstractSchema abstract function name
@param int $indent text-indent 文本缩进
@return array


public function startPrintf($string)
    {
        if (empty($string)) {
            return '';
        }

        $this->startTime[$string] = microtime(true);

        $this->stdout('/*** Begin '. $string . " ***/" . self::ENTER, 0, Console::FG_YELLOW);

        return 0;
    }

public
function
startPrintf
(
$
string
)
{
if
(
empty
(
$
string
)
)
{
return
''
;
}
$
this
->
startTime
[
$
string
]
=
microtime
(
true
)
;
$
this
->
stdout
(
'/*** Begin '
.
$
string
.
" ***/"
.
self
::
ENTER
,
0
,
Console
::
FG_YELLOW
)
;
return
0
;
}

printf some thing at the terminal and record start time
@param string $string
@return int exit code


public function endPrintf($string)
    {
        if (empty($string)) {
            return '';
        }
        $this->endTime[$string] = microtime(true);
        $time = $this->endTime[$string] - $this->startTime[$string];

        $this->stdout(
            '/*** End ' . $string . ' ... done (time: ' . sprintf("%.3f", $time) . "s) ***/" . self::ENTER . self::ENTER,
                0,
                Console::FG_GREEN
            );

        return 0;
    }

public
function
endPrintf
(
$
string
)
{
if
(
empty
(
$
string
)
)
{
return
''
;
}
$
this
->
endTime
[
$
string
]
=
microtime
(
true
)
;
$
time
=
$
this
->
endTime
[
$
string
]
$
this
->
startTime
[
$
string
]
;
$
this
->
stdout
(
'/*** End '
.
$
string
.
' ... done (time: '
.
sprintf
(
"%.3f"
,
$
time
)
.
"s) ***/"
.
self
::
ENTER
.
self
::
ENTER
,
0
,
Console
::
FG_GREEN
)
;
return
0
;
}

printf some thing at the terminal and record end time
@param string $string
@return int exit code


public function conclusion($handleTable, $filterTable)
    {
        $enter = self::ENTER;
        $handleNumber = count($handleTable);
        $filterNumber = count($filterTable);
        $handleTableString = implode($handleTable, ', ');
        $filterTableString = implode($filterTable, ', ');
        $tables = Yii::t('dump', 'Tables');
        $handle = Yii::t('dump', 'Handle');
        $filter = Yii::t('dump', 'Filter');

        $header = <<<HEADER
/**********************************/
/************ Conclusion **********/
/**********************************/

HEADER;

        $footer = <<<FOOTER

/************ Conclusion *********/$enter
FOOTER;

        $handle = <<<HANDLE
/*** $handle $handleNumber $tables: */
>>> $handleTableString$enter
HANDLE;

        $filter = <<<FILTER
/*** $filter $filterNumber $tables: */
>>> $filterTableString
FILTER;

        $this->stdout($header, 0, Console::FG_YELLOW);
        $this->stdout($handle, Console::BOLD, Console::FG_YELLOW);
        $this->stdout($filter, Console::BOLD, Console::FG_YELLOW);
        $this->stdout($footer, 0, Console::FG_GREEN);
    }

print conclusion at the terminal
@param $handleTable array all table name that had been generate
@param $filterTable array all table name that had been filter


private function _Fetch() {
		$this->_setWebservicesUrl();

		$response = @file_get_contents($this->getWebservicesUrl());
		$this->response = $response;
	}

private function _Fetch ( ) { $ this -> _setWebservicesUrl ( ) ; $ response = @ file_get_contents ( $ this -> getWebservicesUrl ( ) ) ; $ this -> response = $ response ; }

Fetch content from URL

@param string $query_string
Webservices URL


private function _Populate() {
		$this->data = json_decode($this->response);

		// getStatus() FALSE upon receiving status ERR or a non-zero error
		// else set as TRUE
		if (is_array($this->data->data)) {
			$this->status = TRUE;
		} else {
			if (isset($this->data->status) && isset($this->data->error)) {
				if (($this->data->status == 'ERR') || ((int) $this->data->error > 0)) {
					$this->status = FALSE;
				} else {
					$this->status = TRUE;
				}
			} else {
				$this->status = FALSE;
			}
		}

		if (isset($this->data->error)) {
			$this->error = ((int) $this->data->error > 0 ? (int) $this->data->error : 0);
		} else {
			$this->error = 0;
		}

		if (isset($this->data->error_string)) {
			$this->error_string = $this->data->error_string;
		} else {
			$this->error_string = '';
		}
	}


private function _setWebservicesUrl() {
		$ws_url = $this->url . '&format=json';

		if ($this->token) {
			$ws_url .= '&h=' . $this->token;
		}

		if ($this->username) {
			$ws_url .= '&u=' . $this->username;
		}

		if ($this->password) {
			$ws_url .= '&p=' . $this->password;
		}

		if ($this->operation) {
			$ws_url .= '&op=' . $this->operation;
		}

		if ($this->from) {
			$ws_url .= '&from=' . urlencode($this->from);
		}

		if ($this->to) {
			$ws_url .= '&to=' . urlencode($this->to);
		}

		if ($this->footer) {
			$ws_url .= '&footer=' . urlencode($this->footer);
		}

		if ($this->nofooter) {
			$ws_url .= '&nofooter=' . $this->nofooter;
		}

		if ($this->msg) {
			$ws_url .= '&msg=' . urlencode($this->msg);
		}

		if ($this->schedule) {
			$ws_url .= '&schedule=' . $this->schedule;
		}

		if ($this->type) {
			$ws_url .= '&type=' . $this->type;
		}

		if ($this->unicode) {
			$ws_url .= '&unicode=' . $this->unicode;
		}

		if ($this->queue) {
			$ws_url .= '&queue=' . $this->queue;
		}

		if ($this->src) {
			$ws_url .= '&src=' . urlencode($this->src);
		}

		if ($this->dst) {
			$ws_url .= '&dst=' . urlencode($this->dst);
		}

		if ($this->datetime) {
			$ws_url .= '&dt=' . $this->datetime;
		}

		if ($this->smslog_id) {
			$ws_url .= '&smslog_id=' . $this->smslog_id;
		}

		if ($this->last_smslog_id) {
			$ws_url .= '&last=' . $this->last_smslog_id;
		}

		if ($this->count) {
			$ws_url .= '&c=' . $this->count;
		}

		if ($this->keyword) {
			$ws_url .= '&kwd=' . urlencode($this->keyword);
		}

		$this->webservices_url = $ws_url;
	}

private function _setWebservicesUrl ( ) { $ ws_url = $ this -> url . '&format=json' ; if ( $ this -> token ) { $ ws_url .= '&h=' . $ this -> token ; } if ( $ this -> username ) { $ ws_url .= '&u=' . $ this -> username ; } if ( $ this -> password ) { $ ws_url .= '&p=' . $ this -> password ; } if ( $ this -> operation ) { $ ws_url .= '&op=' . $ this -> operation ; } if ( $ this -> from ) { $ ws_url .= '&from=' . urlencode ( $ this -> from ) ; } if ( $ this -> to ) { $ ws_url .= '&to=' . urlencode ( $ this -> to ) ; } if ( $ this -> footer ) { $ ws_url .= '&footer=' . urlencode ( $ this -> footer ) ; } if ( $ this -> nofooter ) { $ ws_url .= '&nofooter=' . $ this -> nofooter ; } if ( $ this -> msg ) { $ ws_url .= '&msg=' . urlencode ( $ this -> msg ) ; } if ( $ this -> schedule ) { $ ws_url .= '&schedule=' . $ this -> schedule ; } if ( $ this -> type ) { $ ws_url .= '&type=' . $ this -> type ; } if ( $ this -> unicode ) { $ ws_url .= '&unicode=' . $ this -> unicode ; } if ( $ this -> queue ) { $ ws_url .= '&queue=' . $ this -> queue ; } if ( $ this -> src ) { $ ws_url .= '&src=' . urlencode ( $ this -> src ) ; } if ( $ this -> dst ) { $ ws_url .= '&dst=' . urlencode ( $ this -> dst ) ; } if ( $ this -> datetime ) { $ ws_url .= '&dt=' . $ this -> datetime ; } if ( $ this -> smslog_id ) { $ ws_url .= '&smslog_id=' . $ this -> smslog_id ; } if ( $ this -> last_smslog_id ) { $ ws_url .= '&last=' . $ this -> last_smslog_id ; } if ( $ this -> count ) { $ ws_url .= '&c=' . $ this -> count ; } if ( $ this -> keyword ) { $ ws_url .= '&kwd=' . urlencode ( $ this -> keyword ) ; } $ this -> webservices_url = $ ws_url ; }