public static function loadUserCell($mUser)
    {
        if (is_numeric($mUser)) {

            $oUserModel = Factory::model('User', 'nails/module-auth');
            $oUser      = $oUserModel->getById($mUser);

        } elseif (is_string($mUser)) {

            $oUserModel = Factory::model('User', 'nails/module-auth');
            $oUser      = $oUserModel->getByEmail($mUser);

            if (empty($oUser)) {
                $oUser = $oUserModel->getByUsername($mUser);
            }

        } else {
            $oUser = $mUser;
        }

        $aUser = [
            'id'          => !empty($oUser->id) ? $oUser->id : null,
            'profile_img' => !empty($oUser->profile_img) ? $oUser->profile_img : null,
            'gender'      => !empty($oUser->gender) ? $oUser->gender : null,
            'first_name'  => !empty($oUser->first_name) ? $oUser->first_name : null,
            'last_name'   => !empty($oUser->last_name) ? $oUser->last_name : null,
            'email'       => !empty($oUser->email) ? $oUser->email : null,
        ];

        $oView = Factory::service('View');
        return $oView->load('admin/_components/table-cell-user', $aUser, true);
    }

public static function loadUserCell ( $ mUser ) { if ( is_numeric ( $ mUser ) ) { $ oUserModel = Factory :: model ( 'User' , 'nails/module-auth' ) ; $ oUser = $ oUserModel -> getById ( $ mUser ) ; } elseif ( is_string ( $ mUser ) ) { $ oUserModel = Factory :: model ( 'User' , 'nails/module-auth' ) ; $ oUser = $ oUserModel -> getByEmail ( $ mUser ) ; if ( empty ( $ oUser ) ) { $ oUser = $ oUserModel -> getByUsername ( $ mUser ) ; } } else { $ oUser = $ mUser ; } $ aUser = [ 'id' => ! empty ( $ oUser -> id ) ? $ oUser -> id : null , 'profile_img' => ! empty ( $ oUser -> profile_img ) ? $ oUser -> profile_img : null , 'gender' => ! empty ( $ oUser -> gender ) ? $ oUser -> gender : null , 'first_name' => ! empty ( $ oUser -> first_name ) ? $ oUser -> first_name : null , 'last_name' => ! empty ( $ oUser -> last_name ) ? $ oUser -> last_name : null , 'email' => ! empty ( $ oUser -> email ) ? $ oUser -> email : null , ] ; $ oView = Factory :: service ( 'View' ) ; return $ oView -> load ( 'admin/_components/table-cell-user' , $ aUser , true ) ; }

Load the admin "user" table cell component

@param  mixed $mUser The user object or the User's ID/email/username

@return string
@throws \Nails\Common\Exception\FactoryException

Load the admin user table cell component


public static function loadDateCell($sDate, $sNoData = '—')
    {
        $aData = [
            'date'   => $sDate,
            'noData' => $sNoData,
        ];

        $oView = Factory::service('View');
        return $oView->load('admin/_components/table-cell-date', $aData, true);
    }

public static function loadDateCell ( $ sDate , $ sNoData = '—' ) { $ aData = [ 'date' => $ sDate , 'noData' => $ sNoData , ] ; $ oView = Factory :: service ( 'View' ) ; return $ oView -> load ( 'admin/_components/table-cell-date' , $ aData , true ) ; }

Load the admin "date" table cell component

@param  string $sDate   The date to render
@param  string $sNoData What to render if the date is invalid or empty

@return string
@throws \Nails\Common\Exception\FactoryException

Load the admin date table cell component


public static function loadDateTimeCell($sDateTime, $sNoData = '—')
    {
        $aData = [
            'dateTime' => $sDateTime,
            'noData'   => $sNoData,
        ];

        $oView = Factory::service('View');
        return $oView->load('admin/_components/table-cell-datetime', $aData, true);
    }

public static function loadDateTimeCell ( $ sDateTime , $ sNoData = '—' ) { $ aData = [ 'dateTime' => $ sDateTime , 'noData' => $ sNoData , ] ; $ oView = Factory :: service ( 'View' ) ; return $ oView -> load ( 'admin/_components/table-cell-datetime' , $ aData , true ) ; }

Load the admin "dateTime" table cell component

@param  string $sDateTime The dateTime to render
@param  string $sNoData   What to render if the datetime is invalid or empty

@return string
@throws \Nails\Common\Exception\FactoryException

Load the admin dateTime table cell component


public static function loadBoolCell($value, $sDateTime = null)
    {
        $aData = [
            'value'    => $value,
            'dateTime' => $sDateTime,
        ];

        $oView = Factory::service('View');
        return $oView->load('admin/_components/table-cell-boolean', $aData, true);
    }

public static function loadBoolCell ( $ value , $ sDateTime = null ) { $ aData = [ 'value' => $ value , 'dateTime' => $ sDateTime , ] ; $ oView = Factory :: service ( 'View' ) ; return $ oView -> load ( 'admin/_components/table-cell-boolean' , $ aData , true ) ; }

Load the admin "boolean" table cell component

@param  string $value     The value to 'truthy' test
@param  string $sDateTime A datetime to show (for truthy values only)

@return string
@throws \Nails\Common\Exception\FactoryException

Load the admin boolean table cell component


public static function loadSettingsComponentTable($sComponentService, $sProvider, $sComponentType = 'component')
    {
        $oModel          = Factory::service($sComponentService, $sProvider);
        $sKey            = $oModel->getSettingKey();
        $aComponents     = $oModel->getAll();
        $aEnabled        = (array) $oModel->getEnabledSlug();
        $bEnableMultiple = $oModel->isMultiple();

        $aData = [
            'key'               => $sKey,
            'components'        => $aComponents,
            'enabled'           => $aEnabled,
            'canSelectMultiple' => $bEnableMultiple,
            'componentType'     => $sComponentType,
        ];

        $oView = Factory::service('View');
        return $oView->load('admin/_components/settings-component-table', $aData, true);
    }

Load the admin "settings component table" component

@param  string $sComponentService The component service to use
@param  array  $sProvider         The model provider
@param  string $sComponentType    The type of component being loaded

@return string
@throws \Nails\Common\Exception\FactoryException

Load the admin settings component table component


public static function addHeaderButton(
        $sUrl,
        $sLabel,
        $sContext = null,
        $sConfirmTitle = null,
        $sConfirmBody = null
    ) {
        $sContext = empty($sContext) ? 'primary' : $sContext;

        self::$aHeaderButtons[] = [
            'url'          => $sUrl,
            'label'        => $sLabel,
            'context'      => $sContext,
            'confirmTitle' => $sConfirmTitle,
            'confirmBody'  => $sConfirmBody,
        ];
    }

public static function addHeaderButton ( $ sUrl , $ sLabel , $ sContext = null , $ sConfirmTitle = null , $ sConfirmBody = null ) { $ sContext = empty ( $ sContext ) ? 'primary' : $ sContext ; self :: $ aHeaderButtons [ ] = [ 'url' => $ sUrl , 'label' => $ sLabel , 'context' => $ sContext , 'confirmTitle' => $ sConfirmTitle , 'confirmBody' => $ sConfirmBody , ] ; }

Adds a button to Admin's header area

@param string $sUrl          The button's URL
@param string $sLabel        The button's label
@param string $sContext      The button's context
@param string $sConfirmTitle If a confirmation is required, the title to use
@param string $sConfirmBody  If a confirmation is required, the body to use


public static function dynamicTable($sKey, array $aFields, array $aData = [])
    {
        return Factory::service('View')
            ->load(
                'admin/_components/dynamic-table',
                [
                    'sKey'    => $sKey,
                    'aFields' => $aFields,
                    'aData'   => $aData,
                ],
                true
            );
    }

public static function dynamicTable ( $ sKey , array $ aFields , array $ aData = [ ] ) { return Factory :: service ( 'View' ) -> load ( 'admin/_components/dynamic-table' , [ 'sKey' => $ sKey , 'aFields' => $ aFields , 'aData' => $ aData , ] , true ) ; }

Generates a dynamic table

@param string $sKey    The key to give items in the table
@param array  $aFields The fields to render
@param array  $aData   Data to populate the table with

@return string
@throws \Nails\Common\Exception\FactoryException


public function postSave()
    {
        $oInput   = Factory::service('Input');
        $aPrefRaw = array_filter((array) $oInput->post('preferences'));
        $oPref    = new \stdClass();

        foreach ($aPrefRaw as $sModule => $aOptions) {
            $oPref->{$sModule}       = new \stdClass();
            $oPref->{$sModule}->open = stringToBoolean($aOptions['open']);
        }

        $oAdminModel = Factory::model('Admin', 'nails/module-admin');
        $oAdminModel->setAdminData('nav_state', $oPref);
        return Factory::factory('ApiResponse', 'nails/module-api');
    }

public function postSave ( ) { $ oInput = Factory :: service ( 'Input' ) ; $ aPrefRaw = array_filter ( ( array ) $ oInput -> post ( 'preferences' ) ) ; $ oPref = new \ stdClass ( ) ; foreach ( $ aPrefRaw as $ sModule => $ aOptions ) { $ oPref -> { $ sModule } = new \ stdClass ( ) ; $ oPref -> { $ sModule } -> open = stringToBoolean ( $ aOptions [ 'open' ] ) ; } $ oAdminModel = Factory :: model ( 'Admin' , 'nails/module-admin' ) ; $ oAdminModel -> setAdminData ( 'nav_state' , $ oPref ) ; return Factory :: factory ( 'ApiResponse' , 'nails/module-api' ) ; }

Saves the user's admin nav preferences
@return \Nails\Api\Factory\ApiResponse


protected function execute(InputInterface $oInput, OutputInterface $oOutput): int
    {
        parent::execute($oInput, $oOutput);

        // --------------------------------------------------------------------------

        try {
            //  Ensure the paths exist
            $this->createPath(self::EXPORT_PATH);
            //  Create the DataExport source
            $this->createSource();
        } catch (\Exception $e) {
            return $this->abort(
                self::EXIT_CODE_FAILURE,
                [$e->getMessage()]
            );
        }

        // --------------------------------------------------------------------------

        //  Cleaning up
        $oOutput->writeln('');
        $oOutput->writeln('<comment>Cleaning up...</comment>');

        // --------------------------------------------------------------------------

        //  And we're done
        $oOutput->writeln('');
        $oOutput->writeln('Complete!');

        return self::EXIT_CODE_SUCCESS;
    }

Executes the app

@param InputInterface  $oInput  The Input Interface provided by Symfony
@param OutputInterface $oOutput The Output Interface provided by Symfony

@return int


private function createSource(): void
    {
        $aFields               = $this->getArguments();
        $aFields['CLASS_NAME'] = str_replace(' ', '', ucwords(preg_replace('/[^a-zA-Z ]/', '', $aFields['NAME'])));
        $aFields['FILENAME']   = strtolower(url_title($aFields['NAME']));

        try {

            $this->oOutput->write('Creating DataExport Source <comment>' . $aFields['CLASS_NAME'] . '</comment>... ');

            //  Check for existing DataExport source
            $sPath = static::EXPORT_PATH . $aFields['CLASS_NAME'] . '.php';
            if (file_exists($sPath)) {
                throw new ControllerExistsException(
                    'DataExport Source "' . $aFields['CLASS_NAME'] . '" exists already at path "' . $sPath . '"'
                );
            }

            $this->createFile($sPath, $this->getResource('template/data_export_source.php', $aFields));
            $aCreated[] = $sPath;
            $this->oOutput->writeln('<info>done!</info>');

        } catch (\Exception $e) {
            $this->oOutput->writeln('<error>failed!</error>');
            throw new NailsException($e->getMessage());
        }
    }

//  Check for existing DataExport source

Create the Model

@return void
@throws \Exception


protected function formatRow($oRow)
    {
        $aItems = array_map(
            function ($sItem) {
                return str_replace('"', '""', trim($sItem));
            },
            (array) $oRow
        );

        return '"' . implode('","', $aItems) . '"' . "\n";
    }

protected function formatRow ( $ oRow ) { $ aItems = array_map ( function ( $ sItem ) { return str_replace ( '"' , '""' , trim ( $ sItem ) ) ; } , ( array ) $ oRow ) ; return '"' . implode ( '","' , $ aItems ) . '"' . "\n" ; }

Escapes items to be written to the CSV

@param \stdClass|array $oRow The row to format

@return string


public function addAction($label, $url = 'index', $alerts = [], $order = null)
    {
        $this->actions[$url]         = new \stdClass();
        $this->actions[$url]->label  = $label;
        $this->actions[$url]->alerts = !is_array($alerts) ? [$alerts] : $alerts;

        if (is_null($order)) {
            $this->actions[$url]->order = count($this->actions);
        } else {
            $this->actions[$url]->order = $order;
        }

        return $this;
    }

public function addAction ( $ label , $ url = 'index' , $ alerts = [ ] , $ order = null ) { $ this -> actions [ $ url ] = new \ stdClass ( ) ; $ this -> actions [ $ url ] -> label = $ label ; $ this -> actions [ $ url ] -> alerts = ! is_array ( $ alerts ) ? [ $ alerts ] : $ alerts ; if ( is_null ( $ order ) ) { $ this -> actions [ $ url ] -> order = count ( $ this -> actions ) ; } else { $ this -> actions [ $ url ] -> order = $ order ; } return $ this ; }

Adds a new action to the navGroup. An action is menu item essentially.

@param string $label  The label to give the action
@param string $url    The url this action applies to
@param array  $alerts An array of alerts to have along side this action
@param mixed  $order  An optional order index, used to push menu items up and down the group

@return Nav      $this, for chaining

Adds a new action to the navGroup . An action is menu item essentially .


public function setAdminData($key, $value, $userId = null)
    {
        return $this->setUnsetAdminData($key, $value, $userId, true);
    }

public function setAdminData ( $ key , $ value , $ userId = null ) { return $ this -> setUnsetAdminData ( $ key , $ value , $ userId , true ) ; }

Sets a piece of admin data

@param  string $key    The key to set
@param  mixed  $value  The value to set
@param  mixed  $userId The user's ID, if null active user is used.

@return boolean


public function unsetAdminData($key, $userId = null)
    {
        return $this->setUnsetAdminData($key, null, $userId, false);
    }

public function unsetAdminData ( $ key , $ userId = null ) { return $ this -> setUnsetAdminData ( $ key , null , $ userId , false ) ; }

Unsets a piece of admin data

@param  string $key    The key to set
@param  mixed  $userId The user's ID, if null active user is used.

@return boolean


protected function setUnsetAdminData($key, $value, $userId, $set)
    {
        //  Get the user ID
        $userId = $this->adminDataGetUserId($userId);

        //  Get the existing data for this user
        $existing = $this->getAdminData(null, $userId);

        if ($set) {

            //  Set the new key
            if (in_array($key, $this->aJsonFields)) {
                $value = json_encode($value);
            }
            $existing[$key] = $value;

        } else {

            //  Unset the existing key
            $existing[$key] = null;
        }

        //  Save to the DB
        $bResult = $this->oUserMetaService->update(
            NAILS_DB_PREFIX . 'user_meta_admin',
            $userId,
            $existing
        );
    }

protected
function
setUnsetAdminData
(
$
key
,
$
value
,
$
userId
,
$
set
)
{
//  Get the user ID
$
userId
=
$
this
->
adminDataGetUserId
(
$
userId
)
;
//  Get the existing data for this user
$
existing
=
$
this
->
getAdminData
(
,
$
userId
)
;
if
(
$
set
)
{
//  Set the new key
if
(
in_array
(
$
key
,
$
this
->
aJsonFields
)
)
{
$
value
=
json_encode
(
$
value
)
;
}
$
existing
[
$
key
]
=
$
value
;
}
else
{
//  Unset the existing key
$
existing
[
$
key
]
=
;
}
//  Save to the DB
$
bResult
=
$
this
->
oUserMetaService
->
update
(
NAILS_DB_PREFIX
.
'user_meta_admin'
,
$
userId
,
$
existing
)
;
}

Handles the setting and unsetting of admin data

@param  string  $key    The key to set
@param  mixed   $value  The value to set
@param  mixed   $userId The user's ID, if null active user is used.
@param  boolean $set    Whether the data is being set or unset

@return boolean


public function clearAdminData($userId)
    {
        //  Get the user ID
        $userId = $this->adminDataGetUserId($userId);

        $bResult = $this->oUserMetaService->update(
            NAILS_DB_PREFIX . 'user_meta_admin',
            $userId,
            [
                'nav_state' => null,
            ]
        );

        if ($bResult) {
            $this->unsetCache('admin-data-' . $userId);
        }

        return $bResult;
    }

public
function
clearAdminData
(
$
userId
)
{
//  Get the user ID
$
userId
=
$
this
->
adminDataGetUserId
(
$
userId
)
;
$
bResult
=
$
this
->
oUserMetaService
->
update
(
NAILS_DB_PREFIX
.
'user_meta_admin'
,
$
userId
,
[
'nav_state'
=>
,
]
)
;
if
(
$
bResult
)
{
$
this
->
unsetCache
(
'admin-data-'
.
$
userId
)
;
}
return
$
bResult
;
}

Completely clears out the admin array

@param  mixed $userId The user's ID, if null active user is used.

@return boolean


public function getAll($iPage = null, $iPerPage = null, array $aData = [], $bIncludeDeleted = false): array
    {
        $dirMap        = directory_map($this->logPath, 0);
        $logFiles      = [];
        $filenameRegex = '/^log\-(\d{4}\-\d{2}\-\d{2})\.php$/';

        foreach ($dirMap as $logFile) {

            if (preg_match($filenameRegex, $logFile)) {

                $logFiles[] = $logFile;
            }
        }

        arsort($logFiles);
        $logFiles = array_values($logFiles);

        $out = [];

        foreach ($logFiles as $file) {

            $temp        = new \stdClass();
            $temp->date  = preg_replace($filenameRegex, '$1', $file);
            $temp->file  = $file;
            $temp->lines = $this->countLines($this->logPath . $file);

            $out[] = $temp;
        }

        return $out;
    }

public function getAll ( $ iPage = null , $ iPerPage = null , array $ aData = [ ] , $ bIncludeDeleted = false ) : array { $ dirMap = directory_map ( $ this -> logPath , 0 ) ; $ logFiles = [ ] ; $ filenameRegex = '/^log\-(\d{4}\-\d{2}\-\d{2})\.php$/' ; foreach ( $ dirMap as $ logFile ) { if ( preg_match ( $ filenameRegex , $ logFile ) ) { $ logFiles [ ] = $ logFile ; } } arsort ( $ logFiles ) ; $ logFiles = array_values ( $ logFiles ) ; $ out = [ ] ; foreach ( $ logFiles as $ file ) { $ temp = new \ stdClass ( ) ; $ temp -> date = preg_replace ( $ filenameRegex , '$1' , $ file ) ; $ temp -> file = $ file ; $ temp -> lines = $ this -> countLines ( $ this -> logPath . $ file ) ; $ out [ ] = $ temp ; } return $ out ; }


protected function findConfig($sFile)
    {
        //  @todo (Pablo - 2018-07-13) - The paths and URLs should probably be determined by the Asset service
        if (file_exists(NAILS_APP_PATH . 'assets/build/js/' . $sFile)) {
            return site_url('assets/build/js/' . $sFile);
        } elseif (file_exists(NAILS_APP_PATH . 'assets/js/' . $sFile)) {
            return site_url('assets/js/' . $sFile);
        } else {
            return NAILS_ASSETS_URL . 'js/' . $sFile;
        }
    }

Looks for an app version of the file

@param string $sFile The file name to search for

@return string


protected function loadJs()
    {
        \Nails\Common\Controller\Base::setNailsJs();

        $oAsset = Factory::service('Asset');

        //  Module assets
        $oAsset->load('admin.min.js', 'nails/module-admin');
        $oAsset->load('nails.default.min.js', 'NAILS');
        $oAsset->load('nails.admin.js', 'NAILS');
        $oAsset->load('nails.forms.min.js', 'NAILS');
        $oAsset->load('nails.api.min.js', 'NAILS');

        //  Component assets
        foreach (Components::available() as $oComponent) {

            if (!empty($oComponent->data->{'nails/module-admin'}->autoload)) {

                $oAutoLoad = $oComponent->data->{'nails/module-admin'}->autoload;
                if (!empty($oAutoLoad->assets->js)) {
                    foreach ($oAutoLoad->assets->js as $mAsset) {

                        if (is_string($mAsset)) {
                            $sAsset    = $mAsset;
                            $sLocation = $oComponent->slug;
                        } else {
                            $sAsset    = !empty($mAsset[0]) ? $mAsset[0] : null;
                            $sLocation = !empty($mAsset[1]) ? $mAsset[1] : null;
                        }

                        $oAsset->load($sAsset, $sLocation, 'JS');
                    }
                }

                //  JS Inline
                if (!empty($oAutoLoad->assets->jsInline)) {
                    foreach ($oAutoLoad->assets->jsInline as $sAsset) {
                        $oAsset->inline($sAsset, 'JS');
                    }
                }
            }
        }

        //  Global JS
        $sAdminJsPath = defined('APP_ADMIN_JS_PATH') ? APP_ADMIN_JS_PATH : NAILS_APP_PATH . 'assets/build/js/admin.min.js';
        $sAdminJsUrl  = defined('APP_ADMIN_JS_URL') ? APP_ADMIN_JS_URL : 'admin.min.js';
        if (file_exists($sAdminJsPath)) {
            $oAsset->load($sAdminJsUrl);
        }

        //  Inline assets
        $sJs = 'var _nails,_nails_admin,_nails_api, _nails_forms;';

        $sJs .= 'if (typeof(NAILS_JS) === \'function\'){';
        $sJs .= '_nails = new NAILS_JS();';
        $sJs .= '}';

        $sJs .= 'if (typeof(NAILS_API) === \'function\'){';
        $sJs .= '_nails_api = new NAILS_API();';
        $sJs .= '}';

        $sJs .= 'if (typeof(NAILS_Admin) === \'function\'){';
        $sJs .= '_nails_admin = new NAILS_Admin();';
        $sJs .= '}';

        $sJs .= 'if (typeof(NAILS_Forms) === \'function\'){';
        $sJs .= '_nails_forms = new NAILS_Forms();';
        $sJs .= '}';

        $oAsset->inline($sJs, 'JS');
    }

Load all Admin orientated JS

@throws \Nails\Common\Exception\FactoryException


protected function loadCss()
    {
        $oAsset = Factory::service('Asset');

        //  Module assets
        $oAsset->load('nails.admin.css', 'NAILS');
        $oAsset->load('admin.css', 'nails/module-admin');

        //  Component assets
        foreach (Components::available() as $oComponent) {
            if (!empty($oComponent->data->{'nails/module-admin'}->autoload)) {

                $oAutoLoad = $oComponent->data->{'nails/module-admin'}->autoload;

                if (!empty($oAutoLoad->assets->css)) {
                    foreach ($oAutoLoad->assets->css as $mAsset) {

                        if (is_string($mAsset)) {
                            $sAsset    = $mAsset;
                            $sLocation = $oComponent->slug;
                        } else {
                            $sAsset    = !empty($mAsset[0]) ? $mAsset[0] : null;
                            $sLocation = !empty($mAsset[1]) ? $mAsset[1] : null;
                        }

                        $oAsset->load($sAsset, $sLocation, 'CSS');
                    }
                }

                //  CSS Inline
                if (!empty($oAutoLoad->assets->cssInline)) {
                    foreach ($oAutoLoad->assets->cssInline as $sAsset) {
                        $oAsset->inline($sAsset, 'CSS');
                    }
                }
            }
        }

        //  Global CSS
        $sAdminCssPath = defined('APP_ADMIN_CSS_PATH') ? APP_ADMIN_CSS_PATH : NAILS_APP_PATH . 'assets/build/css/admin.min.css';
        $sAdminCssUrl  = defined('APP_ADMIN_CSS_URL') ? APP_ADMIN_CSS_URL : 'admin.min.css';
        if (file_exists($sAdminCssPath)) {
            $oAsset->load($sAdminCssUrl);
        }
    }

protected
function
loadCss
(
)
{
$
oAsset
=
Factory
::
service
(
'Asset'
)
;
//  Module assets
$
oAsset
->
load
(
'nails.admin.css'
,
'NAILS'
)
;
$
oAsset
->
load
(
'admin.css'
,
'nails/module-admin'
)
;
//  Component assets
foreach
(
Components
::
available
(
)
as
$
oComponent
)
{
if
(
!
empty
(
$
oComponent
->
data
->
{
'nails/module-admin'
}
->
autoload
)
)
{
$
oAutoLoad
=
$
oComponent
->
data
->
{
'nails/module-admin'
}
->
autoload
;
if
(
!
empty
(
$
oAutoLoad
->
assets
->
css
)
)
{
foreach
(
$
oAutoLoad
->
assets
->
css
as
$
mAsset
)
{
if
(
is_string
(
$
mAsset
)
)
{
$
sAsset
=
$
mAsset
;
$
sLocation
=
$
oComponent
->
slug
;
}
else
{
$
sAsset
=
!
empty
(
$
mAsset
[
0
]
)
$
mAsset
[
0
]
:
;
$
sLocation
=
!
empty
(
$
mAsset
[
1
]
)
$
mAsset
[
1
]
:
;
}
$
oAsset
->
load
(
$
sAsset
,
$
sLocation
,
'CSS'
)
;
}
}
//  CSS Inline
if
(
!
empty
(
$
oAutoLoad
->
assets
->
cssInline
)
)
{
foreach
(
$
oAutoLoad
->
assets
->
cssInline
as
$
sAsset
)
{
$
oAsset
->
inline
(
$
sAsset
,
'CSS'
)
;
}
}
}
}
//  Global CSS
$
sAdminCssPath
=
defined
(
'APP_ADMIN_CSS_PATH'
)
APP_ADMIN_CSS_PATH
:
NAILS_APP_PATH
.
'assets/build/css/admin.min.css'
;
$
sAdminCssUrl
=
defined
(
'APP_ADMIN_CSS_URL'
)
APP_ADMIN_CSS_URL
:
'admin.min.css'
;
if
(
file_exists
(
$
sAdminCssPath
)
)
{
$
oAsset
->
load
(
$
sAdminCssUrl
)
;
}
}

Load all Admin orientated CSS

@throws \Nails\Common\Exception\FactoryException


protected function loadLibraries()
    {
        $oAsset = Factory::service('Asset');

        //  jQuery
        $oAsset->load('jquery/dist/jquery.min.js', 'NAILS-BOWER');

        //  Fancybox
        $oAsset->load('fancybox/source/jquery.fancybox.pack.js', 'NAILS-BOWER');
        $oAsset->load('fancybox/source/jquery.fancybox.css', 'NAILS-BOWER');

        //  jQuery Toggles
        $oAsset->load('jquery-toggles/toggles.min.js', 'NAILS-BOWER');
        $oAsset->load('jquery-toggles/css/toggles.css', 'NAILS-BOWER');
        $oAsset->load('jquery-toggles/css/themes/toggles-modern.css', 'NAILS-BOWER');

        //  Tipsy
        $oAsset->load('tipsy/src/javascripts/jquery.tipsy.js', 'NAILS-BOWER');
        $oAsset->load('tipsy/src/stylesheets/tipsy.css', 'NAILS-BOWER');

        //  scrollTo
        $oAsset->load('jquery.scrollTo/jquery.scrollTo.min.js', 'NAILS-BOWER');

        //  jQuery Cookies
        $oAsset->load('jquery-cookie/jquery.cookie.js', 'NAILS-BOWER');

        //  Retina.js
        $oAsset->load('retina.js/dist/retina.min.js', 'NAILS-BOWER');

        //  Bootstrap
        $oAsset->load('bootstrap/js/dropdown.js', 'NAILS-BOWER');

        //  Fontawesome
        $oAsset->load('fontawesome/css/font-awesome.min.css', 'NAILS-BOWER');

        //  Asset libraries
        $oAsset->library('jqueryui');
        $oAsset->library('select2');
        $oAsset->library('ckeditor');
        $oAsset->library('uploadify');
        $oAsset->library('knockout');
        $oAsset->library('moment');
        $oAsset->library('mustache');
    }

Load services required by admin

@throws \Nails\Common\Exception\FactoryException


protected function autoLoad()
    {
        foreach (Components::available() as $oComponent) {
            if (!empty($oComponent->data->{'nails/module-admin'}->autoload)) {

                $oAutoLoad = $oComponent->data->{'nails/module-admin'}->autoload;

                //  Libraries
                if (!empty($oAutoLoad->services)) {
                    foreach ($oAutoLoad->services as $sService) {
                        Factory::service($sService, $oComponent->slug);
                    }
                }

                //  Models
                if (!empty($oAutoLoad->models)) {
                    foreach ($oAutoLoad->models as $sModel) {
                        Factory::model($sModel, $oComponent->slug);
                    }
                }

                //  Helpers
                if (!empty($oAutoLoad->helpers)) {
                    foreach ($oAutoLoad->helpers as $sHelper) {
                        Factory::helper($sHelper, $oComponent->slug);
                    }
                }
            }
        }
    }

protected
function
autoLoad
(
)
{
foreach
(
Components
::
available
(
)
as
$
oComponent
)
{
if
(
!
empty
(
$
oComponent
->
data
->
{
'nails/module-admin'
}
->
autoload
)
)
{
$
oAutoLoad
=
$
oComponent
->
data
->
{
'nails/module-admin'
}
->
autoload
;
//  Libraries
if
(
!
empty
(
$
oAutoLoad
->
services
)
)
{
foreach
(
$
oAutoLoad
->
services
as
$
sService
)
{
Factory
::
service
(
$
sService
,
$
oComponent
->
slug
)
;
}
}
//  Models
if
(
!
empty
(
$
oAutoLoad
->
models
)
)
{
foreach
(
$
oAutoLoad
->
models
as
$
sModel
)
{
Factory
::
model
(
$
sModel
,
$
oComponent
->
slug
)
;
}
}
//  Helpers
if
(
!
empty
(
$
oAutoLoad
->
helpers
)
)
{
foreach
(
$
oAutoLoad
->
helpers
as
$
sHelper
)
{
Factory
::
helper
(
$
sHelper
,
$
oComponent
->
slug
)
;
}
}
}
}
}

Autoload component items

@throws \Nails\Common\Exception\FactoryException


public static function backwardsCompatibility(&$oBindTo)
    {
        //  @todo (Pablo - 2017-06-08) - Try and remove these dependencies
        $oBindTo->load =& get_instance()->load;
        $oBindTo->lang =& get_instance()->lang;
    }

Provides some backwards compatability

@param \stdClass $oBindTo The class to bind to


public function site()
    {
        if (!userHasPermission('admin:admin:settings:site:.*')) {
            unauthorised();
        }

        // --------------------------------------------------------------------------

        $oInput = Factory::service('Input');
        if ($oInput->post()) {

            $aSettings = [];

            if (userHasPermission('admin:admin:settings:site:customjscss')) {
                $aSettings['site_custom_js']     = $oInput->post('site_custom_js');
                $aSettings['site_custom_css']    = $oInput->post('site_custom_css');
                $aSettings['site_custom_markup'] = $oInput->post('site_custom_markup');
            }

            if (userHasPermission('admin:admin:settings:site:analytics')) {
                $aSettings['google_analytics_account'] = $oInput->post('google_analytics_account');
            }

            if (userHasPermission('admin:admin:settings:site:maintenance')) {
                $sRawIPs                                 = $oInput->post('maintenance_mode_whitelist');
                $aSettings['maintenance_mode_enabled']   = (bool) $oInput->post('maintenance_mode_enabled');
                $aSettings['maintenance_mode_whitelist'] = $this->prepareWhitelist($sRawIPs);
                $aSettings['maintenance_mode_title']     = $oInput->post('maintenance_mode_title');
                $aSettings['maintenance_mode_body']      = $oInput->post('maintenance_mode_body');
            }

            if (!empty($aSettings)) {

                $oAppSettingService = Factory::service('AppSetting');
                if ($oAppSettingService->set($aSettings, 'site')) {
                    $this->data['success'] = 'Site settings have been saved.';
                } else {
                    $this->data['error'] = 'There was a problem saving site settings.';
                }

            } else {
                $this->data['message'] = 'No settings to save.';
            }
        }

        // --------------------------------------------------------------------------

        //  Get data
        $this->data['settings'] = appSetting(null, 'app', true);

        // --------------------------------------------------------------------------

        //  Set page title
        $this->data['page']->title = 'Settings › Site';

        // --------------------------------------------------------------------------

        //  Load assets
        $oAsset = Factory::service('Asset');
        $oAsset->load('nails.admin.settings.min.js', 'NAILS');
        $oAsset->load('nails.admin.admin.settings.min.js', 'NAILS');

        // --------------------------------------------------------------------------

        //  Load views
        Helper::loadView('site');
    }


protected function prepareWhitelist($sInput)
    {
        $sWhitelistRaw = $sInput;
        $sWhitelistRaw = str_replace("\n\r", "\n", $sWhitelistRaw);
        $aWhitelistRaw = explode("\n", $sWhitelistRaw);
        $aWhitelist    = [];

        foreach ($aWhitelistRaw as $sLine) {
            $aWhitelist = array_merge(explode(',', $sLine), $aWhitelist);
        }

        $aWhitelist = array_unique($aWhitelist);
        $aWhitelist = array_filter($aWhitelist);
        $aWhitelist = array_map('trim', $aWhitelist);
        $aWhitelist = array_values($aWhitelist);

        return $aWhitelist;
    }

protected function prepareWhitelist ( $ sInput ) { $ sWhitelistRaw = $ sInput ; $ sWhitelistRaw = str_replace ( "\n\r" , "\n" , $ sWhitelistRaw ) ; $ aWhitelistRaw = explode ( "\n" , $ sWhitelistRaw ) ; $ aWhitelist = [ ] ; foreach ( $ aWhitelistRaw as $ sLine ) { $ aWhitelist = array_merge ( explode ( ',' , $ sLine ) , $ aWhitelist ) ; } $ aWhitelist = array_unique ( $ aWhitelist ) ; $ aWhitelist = array_filter ( $ aWhitelist ) ; $ aWhitelist = array_map ( 'trim' , $ aWhitelist ) ; $ aWhitelist = array_values ( $ aWhitelist ) ; return $ aWhitelist ; }

Takes a multi line input and converts it into an array

@param  string $sInput The input string

@return array


protected function extractFieldsets($sComponentSlug, $aSettings, $fieldSetIndex = 0)
    {
        foreach ($aSettings as $oSetting) {

            //  If the object contains a `fields` property then consider this a fieldset and inception
            if (isset($oSetting->fields)) {

                $fieldSetIndex++;

                if (!isset($this->data['fieldsets'][$fieldSetIndex])) {
                    $this->data['fieldsets'][$fieldSetIndex] = [
                        'legend' => $oSetting->legend,
                        'fields' => [],
                    ];
                }

                $this->extractFieldsets($sComponentSlug, $oSetting->fields, $fieldSetIndex);

            } else {

                $sValue = appSetting($oSetting->key, $sComponentSlug);
                if (!is_null($sValue)) {
                    $oSetting->default = $sValue;
                }

                if (!isset($this->data['fieldsets'][$fieldSetIndex])) {
                    $this->data['fieldsets'][$fieldSetIndex] = [
                        'legend' => '',
                        'fields' => [],
                    ];
                }

                $this->data['fieldsets'][$fieldSetIndex]['fields'][] = $oSetting;
                $this->aFields[]                                     = $oSetting;
            }
        }
    }

Recursively gets all the settings from the settings array

@param string $sComponentSlug The component's slug
@param array  $aSettings      The array of fieldsets and/or settings
@param int    $fieldSetIndex  The index of the fieldset


public function getSourceBySlug($sSlug)
    {
        foreach ($this->aSources as $oSource) {
            if ($sSlug === $oSource->slug) {
                return $oSource;
            }
        }

        return null;
    }

public function getSourceBySlug ( $ sSlug ) { foreach ( $ this -> aSources as $ oSource ) { if ( $ sSlug === $ oSource -> slug ) { return $ oSource ; } } return null ; }

Returns a specific source by its slug

@param $sSlug

@return \stdClass|null


public function getFormatBySlug($sSlug)
    {
        foreach ($this->aFormats as $oFormat) {
            if ($sSlug === $oFormat->slug) {
                return $oFormat;
            }
        }

        return null;
    }

public function getFormatBySlug ( $ sSlug ) { foreach ( $ this -> aFormats as $ oFormat ) { if ( $ sSlug === $ oFormat -> slug ) { return $ oFormat ; } } return null ; }

Returns a specific format by its slug

@param $sSlug

@return \stdClass|null


public function export($sSourceSlug, $sFormatSlug, $aOptions = [])
    {
        $oSource = $this->getSourceBySlug($sSourceSlug);
        if (empty($oSource)) {
            throw new NailsException('Invalid data source "' . $sSourceSlug . '"');
        }

        $oFormat = $this->getFormatBySlug($sFormatSlug);
        if (empty($oFormat)) {
            throw new NailsException('Invalid data format "' . $sFormatSlug . '"');
        }

        $oSourceResponse = $oSource->instance->execute($aOptions);
        if (!is_array($oSourceResponse)) {
            $aSourceResponses = [$oSourceResponse];
        } else {
            $aSourceResponses = $oSourceResponse;
        }

        //  Create temporary working directory
        $sTempDir = CACHE_PATH . 'data-export-' . md5(microtime(true)) . mt_rand() . '/';
        mkdir($sTempDir);

        //  Process each file
        $aFiles = [];
        try {

            foreach ($aSourceResponses as $oSourceResponse) {

                if (!($oSourceResponse instanceof SourceResponse)) {
                    throw new NailsException('Source must return an instance of SourceResponse');
                }

                //  Create a new file
                $sFile    = $sTempDir . $oSourceResponse->getFilename() . '.' . $oFormat->instance->getFileExtension();
                $aFiles[] = $sFile;
                $rFile    = fopen($sFile, 'w+');
                //  Write to the file
                $oSourceResponse->reset();
                $oFormat->instance->execute($oSourceResponse, $rFile);
                //  Close the file
                fclose($rFile);
            }

            //  Compress if > 1
            if (count($aFiles) > 1) {
                $sArchiveFile = $sTempDir . 'export.zip';
                $oZip         = Factory::service('Zip');
                foreach ($aFiles as $sFile) {
                    $oZip->read_file($sFile);
                }
                $oZip->archive($sArchiveFile);
                $aFiles[] = $sArchiveFile;
            }
            $sFile = end($aFiles);

            //  Save to CDN
            $oCdn    = Factory::service('Cdn', 'nails/module-cdn');
            $oObject = $oCdn->objectCreate($sFile, 'data-export');

            if (empty($oObject)) {
                throw new NailsException('Failed to upload exported file. ' . $oCdn->lastError());
            }
        } finally {
            //  Tidy up
            foreach ($aFiles as $sFile) {
                if (file_exists($sFile)) {
                    unlink($sFile);
                }
            }
            rmdir($sTempDir);
        }

        return $oObject->id;
    }

Executes a DateExport source then passes to a DataExport format. Once complete
the resulting file is uploaded to the CDN and the object's ID returned.

@param string $sSourceSlug The slug of the source to use
@param string $sFormatSlug The slug of the format to use
@param array  $aOptions    Additional options to pass to the source

@return integer
@throws NailsException

Executes a DateExport source then passes to a DataExport format . Once complete the resulting file is uploaded to the CDN and the object s ID returned .


protected function executionFailed(
        \Exception $oException,
        \stdClass $oRequest,
        \Nails\Admin\Model\Export $oModel,
        \Nails\Admin\Factory\Email\DataExport $oEmail
    ) {
        $this->writeLog('Exception: ' . $oException->getMessage());
        $oModel->setBatchStatus($oRequest->ids, $oModel::STATUS_FAILED, $oException->getMessage());

        $oEmail
            ->data([
                'status' => $oModel::STATUS_FAILED,
                'error'  => $oException->getMessage(),
            ]);

        foreach ($oRequest->recipients as $iRecipient) {
            $oEmail->to($iRecipient)->send();
        }
    }

protected
function
executionFailed
(
\
Exception
$
oException
,
\
stdClass
$
oRequest
,
\
Nails
\
Admin
\
Model
\
Export
$
oModel
,
\
Nails
\
Admin
\
Factory
\
Email
\
DataExport
$
oEmail
)
{
$
this
->
writeLog
(
'Exception: '
.
$
oException
->
getMessage
(
)
)
;
$
oModel
->
setBatchStatus
(
$
oRequest
->
ids
,
$
oModel
::
STATUS_FAILED
,
$
oException
->
getMessage
(
)
)
;
$
oEmail
->
data
(
[
'status'
=>
$
oModel
::
STATUS_FAILED
,
'error'
=>
$
oException
->
getMessage
(
)
,
]
)
;
foreach
(
$
oRequest
->
recipients
as
$
iRecipient
)
{
$
oEmail
->
to
(
$
iRecipient
)
->
send
(
)
;
}
}

Marks a request as failed, recording why it failed and informs the recipients

@param \Exception                            $oException The exception whichw as thrown
@param \stdClass                             $oRequest   The current request
@param \Nails\Admin\Model\Export             $oModel     The data export model
@param \Nails\Admin\Factory\Email\DataExport $oEmail     The email object

Marks a request as failed recording why it failed and informs the recipients


public function add(
        $sVerb,
        $sArticle,
        $sItem,
        $iItemId,
        $sTitle,
        $sUrl = null,
        $sField = null,
        $mOldValue = null,
        $mNewValue = null,
        $bStrict = true
    ) {
        /**
         * if the old_value and the new_value are the same then why are you logging
         * a change!? Lazy [read: efficient] dev.
         */

        if (!is_null($sField)) {

            if (!is_string($mNewValue)) {
                $mNewValue = print_r($mNewValue, true);
            }

            if (!is_string($mOldValue)) {
                $mOldValue = print_r($mOldValue, true);
            }

            $mNewValue = trim($mNewValue);
            $mOldValue = trim($mOldValue);

            if ($bStrict && $mNewValue === $mOldValue) {
                return false;
            } elseif ($mNewValue == $mOldValue) {
                return false;
            }
        }

        // --------------------------------------------------------------------------

        /**
         * Define the key for this change; keys should be common across identical
         * items so we can group changes of the same item together.
         */
        $key = md5(activeUser('id') . '|' . $sVerb . '|' . $sArticle . '|' . $sItem . '|' . $iItemId . '|' . $sTitle . '|' . $sUrl);

        if (empty($this->aChanges[$key])) {
            $this->aChanges[$key] = [
                'user_id' => activeUser('id') ? activeUser('id') : null,
                'verb'    => $sVerb,
                'article' => $sArticle,
                'item'    => $sItem,
                'item_id' => $iItemId,
                'title'   => $sTitle,
                'url'     => $sUrl,
                'changes' => [],
            ];
        }

        // --------------------------------------------------------------------------

        /**
         * Generate a subkey, so that multiple calls to the same field overwrite
         * each other
         */
        if ($sField) {
            $this->aChanges[$key]['changes'][md5($sField)] = (object) [
                'field'     => $sField,
                'old_value' => $mOldValue,
                'new_value' => $mNewValue,
            ];
        }

        // --------------------------------------------------------------------------

        //  If we're not saving  in batches then save now
        if (!$this->bBatchSave) {
            $this->save();
        }

        return true;
    }

Adds a new changelog item

@param string  $sVerb     The verb, e.g "created"
@param string  $sArticle
@param string  $sItem
@param integer $iItemId   The item's ID (e.g the blog post's ID)
@param string  $sTitle    The title of the item (e.g the blog post's title)
@param string  $sUrl      The url to the item (e.g the blog post's URL)
@param string  $sField
@param mixed   $mOldValue The old value
@param mixed   $mNewValue The new value
@param boolean $bStrict   whether or not to compare $mOldValue and $mNewValue strictly

@return bool
@throws \Nails\Common\Exception\FactoryException
@throws \Nails\Common\Exception\ModelException


public function save()
    {
        //  Process all the items and save to the DB, then clean up
        if ($this->aChanges) {

            $this->aChanges = array_values($this->aChanges);
            $oDate          = Factory::factory('DateTime');

            for ($i = 0; $i < count($this->aChanges); $i++) {
                $this->aChanges[$i]['changes']     = array_values($this->aChanges[$i]['changes']);
                $this->aChanges[$i]['changes']     = json_encode($this->aChanges[$i]['changes']);
                $this->aChanges[$i]['created']     = $oDate->format('Y-m-d H:i:s');
                $this->aChanges[$i]['created_by']  = activeUser('id');
                $this->aChanges[$i]['modified']    = $oDate->format('Y-m-d H:i:s');
                $this->aChanges[$i]['modified_by'] = activeUser('id');
            }

            $oDb = Factory::service('Database');
            $oDb->insert_batch($this->getTableName(), $this->aChanges);
        }

        $this->clear();
    }

Save the changelog items

@throws \Nails\Common\Exception\FactoryException
@throws \Nails\Common\Exception\ModelException


public function getAll($iPage = null, $iPerPage = null, array $aData = [], $bIncludeDeleted = false): array
    {
        //  If the first value is an array then treat as if called with getAll(null, null, $aData);
        //  @todo (Pablo - 2017-06-29) - Refactor how this join works (use expandable field)
        if (is_array($iPage)) {
            $aData = $iPage;
            $iPage = null;
        }

        if (empty($aData['select'])) {
            $aData['select'] = [
                $this->getTableAlias() . '.*',
                'u.first_name',
                'u.last_name',
                'u.gender',
                'u.profile_img',
                'ue.email',
            ];
        }

        return parent::getAll($iPage, $iPerPage, $aData, $bIncludeDeleted);
    }

Fetches all objects, optionally paginated.

@param integer $iPage           The page number of the results, if null then no pagination
@param integer $iPerPage        How many items per page of paginated results
@param array   $aData           Any data to pass to getCountCommon()
@param bool    $bIncludeDeleted Whetehr to include deleted items

@return array

Fetches all objects optionally paginated .


protected function getCountCommon(array $aData = [])
    {
        //  Join user tables
        $oDb = Factory::service('Database');
        $oDb->join(NAILS_DB_PREFIX . 'user u', 'u.id = ' . $this->getTableAlias() . '.user_id', 'LEFT');
        $oDb->join(NAILS_DB_PREFIX . 'user_email ue', 'ue.user_id = ' . $this->getTableAlias() . '.user_id AND ue.is_primary = 1', 'LEFT');

        //  Searching?
        if (!empty($aData['keywords'])) {

            if (empty($aData['or_like'])) {
                $aData['or_like'] = [];
            }

            $toSlug = strtolower(str_replace(' ', '_', $aData['keywords']));

            $aData['or_like'][] = [
                'column' => $this->getTableAlias() . '.type',
                'value'  => $toSlug,
            ];
            $aData['or_like'][] = [
                'column' => 'ue.email',
                'value'  => $aData['keywords'],
            ];
        }

        parent::getCountCommon($aData);
    }

protected
function
getCountCommon
(
array
$
aData
=
[
]
)
{
//  Join user tables
$
oDb
=
Factory
::
service
(
'Database'
)
;
$
oDb
->
join
(
NAILS_DB_PREFIX
.
'user u'
,
'u.id = '
.
$
this
->
getTableAlias
(
)
.
'.user_id'
,
'LEFT'
)
;
$
oDb
->
join
(
NAILS_DB_PREFIX
.
'user_email ue'
,
'ue.user_id = '
.
$
this
->
getTableAlias
(
)
.
'.user_id AND ue.is_primary = 1'
,
'LEFT'
)
;
//  Searching?
if
(
!
empty
(
$
aData
[
'keywords'
]
)
)
{
if
(
empty
(
$
aData
[
'or_like'
]
)
)
{
$
aData
[
'or_like'
]
=
[
]
;
}
$
toSlug
=
strtolower
(
str_replace
(
' '
,
'_'
,
$
aData
[
'keywords'
]
)
)
;
$
aData
[
'or_like'
]
[
]
=
[
'column'
=>
$
this
->
getTableAlias
(
)
.
'.type'
,
'value'
=>
$
toSlug
,
]
;
$
aData
[
'or_like'
]
[
]
=
[
'column'
=>
'ue.email'
,
'value'
=>
$
aData
[
'keywords'
]
,
]
;
}
parent
::
getCountCommon
(
$
aData
)
;
}

Applies common conditionals

@param array $aData Data passed from the calling method

@throws \Nails\Common\Exception\FactoryException


protected function formatObject(
        &$oObj,
        array $aData = [],
        array $aIntegers = [],
        array $aBools = [],
        array $aFloats = []
    ) {

        parent::formatObject($oObj, $aData, $aIntegers, $aBools, $aFloats);

        if (!empty($oObj->item_id)) {
            $oObj->item_id = (int) $oObj->item_id;
        }

        $oObj->changes = @json_decode($oObj->changes);
        $oObj->user    = (object) [
            'id'          => $oObj->user_id,
            'first_name'  => isset($oObj->first_name) ? $oObj->first_name : '',
            'last_name'   => isset($oObj->last_name) ? $oObj->last_name : '',
            'gender'      => isset($oObj->gender) ? $oObj->gender : '',
            'profile_img' => isset($oObj->profile_img) ? $oObj->profile_img : '',
            'email'       => isset($oObj->email) ? $oObj->email : '',
        ];

        unset($oObj->user_id);
        unset($oObj->first_name);
        unset($oObj->last_name);
        unset($oObj->gender);
        unset($oObj->profile_img);
        unset($oObj->email);
    }

protected function formatObject ( & $ oObj , array $ aData = [ ] , array $ aIntegers = [ ] , array $ aBools = [ ] , array $ aFloats = [ ] ) { parent :: formatObject ( $ oObj , $ aData , $ aIntegers , $ aBools , $ aFloats ) ; if ( ! empty ( $ oObj -> item_id ) ) { $ oObj -> item_id = ( int ) $ oObj -> item_id ; } $ oObj -> changes = @ json_decode ( $ oObj -> changes ) ; $ oObj -> user = ( object ) [ 'id' => $ oObj -> user_id , 'first_name' => isset ( $ oObj -> first_name ) ? $ oObj -> first_name : '' , 'last_name' => isset ( $ oObj -> last_name ) ? $ oObj -> last_name : '' , 'gender' => isset ( $ oObj -> gender ) ? $ oObj -> gender : '' , 'profile_img' => isset ( $ oObj -> profile_img ) ? $ oObj -> profile_img : '' , 'email' => isset ( $ oObj -> email ) ? $ oObj -> email : '' , ] ; unset ( $ oObj -> user_id ) ; unset ( $ oObj -> first_name ) ; unset ( $ oObj -> last_name ) ; unset ( $ oObj -> gender ) ; unset ( $ oObj -> profile_img ) ; unset ( $ oObj -> email ) ; }

Formats a single object

The getAll() method iterates over each returned item with this method so as to
correctly format the output. Use this to cast integers and booleans and/or organise data into objects.

@param  object $oObj      A reference to the object being formatted.
@param  array  $aData     The same data array which is passed to _getcount_common, for reference if needed
@param  array  $aIntegers Fields which should be cast as integers if numerical and not null
@param  array  $aBools    Fields which should be cast as booleans if not null
@param  array  $aFloats   Fields which should be cast as floats if not null


public function getRemap($sMethod, array $aData = [])
    {
        list($sModel, $iItemId) = $this->getModelClassAndId();
        $aData['where'] = [
            ['model', $sModel],
            ['item_id', $iItemId],
        ];

        return parent::getRemap($sMethod, $aData);
    }

public function getRemap ( $ sMethod , array $ aData = [ ] ) { list ( $ sModel , $ iItemId ) = $ this -> getModelClassAndId ( ) ; $ aData [ 'where' ] = [ [ 'model' , $ sModel ] , [ 'item_id' , $ iItemId ] , ] ; return parent :: getRemap ( $ sMethod , $ aData ) ; }

Handles GET requests

@param string $sMethod The method being called
@param array  $aData   Any data to apply to the requests

@return ApiResponse
@throws ApiException
@throws FactoryException


protected function validateUserInput($aData, $oItem = null)
    {
        $aData = parent::validateUserInput($aData, $oItem);

        list($sModel) = $this->getModelClassAndId();
        $aData['model'] = $sModel;

        return $aData;
    }

protected function validateUserInput ( $ aData , $ oItem = null ) { $ aData = parent :: validateUserInput ( $ aData , $ oItem ) ; list ( $ sModel ) = $ this -> getModelClassAndId ( ) ; $ aData [ 'model' ] = $ sModel ; return $ aData ; }

Validates user input; adds the model to the response

@param array     $aData The user data to validate
@param \stdClass $oItem The current object (when editing)

@return array
@throws ApiException
@throws FactoryException

Validates user input ; adds the model to the response


protected function getModelClassAndId()
    {
        $oInput         = Factory::service('Input');
        $sModelName     = $oInput->get('model_name') ?: $oInput->post('model_name');
        $sModelProvider = $oInput->get('model_provider') ?: $oInput->post('model_provider');
        $iItemId        = (int) $oInput->get('item_id');

        try {
            $oModel = Factory::model($sModelName, $sModelProvider);
            $sModel = get_class($oModel);
        } catch (\Exception $e) {
            throw new ApiException('"' . $sModelProvider . ':' . $sModelName . '" is not a valid model');
        }

        return [$sModel, $iItemId];
    }

protected
function
getModelClassAndId
(
)
{
$
oInput
=
Factory
::
service
(
'Input'
)
;
$
sModelName
=
$
oInput
->
get
(
'model_name'
)
:
$
oInput
->
post
(
'model_name'
)
;
$
sModelProvider
=
$
oInput
->
get
(
'model_provider'
)
:
$
oInput
->
post
(
'model_provider'
)
;
$
iItemId
=
(
int
)
$
oInput
->
get
(
'item_id'
)
;
try
{
$
oModel
=
Factory
::
model
(
$
sModelName
,
$
sModelProvider
)
;
$
sModel
=
get_class
(
$
oModel
)
;
}
catch
(
\
Exception
$
e
)
{
throw
new
ApiException
(
'"'
.
$
sModelProvider
.
':'
.
$
sModelName
.
'" is not a valid model'
)
;
}
return
[
$
sModel
,
$
iItemId
]
;
}

Returns an arry of the model's class name and the item's ID

@return array
@throws ApiException
@throws FactoryException

Returns an arry of the model s class name and the item s ID


protected function formatObject($oObj)
    {
        return (object) [
            'id'      => $oObj->id,
            'message' => auto_typography($oObj->message),
            'date'    => toUserDatetime($oObj->created),
            'user'    => (object) [
                'id'         => $oObj->created_by ? (int) $oObj->created_by->id : null,
                'first_name' => $oObj->created_by ? $oObj->created_by->first_name : null,
                'last_name'  => $oObj->created_by ? $oObj->created_by->last_name : null,
            ],
        ];
    }

protected function formatObject ( $ oObj ) { return ( object ) [ 'id' => $ oObj -> id , 'message' => auto_typography ( $ oObj -> message ) , 'date' => toUserDatetime ( $ oObj -> created ) , 'user' => ( object ) [ 'id' => $ oObj -> created_by ? ( int ) $ oObj -> created_by -> id : null , 'first_name' => $ oObj -> created_by ? $ oObj -> created_by -> first_name : null , 'last_name' => $ oObj -> created_by ? $ oObj -> created_by -> last_name : null , ] , ] ; }

Formats the response object

@param \stdClass $oObj The object to format

@return \stdClass


public function setDate( $date_string = null ) {
		if( $date_string ) {
			$this->now = getdate(strtotime($date_string));
		} else {
			$this->now = getdate();
		}
	}

public function setDate ( $ date_string = null ) { if ( $ date_string ) { $ this -> now = getdate ( strtotime ( $ date_string ) ) ; } else { $ this -> now = getdate ( ) ; } }

Sets the date for the calendar

@param null|string $date_string Date string parsed by strtotime for the calendar date. If null set to current timestamp.


public function addDailyHtml( $html, $start_date_string, $end_date_string = null ) {
		static $htmlCount = 0;
		$start_date = strtotime($start_date_string);
		if( $end_date_string ) {
			$end_date = strtotime($end_date_string);
		} else {
			$end_date = $start_date;
		}

		$working_date = $start_date;
		do {
			$tDate        = getdate($working_date);
			$working_date += 86400;

			$this->dailyHtml[$tDate['year']][$tDate['mon']][$tDate['mday']][$htmlCount] = $html;
		} while( $working_date < $end_date + 1 );

		$htmlCount++;
	}

public function addDailyHtml ( $ html , $ start_date_string , $ end_date_string = null ) { static $ htmlCount = 0 ; $ start_date = strtotime ( $ start_date_string ) ; if ( $ end_date_string ) { $ end_date = strtotime ( $ end_date_string ) ; } else { $ end_date = $ start_date ; } $ working_date = $ start_date ; do { $ tDate = getdate ( $ working_date ) ; $ working_date += 86400 ; $ this -> dailyHtml [ $ tDate [ 'year' ] ] [ $ tDate [ 'mon' ] ] [ $ tDate [ 'mday' ] ] [ $ htmlCount ] = $ html ; } while ( $ working_date < $ end_date + 1 ) ; $ htmlCount ++ ; }

Add a daily event to the calendar

@param string      $html The raw HTML to place on the calendar for this event
@param string      $start_date_string Date string for when the event starts
@param null|string $end_date_string Date string for when the event ends. Defaults to start date


public function setStartOfWeek( $offset ) {
		if( is_int($offset) ) {
			$this->offset = $offset % 7;
		} else {
			$this->offset = date('N', strtotime($offset)) % 7;
		}
	}

public function setStartOfWeek ( $ offset ) { if ( is_int ( $ offset ) ) { $ this -> offset = $ offset % 7 ; } else { $ this -> offset = date ( 'N' , strtotime ( $ offset ) ) % 7 ; } }

Sets the first day of the week

@param int|string $offset Day to start on, ex: "Monday" or 0-6 where 0 is Sunday


public static function p($str, $args = false)
    {
        if (self::$_debug === true || ApiConfig::get('debug') === true) {
            // first call
            if (self::$_debug === false) {
                self::$_debug = true;
            }

            if ($args !== false) {
                $str .= ', dump: ' . var_export($args, true);
            }

            $str .= ".\n";

            print_r('> ' . $str);
        }
    }

public
static
function
p
(
$
str
,
$
args
=
false
)
{
if
(
self
::
$
_debug
===
true
||
ApiConfig
::
get
(
'debug'
)
===
true
)
{
// first call
if
(
self
::
$
_debug
===
false
)
{
self
::
$
_debug
=
true
;
}
if
(
$
args
!==
false
)
{
$
str
.=
', dump: '
.
var_export
(
$
args
,
true
)
;
}
$
str
.=
".\n"
;
print_r
(
'> '
.
$
str
)
;
}
}

Print debug message

@param   string $str Debug message
@param   array $args (Optional) Value to dump
@static
@access  public
@return  void


public function submitBonus($teamReference, $params)
    {
        ApiDebug::p(__FUNCTION__);

        $adjustments = $this->_client->post('/hr/v2/teams/' . $teamReference . '/adjustments', $params);
        ApiDebug::p('found adjustments info', $adjustments);

        return $adjustments;
    }

public
function
submitBonus
(
$
teamReference
,
$
params
)
{
ApiDebug
::
p
(
__FUNCTION__
)
;
$
adjustments
=
$
this
->
_client
->
post
(
'/hr/v2/teams/'
.
$
teamReference
.
'/adjustments'
,
$
params
)
;
ApiDebug
::
p
(
'found adjustments info'
,
$
adjustments
)
;
return
$
adjustments
;
}

Submit a Custom Payment

@param   integer $teamReference Team reference
@param   array $params Parameters
@return  object


public function assign($company, $team, $engagement, $params)
    {
        ApiDebug::p(__FUNCTION__);

        $response = $this->_client->put('/otask/v1/tasks/companies/' .$company . '/teams/' . $team . '/engagements/' . $engagement . '/tasks', $params);
        ApiDebug::p('found response info', $response);

        return $response;
    }

public
function
assign
(
$
company
,
$
team
,
$
engagement
,
$
params
)
{
ApiDebug
::
p
(
__FUNCTION__
)
;
$
response
=
$
this
->
_client
->
put
(
'/otask/v1/tasks/companies/'
.
$
company
.
'/teams/'
.
$
team
.
'/engagements/'
.
$
engagement
.
'/tasks'
,
$
params
)
;
ApiDebug
::
p
(
'found response info'
,
$
response
)
;
return
$
response
;
}

Assign engagements to the list of activities

@param   string  $company Company ID
@param   string  $team Team ID
@param   integer $engagement Engagement
@param   array   $params Parameters
@return  object


public function assignToEngagement($engagement, $params)
    {
        ApiDebug::p(__FUNCTION__);

        $response = $this->_client->put('/tasks/v2/tasks/contracts/' . $engagement, $params);
        ApiDebug::p('found response info', $response);

        return $response;
    }

public
function
assignToEngagement
(
$
engagement
,
$
params
)
{
ApiDebug
::
p
(
__FUNCTION__
)
;
$
response
=
$
this
->
_client
->
put
(
'/tasks/v2/tasks/contracts/'
.
$
engagement
,
$
params
)
;
ApiDebug
::
p
(
'found response info'
,
$
response
)
;
return
$
response
;
}

Assign to specific engagement the list of activities

@param   integer $engagement Engagement
@param   array   $params Parameters
@return  object


public function getByFreelancer($freelancerReference, $params)
    {
        ApiDebug::p(__FUNCTION__);

        $report = $this->_client->get('/finreports/v2/providers/' . $freelancerReference . '/earnings', $params);
        ApiDebug::p('found report info', $report);

        return $report;
    }

public
function
getByFreelancer
(
$
freelancerReference
,
$
params
)
{
ApiDebug
::
p
(
__FUNCTION__
)
;
$
report
=
$
this
->
_client
->
get
(
'/finreports/v2/providers/'
.
$
freelancerReference
.
'/earnings'
,
$
params
)
;
ApiDebug
::
p
(
'found report info'
,
$
report
)
;
return
$
report
;
}

Generate Earning Reports for a Specific Freelancer

@param   integer $freelancerReference Freelancer reference
@param   array $params Parameters
@return  object


public function getByFreelancersTeam($freelancerTeamReference, $params)
    {
        ApiDebug::p(__FUNCTION__);

        $report = $this->_client->get('/finreports/v2/provider_teams/' . $freelancerTeamReference . '/earnings', $params);
        ApiDebug::p('found report info', $report);

        return $report;
    }

public
function
getByFreelancersTeam
(
$
freelancerTeamReference
,
$
params
)
{
ApiDebug
::
p
(
__FUNCTION__
)
;
$
report
=
$
this
->
_client
->
get
(
'/finreports/v2/provider_teams/'
.
$
freelancerTeamReference
.
'/earnings'
,
$
params
)
;
ApiDebug
::
p
(
'found report info'
,
$
report
)
;
return
$
report
;
}

Generate Earning Reports for a Specific Freelancer's Team

@param   integer $freelancerTeamReference Freelancer team reference
@param   array $params Parameters
@return  object

Generate Earning Reports for a Specific Freelancer s Team


public function getByFreelancersCompany($freelancerCompanyReference, $params)
    {
        ApiDebug::p(__FUNCTION__);

        $report = $this->_client->get('/finreports/v2/provider_companies/' . $freelancerCompanyReference . '/earnings', $params);
        ApiDebug::p('found report info', $report);

        return $report;
    }

public
function
getByFreelancersCompany
(
$
freelancerCompanyReference
,
$
params
)
{
ApiDebug
::
p
(
__FUNCTION__
)
;
$
report
=
$
this
->
_client
->
get
(
'/finreports/v2/provider_companies/'
.
$
freelancerCompanyReference
.
'/earnings'
,
$
params
)
;
ApiDebug
::
p
(
'found report info'
,
$
report
)
;
return
$
report
;
}

Generate Earning Reports for a Specific Freelancer's Company

@param   integer $freelancerCompanyReference Freelancer company reference
@param   array $params Parameters
@return  object

Generate Earning Reports for a Specific Freelancer s Company


public function getByBuyersTeam($buyerTeamReference, $params)
    {
        ApiDebug::p(__FUNCTION__);

        $report = $this->_client->get('/finreports/v2/buyer_teams/' . $buyerTeamReference . '/earnings', $params);
        ApiDebug::p('found report info', $report);

        return $report;
    }

public
function
getByBuyersTeam
(
$
buyerTeamReference
,
$
params
)
{
ApiDebug
::
p
(
__FUNCTION__
)
;
$
report
=
$
this
->
_client
->
get
(
'/finreports/v2/buyer_teams/'
.
$
buyerTeamReference
.
'/earnings'
,
$
params
)
;
ApiDebug
::
p
(
'found report info'
,
$
report
)
;
return
$
report
;
}

Generate Earning Reports for a Specific Buyer's Team

@param   integer $buyerTeamReference Buyer team reference
@param   array $params Parameters
@return  object

Generate Earning Reports for a Specific Buyer s Team


public function getByBuyersCompany($buyerCompanyReference, $params)
    {
        ApiDebug::p(__FUNCTION__);

        $report = $this->_client->get('/finreports/v2/buyer_companies/' . $buyerCompanyReference . '/earnings', $params);
        ApiDebug::p('found report info', $report);

        return $report;
    }

public
function
getByBuyersCompany
(
$
buyerCompanyReference
,
$
params
)
{
ApiDebug
::
p
(
__FUNCTION__
)
;
$
report
=
$
this
->
_client
->
get
(
'/finreports/v2/buyer_companies/'
.
$
buyerCompanyReference
.
'/earnings'
,
$
params
)
;
ApiDebug
::
p
(
'found report info'
,
$
report
)
;
return
$
report
;
}

Generate Earning Reports for a Specific Buyer's Company

@param   integer $buyerCompanyReference Buyer company reference
@param   array $params Parameters
@return  object

Generate Earning Reports for a Specific Buyer s Company


public function getList($params)
    {
        ApiDebug::p(__FUNCTION__);

        $engagements = $this->_client->get('/hr/v2/engagements', $params);
        ApiDebug::p('found response info', $engagements);

        return $engagements;
    }

public
function
getList
(
$
params
)
{
ApiDebug
::
p
(
__FUNCTION__
)
;
$
engagements
=
$
this
->
_client
->
get
(
'/hr/v2/engagements'
,
$
params
)
;
ApiDebug
::
p
(
'found response info'
,
$
engagements
)
;
return
$
engagements
;
}

Get list of engagements

@param   array $params Parameters
@return  object


public function getSpecific($reference)
    {
        ApiDebug::p(__FUNCTION__);

        $engagement = $this->_client->get('/hr/v2/engagements/' . $reference);
        ApiDebug::p('found response info', $engagement);

        return $engagement;
    }

public
function
getSpecific
(
$
reference
)
{
ApiDebug
::
p
(
__FUNCTION__
)
;
$
engagement
=
$
this
->
_client
->
get
(
'/hr/v2/engagements/'
.
$
reference
)
;
ApiDebug
::
p
(
'found response info'
,
$
engagement
)
;
return
$
engagement
;
}

Get specific engagement

@param   integer $reference Engagement's reference
@return  object


static public function getFullUrl($url, $ep = null)
    {
        ApiDebug::p('create full url, based on global constant');

        $name = ($ep)
            ? 'UPWORK_BASE_URL_' . strtoupper($ep)
            : 'UPWORK_BASE_URL';

        $fullUrl = constant($name) . $url;
        ApiDebug::p('url', $fullUrl);

        return $fullUrl;
    }

Get full url, based on global constant

@param	string $url Relative URL
@param	string $ep (Optional) Entry point
@static
@access	public
@return	string


public function getList($params)
    {
        ApiDebug::p(__FUNCTION__);

        $response = $this->_client->get('/offers/v1/contractors/offers', $params);
        ApiDebug::p('found response info', $response);

        return $response;
    }

public
function
getList
(
$
params
)
{
ApiDebug
::
p
(
__FUNCTION__
)
;
$
response
=
$
this
->
_client
->
get
(
'/offers/v1/contractors/offers'
,
$
params
)
;
ApiDebug
::
p
(
'found response info'
,
$
response
)
;
return
$
response
;
}

Get list of offers

@param   array $params Parameters
@return  object


public function actions($reference, $params)
    {
        ApiDebug::p(__FUNCTION__);

        $response = $this->_client->post('/offers/v1/contractors/actions/' . $reference, $params);
        ApiDebug::p('found response info', $response);

        return $response;
    }

public
function
actions
(
$
reference
,
$
params
)
{
ApiDebug
::
p
(
__FUNCTION__
)
;
$
response
=
$
this
->
_client
->
post
(
'/offers/v1/contractors/actions/'
.
$
reference
,
$
params
)
;
ApiDebug
::
p
(
'found response info'
,
$
response
)
;
return
$
response
;
}

Run a specific action

@param   integer $reference  Offer reference
@param   array   $params     Prameters
@return  object


public function getSpecific($entityReference, $params)
    {
        ApiDebug::p(__FUNCTION__);

        $report = $this->_client->get('/finreports/v2/financial_accounts/' . $entityReference, $params);
        ApiDebug::p('found auth info', $report);

        return $report;
    }

public
function
getSpecific
(
$
entityReference
,
$
params
)
{
ApiDebug
::
p
(
__FUNCTION__
)
;
$
report
=
$
this
->
_client
->
get
(
'/finreports/v2/financial_accounts/'
.
$
entityReference
,
$
params
)
;
ApiDebug
::
p
(
'found auth info'
,
$
report
)
;
return
$
report
;
}

Generate Financial Reports for a Specific Account

@param   integer $entityReference Entity reference
@param   array $params Parameters
@return  object


public function getAll()
    {
        ApiDebug::p(__FUNCTION__);

        $roles = $this->_client->get('/hr/v2/userroles');
        ApiDebug::p('found response info', $roles);

        return $roles;
    }

public
function
getAll
(
)
{
ApiDebug
::
p
(
__FUNCTION__
)
;
$
roles
=
$
this
->
_client
->
get
(
'/hr/v2/userroles'
)
;
ApiDebug
::
p
(
'found response info'
,
$
roles
)
;
return
$
roles
;
}


public function getBySpecificUser($reference)
    {
        ApiDebug::p(__FUNCTION__);

        $roles = $this->_client->get('/hr/v2/userroles/' . $reference);
        ApiDebug::p('found auth info', $roles);

        return $roles;
    }

public
function
getBySpecificUser
(
$
reference
)
{
ApiDebug
::
p
(
__FUNCTION__
)
;
$
roles
=
$
this
->
_client
->
get
(
'/hr/v2/userroles/'
.
$
reference
)
;
ApiDebug
::
p
(
'found auth info'
,
$
roles
)
;
return
$
roles
;
}

Get by specific user

@param   integer $reference User reference
@return  object


public function invite($jobKey, $params)
    {
        ApiDebug::p(__FUNCTION__);

        $response = $this->_client->post('/hr/v1/jobs/' . $jobKey . '/candidates', $params);
        ApiDebug::p('found response info', $response);

        return $response;
    }

public
function
invite
(
$
jobKey
,
$
params
)
{
ApiDebug
::
p
(
__FUNCTION__
)
;
$
response
=
$
this
->
_client
->
post
(
'/hr/v1/jobs/'
.
$
jobKey
.
'/candidates'
,
$
params
)
;
ApiDebug
::
p
(
'found response info'
,
$
response
)
;
return
$
response
;
}

Invite to Interview

@param   string $jobKey Job key
@param   array $params Parameters
@return  object


public function getByAgency($company, $agency, $params)
    {
        ApiDebug::p(__FUNCTION__);

        return $this->_getByType($company, null, $agency, $params);
    }

public function getByAgency ( $ company , $ agency , $ params ) { ApiDebug :: p ( __FUNCTION__ ) ; return $ this -> _getByType ( $ company , null , $ agency , $ params ) ; }

Generating Agency Specific Reports

@param   string $company Company ID
@param   string $agency Agency ID
@param   array $params Parameters
@return  object


public function getByCompany($company, $params)
    {
        ApiDebug::p(__FUNCTION__);

        return $this->_getByType($company, null, null, $params);
    }

public function getByCompany ( $ company , $ params ) { ApiDebug :: p ( __FUNCTION__ ) ; return $ this -> _getByType ( $ company , null , null , $ params ) ; }

Generating Company Wide Reports

@param   string $company Company ID
@param   array $params Parameters
@return  object


public function getUsersInTeam($teamReference)
    {
        ApiDebug::p(__FUNCTION__);

        $response = $this->_client->get('/hr/v2/teams/' . $teamReference . '/users');
        ApiDebug::p('found response info', $response);

        return $response;
    }

public
function
getUsersInTeam
(
$
teamReference
)
{
ApiDebug
::
p
(
__FUNCTION__
)
;
$
response
=
$
this
->
_client
->
get
(
'/hr/v2/teams/'
.
$
teamReference
.
'/users'
)
;
ApiDebug
::
p
(
'found response info'
,
$
response
)
;
return
$
response
;
}

Get Users in Team

@param   integer $teamReference Team reference
@return  object


public function getList($params)
    {
        ApiDebug::p(__FUNCTION__);

        $jobs = $this->_client->get('/hr/v2/jobs', $params);
        ApiDebug::p('found response info', $jobs);

        return $jobs;
    }

public
function
getList
(
$
params
)
{
ApiDebug
::
p
(
__FUNCTION__
)
;
$
jobs
=
$
this
->
_client
->
get
(
'/hr/v2/jobs'
,
$
params
)
;
ApiDebug
::
p
(
'found response info'
,
$
jobs
)
;
return
$
jobs
;
}

Get list of jobs

@param   array $params Parameters
@return  object


public function getSpecific($key)
    {
        ApiDebug::p(__FUNCTION__);

        $job = $this->_client->get('/hr/v2/jobs/' . $key);
        ApiDebug::p('found response info', $job);

        return $job;
    }

public
function
getSpecific
(
$
key
)
{
ApiDebug
::
p
(
__FUNCTION__
)
;
$
job
=
$
this
->
_client
->
get
(
'/hr/v2/jobs/'
.
$
key
)
;
ApiDebug
::
p
(
'found response info'
,
$
job
)
;
return
$
job
;
}

Get specific job by key

@param   string $key Job key
@return  object


public function postJob($params)
    {
        ApiDebug::p(__FUNCTION__);

        $job = $this->_client->post('/hr/v2/jobs', $params);
        ApiDebug::p('found response info', $job);

        return $job;
    }

public
function
postJob
(
$
params
)
{
ApiDebug
::
p
(
__FUNCTION__
)
;
$
job
=
$
this
->
_client
->
post
(
'/hr/v2/jobs'
,
$
params
)
;
ApiDebug
::
p
(
'found response info'
,
$
job
)
;
return
$
job
;
}

Post a new job

@param   array $params Parameters
@return  object


public function editJob($key, $params)
    {
        ApiDebug::p(__FUNCTION__);

        $job = $this->_client->put('/hr/v2/jobs/' . $key, $params);
        ApiDebug::p('found response info', $job);

        return $job;
    }

public
function
editJob
(
$
key
,
$
params
)
{
ApiDebug
::
p
(
__FUNCTION__
)
;
$
job
=
$
this
->
_client
->
put
(
'/hr/v2/jobs/'
.
$
key
,
$
params
)
;
ApiDebug
::
p
(
'found response info'
,
$
job
)
;
return
$
job
;
}

Edit existend job

@param   string $key Job key
@param   array $params Parameters
@return  object


public function deleteJob($key, $params)
    {
        ApiDebug::p(__FUNCTION__);

        $job = $this->_client->delete('/hr/v2/jobs/' . $key, $params);
        ApiDebug::p('found response info', $job);

        return $job;
    }

public
function
deleteJob
(
$
key
,
$
params
)
{
ApiDebug
::
p
(
__FUNCTION__
)
;
$
job
=
$
this
->
_client
->
delete
(
'/hr/v2/jobs/'
.
$
key
,
$
params
)
;
ApiDebug
::
p
(
'found response info'
,
$
job
)
;
return
$
job
;
}

Delete existend job

@param   string $key Job key
@param   array $params Parameters
@return  object


public function getMyInfo()
    {
        ApiDebug::p(__FUNCTION__);

        $response = $this->_client->get('/hr/v2/users/me');
        ApiDebug::p('found response info', $response);

        return $response;
    }

public
function
getMyInfo
(
)
{
ApiDebug
::
p
(
__FUNCTION__
)
;
$
response
=
$
this
->
_client
->
get
(
'/hr/v2/users/me'
)
;
ApiDebug
::
p
(
'found response info'
,
$
response
)
;
return
$
response
;
}


public function getSpecific($userReference)
    {
        ApiDebug::p(__FUNCTION__);

        $response = $this->_client->get('/hr/v2/users/' . $userReference);
        ApiDebug::p('found response info', $response);

        return $response;
    }

public
function
getSpecific
(
$
userReference
)
{
ApiDebug
::
p
(
__FUNCTION__
)
;
$
response
=
$
this
->
_client
->
get
(
'/hr/v2/users/'
.
$
userReference
)
;
ApiDebug
::
p
(
'found response info'
,
$
response
)
;
return
$
response
;
}

Get Specific User Info

@param integer $userReference User Reference
@return object


private function _getByType($company, $team, $code = null)
    {
        ApiDebug::p(__FUNCTION__);

        $_url = '';
        if (!empty($code)) {
            $_url = '/' . $code;
        }

        $response = $this->_client->get('/otask/v1/tasks/companies/' . $company . '/teams/' . $team . '/tasks' . $_url);
        ApiDebug::p('found response info', $response);

        return $response;
    }

private
function
_getByType
(
$
company
,
$
team
,
$
code
=
)
{
ApiDebug
::
p
(
__FUNCTION__
)
;
$
_url
=
''
;
if
(
!
empty
(
$
code
)
)
{
$
_url
=
'/'
.
$
code
;
}
$
response
=
$
this
->
_client
->
get
(
'/otask/v1/tasks/companies/'
.
$
company
.
'/teams/'
.
$
team
.
'/tasks'
.
$
_url
)
;
ApiDebug
::
p
(
'found response info'
,
$
response
)
;
return
$
response
;
}

Get by type

@param   string $company Company ID
@param   string $team Team ID
@param   string $code (Optional) Code(s)
@return  object


public function getRoomDetails($company, $roomId, $params = array())
    {
        ApiDebug::p(__FUNCTION__);

        $response = $this->_client->get('/messages/v3/' . $company . '/rooms/' . $roomId, $params);
        ApiDebug::p('received data', $response);

        return $response;
    }

public
function
getRoomDetails
(
$
company
,
$
roomId
,
$
params
=
array
(
)
)
{
ApiDebug
::
p
(
__FUNCTION__
)
;
$
response
=
$
this
->
_client
->
get
(
'/messages/v3/'
.
$
company
.
'/rooms/'
.
$
roomId
,
$
params
)
;
ApiDebug
::
p
(
'received data'
,
$
response
)
;
return
$
response
;
}

Get a specific room information

@param   string $company Company ID
@param   string $roomId Room ID
@param   array $params List of parameters
@access  public
@return  object


public function getRoomByOffer($company, $offerId, $params = array())
    {
        ApiDebug::p(__FUNCTION__);

        $response = $this->_client->get('/messages/v3/' . $company . '/rooms/offers/' . $offerId, $params);
        ApiDebug::p('received data', $response);

        return $response;
    }

public
function
getRoomByOffer
(
$
company
,
$
offerId
,
$
params
=
array
(
)
)
{
ApiDebug
::
p
(
__FUNCTION__
)
;
$
response
=
$
this
->
_client
->
get
(
'/messages/v3/'
.
$
company
.
'/rooms/offers/'
.
$
offerId
,
$
params
)
;
ApiDebug
::
p
(
'received data'
,
$
response
)
;
return
$
response
;
}

Get a specific room by offer ID

@param   string $company Company ID
@param	integer $offerId Offer ID
@param   array $params List of parameters
@access  public
@return  object


public function getRoomByApplication($company, $applicationId, $params = array())
    {
        ApiDebug::p(__FUNCTION__);

        $response = $this->_client->get('/messages/v3/' . $company . '/rooms/applications/' . $applicationId, $params);
        ApiDebug::p('received data', $response);

        return $response;
    }

public
function
getRoomByApplication
(
$
company
,
$
applicationId
,
$
params
=
array
(
)
)
{
ApiDebug
::
p
(
__FUNCTION__
)
;
$
response
=
$
this
->
_client
->
get
(
'/messages/v3/'
.
$
company
.
'/rooms/applications/'
.
$
applicationId
,
$
params
)
;
ApiDebug
::
p
(
'received data'
,
$
response
)
;
return
$
response
;
}

Get a specific room by application ID

@param   string $company Company ID
@param	integer $applicationId Application ID
@param   array $params List of parameters
@access  public
@return  object


public function getRoomByContract($company, $contractId, $params = array())
    {
        ApiDebug::p(__FUNCTION__);

        $response = $this->_client->get('/messages/v3/' . $company . '/rooms/contracts/' . $contractId, $params);
        ApiDebug::p('received data', $response);

        return $response;
    }

public
function
getRoomByContract
(
$
company
,
$
contractId
,
$
params
=
array
(
)
)
{
ApiDebug
::
p
(
__FUNCTION__
)
;
$
response
=
$
this
->
_client
->
get
(
'/messages/v3/'
.
$
company
.
'/rooms/contracts/'
.
$
contractId
,
$
params
)
;
ApiDebug
::
p
(
'received data'
,
$
response
)
;
return
$
response
;
}

Get a specific room by contract ID

@param   string $company Company ID
@param	integer $contractId Contract ID
@param   array $params List of parameters
@access  public
@return  object


public function createRoom($company, $params = array())
    {
        ApiDebug::p(__FUNCTION__);

        $response = $this->_client->post('/messages/v3/' . $company . '/rooms', $params);
        ApiDebug::p('received data', $response);

        return $response;
    }

public
function
createRoom
(
$
company
,
$
params
=
array
(
)
)
{
ApiDebug
::
p
(
__FUNCTION__
)
;
$
response
=
$
this
->
_client
->
post
(
'/messages/v3/'
.
$
company
.
'/rooms'
,
$
params
)
;
ApiDebug
::
p
(
'received data'
,
$
response
)
;
return
$
response
;
}

Create a new room

@param   string $company Company ID
@param   array $params List of parameters
@access  public
@return  object


public function sendMessageToRoom($company, $roomId, $params = array())
    {
        ApiDebug::p(__FUNCTION__);

        $response = $this->_client->post('/messages/v3/' . $company . '/rooms/' . $roomId . '/stories', $params);
        ApiDebug::p('received data', $response);

        return $response;
    }

public
function
sendMessageToRoom
(
$
company
,
$
roomId
,
$
params
=
array
(
)
)
{
ApiDebug
::
p
(
__FUNCTION__
)
;
$
response
=
$
this
->
_client
->
post
(
'/messages/v3/'
.
$
company
.
'/rooms/'
.
$
roomId
.
'/stories'
,
$
params
)
;
ApiDebug
::
p
(
'received data'
,
$
response
)
;
return
$
response
;
}

Send a message to a room

@param   string $company Company ID
@param	string $roomId Room ID
@param   array $params List of parameters
@access  public
@return  object


public function updateRoomSettings($company, $roomId, $username, $params = array())
    {
        ApiDebug::p(__FUNCTION__);

        $response = $this->_client->put('/messages/v3/' . $company . '/rooms/' . $roomId . '/users/' . $username, $params);
        ApiDebug::p('received data', $response);

        return $response;
    }

public
function
updateRoomSettings
(
$
company
,
$
roomId
,
$
username
,
$
params
=
array
(
)
)
{
ApiDebug
::
p
(
__FUNCTION__
)
;
$
response
=
$
this
->
_client
->
put
(
'/messages/v3/'
.
$
company
.
'/rooms/'
.
$
roomId
.
'/users/'
.
$
username
,
$
params
)
;
ApiDebug
::
p
(
'received data'
,
$
response
)
;
return
$
response
;
}

Update a room settings

@param   string $company Company ID
@param	string $roomId Room ID
@param	string $username User ID
@param   array $params List of parameters
@access  public
@return  object


public function updateRoomMetadata($company, $roomId, $params = array())
    {
        ApiDebug::p(__FUNCTION__);

        $response = $this->_client->put('/messages/v3/' . $company . '/rooms/' . $roomId, $params);
        ApiDebug::p('received data', $response);

        return $response;
    }

public
function
updateRoomMetadata
(
$
company
,
$
roomId
,
$
params
=
array
(
)
)
{
ApiDebug
::
p
(
__FUNCTION__
)
;
$
response
=
$
this
->
_client
->
put
(
'/messages/v3/'
.
$
company
.
'/rooms/'
.
$
roomId
,
$
params
)
;
ApiDebug
::
p
(
'received data'
,
$
response
)
;
return
$
response
;
}

Update the metadata of a room

@param   string $company Company ID
@param	string $roomId Room ID
@param   array $params List of parameters
@access  public
@return  object


public function getByContract($contractId, $ts)
    {
        ApiDebug::p(__FUNCTION__);

        $response = $this->_client->get('/team/v3/snapshots/contracts/' . $contractId . '/' . $ts);
        ApiDebug::p('found response info', $response);

        return $response;
    }

public
function
getByContract
(
$
contractId
,
$
ts
)
{
ApiDebug
::
p
(
__FUNCTION__
)
;
$
response
=
$
this
->
_client
->
get
(
'/team/v3/snapshots/contracts/'
.
$
contractId
.
'/'
.
$
ts
)
;
ApiDebug
::
p
(
'found response info'
,
$
response
)
;
return
$
response
;
}

Get snapshot info by specific contract

@param   string $contractId Contract ID
@param   string $ts Timestamp
@return  object


public function updateByContract($contractId, $ts, $params)
    {
        ApiDebug::p(__FUNCTION__);

        $response = $this->_client->put('/team/v3/snapshots/contracts/' . $contractId . '/' . $ts, $params);
        ApiDebug::p('found response info', $response);

        return $response;
    }

public
function
updateByContract
(
$
contractId
,
$
ts
,
$
params
)
{
ApiDebug
::
p
(
__FUNCTION__
)
;
$
response
=
$
this
->
_client
->
put
(
'/team/v3/snapshots/contracts/'
.
$
contractId
.
'/'
.
$
ts
,
$
params
)
;
ApiDebug
::
p
(
'found response info'
,
$
response
)
;
return
$
response
;
}

Update snapshot by specific contract

@param   string $contractId Contract ID
@param   string $ts Timestamp
@param   array $params Parameters
@return  object


public function deleteByContract($contractId, $ts)
    {
        ApiDebug::p(__FUNCTION__);

        $response = $this->_client->delete('/team/v3/snapshots/contracts/' . $contractId . '/' . $ts);
        ApiDebug::p('found response info', $response);

        return $response;
    }

public
function
deleteByContract
(
$
contractId
,
$
ts
)
{
ApiDebug
::
p
(
__FUNCTION__
)
;
$
response
=
$
this
->
_client
->
delete
(
'/team/v3/snapshots/contracts/'
.
$
contractId
.
'/'
.
$
ts
)
;
ApiDebug
::
p
(
'found response info'
,
$
response
)
;
return
$
response
;
}

Delete snapshot by specific contract

@param   string $contractId Contract ID
@param   string $ts Timestamp
@return  object


public function getActiveMilestone($contractId)
    {
        ApiDebug::p(__FUNCTION__);

        $response = $this->_client->get('/hr/v3/fp/milestones/statuses/active/contracts/' . $contractId);
        ApiDebug::p('found response info', $response);

        return $response;
    }

Get active Milestone for specific Contract

@param   integer $contractId Contract reference
@return  object


public function getSubmissions($milestoneId)
    {
        ApiDebug::p(__FUNCTION__);

        $response = $this->_client->get('/hr/v3/fp/milestones/' . $milestoneId . '/submissions');
        ApiDebug::p('found response info', $response);

        return $response;
    }

public
function
getSubmissions
(
$
milestoneId
)
{
ApiDebug
::
p
(
__FUNCTION__
)
;
$
response
=
$
this
->
_client
->
get
(
'/hr/v3/fp/milestones/'
.
$
milestoneId
.
'/submissions'
)
;
ApiDebug
::
p
(
'found response info'
,
$
response
)
;
return
$
response
;
}

Get all Submissions for specific Milestone

@param   integer $milestoneId Milestone ID
@return  object


public function create($params)
    {
        ApiDebug::p(__FUNCTION__);

        $response = $this->_client->post('/hr/v3/fp/milestones', $params);
        ApiDebug::p('found response info', $response);

        return $response;
    }

public
function
create
(
$
params
)
{
ApiDebug
::
p
(
__FUNCTION__
)
;
$
response
=
$
this
->
_client
->
post
(
'/hr/v3/fp/milestones'
,
$
params
)
;
ApiDebug
::
p
(
'found response info'
,
$
response
)
;
return
$
response
;
}

Create a new Milestone

@param   array $params Parameters
@return  object


public function edit($milestoneId, $params)
    {
        ApiDebug::p(__FUNCTION__);

        $response = $this->_client->put('/hr/v3/fp/milestones/' . $milestoneId, $params);
        ApiDebug::p('found response info', $response);

        return $response;
    }

public
function
edit
(
$
milestoneId
,
$
params
)
{
ApiDebug
::
p
(
__FUNCTION__
)
;
$
response
=
$
this
->
_client
->
put
(
'/hr/v3/fp/milestones/'
.
$
milestoneId
,
$
params
)
;
ApiDebug
::
p
(
'found response info'
,
$
response
)
;
return
$
response
;
}

Edit an existing Milestone

@param   integer $milestoneId Milestone ID
@param   array $params Parameters
@return  object


public function delete($milestoneId)
    {
        ApiDebug::p(__FUNCTION__);

        $response = $this->_client->delete('/hr/v3/fp/milestones/' . $milestoneId);
        ApiDebug::p('found response info', $response);

        return $response;
    }

public
function
delete
(
$
milestoneId
)
{
ApiDebug
::
p
(
__FUNCTION__
)
;
$
response
=
$
this
->
_client
->
delete
(
'/hr/v3/fp/milestones/'
.
$
milestoneId
)
;
ApiDebug
::
p
(
'found response info'
,
$
response
)
;
return
$
response
;
}

Delete an existing Milestone

@param   integer $milestoneId Milestone ID
@return  object


protected function _request($type, $url, $params = array())
    {
        ApiDebug::p('running Client request', $this->_server);

        $method = 'POST';
        switch ($type) {
            case 'PUT':
                $params['http_method'] = 'put';
                break;
            case 'DELETE':
                $params['http_method'] = 'delete';
                break;
            case 'GET':
                $method = 'GET';
                break;
            default:
                break;
        }

        if (self::$_epoint == UPWORK_API_EP_NAME) {
            $url = $url . '.' . self::DATA_FORMAT;
        } elseif (self::$_epoint == UPWORK_GDS_EP_NAME) {
            $params['tqx'] = 'out:' . self::DATA_FORMAT;
        }

        $this->_server->option('sigMethod', ApiConfig::get('sigMethod'));
        $this->_server->option('epoint', self::$_epoint);

        $response = $this->_server->request($method, $url, $params);

        return json_decode($response);
    }

protected
function
_request
(
$
type
,
$
url
,
$
params
=
array
(
)
)
{
ApiDebug
::
p
(
'running Client request'
,
$
this
->
_server
)
;
$
method
=
'POST'
;
switch
(
$
type
)
{
case
'PUT'
:
$
params
[
'http_method'
]
=
'put'
;
break
;
case
'DELETE'
:
$
params
[
'http_method'
]
=
'delete'
;
break
;
case
'GET'
:
$
method
=
'GET'
;
break
;
default
:
break
;
}
if
(
self
::
$
_epoint
==
UPWORK_API_EP_NAME
)
{
$
url
=
$
url
.
'.'
.
self
::
DATA_FORMAT
;
}
elseif
(
self
::
$
_epoint
==
UPWORK_GDS_EP_NAME
)
{
$
params
[
'tqx'
]
=
'out:'
.
self
::
DATA_FORMAT
;
}
$
this
->
_server
->
option
(
'sigMethod'
,
ApiConfig
::
get
(
'sigMethod'
)
)
;
$
this
->
_server
->
option
(
'epoint'
,
self
::
$
_epoint
)
;
$
response
=
$
this
->
_server
->
request
(
$
method
,
$
url
,
$
params
)
;
return
json_decode
(
$
response
)
;
}

Run API request

@param   string $type Type of request, i.e. method
@param   string $url URL
@param   array $params (Optional) Additional list of parameters
@access  protected
@return  array


public function boot()
    {
        $config = realpath(__DIR__ . '/../resources/config/accountKit.php');

        $js = realpath(__DIR__ . '/../resources/config/accountkit.js');

        $this->publishes([
            $config => config_path('accountKit.php')
        ], 'config');

        $this->publishes([
            $js => public_path('js/accountkit.js')
        ], 'public');
    }

public function boot ( ) { $ config = realpath ( __DIR__ . '/../resources/config/accountKit.php' ) ; $ js = realpath ( __DIR__ . '/../resources/config/accountkit.js' ) ; $ this -> publishes ( [ $ config => config_path ( 'accountKit.php' ) ] , 'config' ) ; $ this -> publishes ( [ $ js => public_path ( 'js/accountkit.js' ) ] , 'public' ) ; }

Publishes all the config file this package needs to function


private function getContentBody($url)
    {
        $data = $this->client->request('GET', $url);

        return json_decode($data->getBody());
    }

private function getContentBody ( $ url ) { $ data = $ this -> client -> request ( 'GET' , $ url ) ; return json_decode ( $ data -> getBody ( ) ) ; }

Make Request To AccountKit

@param string $url

@return mixed


public function accountKitData($code)
    {
        $data = $this->data($code);

        $output = [
            'id' => $data->id,
            'phoneNumber' => '',
            'email' => '',
        ];

        if (array_key_exists('phone', $data)) {
            $output['phoneNumber'] = $data->phone->number ?? null;
        }

        if (array_key_exists('email', $data)) {
            $output['email'] = $data->email->address ?? null;
        }

        return $output;
    }

public function accountKitData ( $ code ) { $ data = $ this -> data ( $ code ) ; $ output = [ 'id' => $ data -> id , 'phoneNumber' => '' , 'email' => '' , ] ; if ( array_key_exists ( 'phone' , $ data ) ) { $ output [ 'phoneNumber' ] = $ data -> phone -> number ?? null ; } if ( array_key_exists ( 'email' , $ data ) ) { $ output [ 'email' ] = $ data -> email -> address ?? null ; } return $ output ; }

Get All User Data

@param string $code
@return array


public function index(ContactRequest $request)
    {

        if ($this->response->typeIs('json')) {
            $pageLimit = $request->input('pageLimit');
            $data      = $this->repository
                ->setPresenter(\Litecms\Contact\Repositories\Presenter\ContactListPresenter::class)
                ->getDataTable($pageLimit);
            return $this->response
                ->data($data)
                ->output();
        }

        $contacts = $this->repository->paginate();

        $this->response->theme->asset()->container('footer')->add('gmap', 'https://maps.googleapis.com/maps/api/js?key=' . config('litecms.contact.gmapapi'));

        return $this->response->setMetaTitle(trans('contact::contact.names'))
            ->view('contact::contact.index', true)
            ->data(compact('contacts'))
            ->output();
    }

Display a list of contact.

@return Response


public function show(ContactRequest $request, Contact $contact)
    {

        if ($contact->exists) {
            $view = 'contact::contact.show';
        } else {
            $view = 'contact::contact.new';
        }

        return $this->response->setMetaTitle(trans('app.view') . ' ' . trans('contact::contact.name'))
            ->data(compact('contact'))
            ->view($view)
            ->output();
    }

public
function
show
(
ContactRequest
$
request
,
Contact
$
contact
)
{
if
(
$
contact
->
exists
)
{
$
view
=
'contact::contact.show'
;
}
else
{
$
view
=
'contact::contact.new'
;
}
return
$
this
->
response
->
setMetaTitle
(
trans
(
'app.view'
)
.
' '
.
trans
(
'contact::contact.name'
)
)
->
data
(
compact
(
'contact'
)
)
->
view
(
$
view
)
->
output
(
)
;
}

Display contact.

@param Request $request
@param Model   $contact

@return Response


public function create(ContactRequest $request)
    {

        $contact = $this->repository->newInstance([]);
        return $this->response->setMetaTitle(trans('app.new') . ' ' . trans('contact::contact.name'))
            ->view('contact::contact.create', true)
            ->data(compact('contact'))
            ->output();
    }

public
function
create
(
ContactRequest
$
request
)
{
$
contact
=
$
this
->
repository
->
newInstance
(
[
]
)
;
return
$
this
->
response
->
setMetaTitle
(
trans
(
'app.new'
)
.
' '
.
trans
(
'contact::contact.name'
)
)
->
view
(
'contact::contact.create'
,
true
)
->
data
(
compact
(
'contact'
)
)
->
output
(
)
;
}

Show the form for creating a new contact.

@param Request $request

@return Response

Show the form for creating a new contact .


public function edit(ContactRequest $request, Contact $contact)
    {
        return $this->response->setMetaTitle(trans('app.edit') . ' ' . trans('contact::contact.name'))
            ->view('contact::contact.edit', true)
            ->data(compact('contact'))
            ->output();
    }

public
function
edit
(
ContactRequest
$
request
,
Contact
$
contact
)
{
return
$
this
->
response
->
setMetaTitle
(
trans
(
'app.edit'
)
.
' '
.
trans
(
'contact::contact.name'
)
)
->
view
(
'contact::contact.edit'
,
true
)
->
data
(
compact
(
'contact'
)
)
->
output
(
)
;
}

Show contact for editing.

@param Request $request
@param Model   $contact

@return Response


public function update(ContactRequest $request, Contact $contact)
    {
        try {
            $attributes = $request->all();

            $contact->update($attributes);
            return $this->response->message(trans('messages.success.updated', ['Module' => trans('contact::contact.name')]))
                ->code(204)
                ->status('success')
                ->url(guard_url('contact/contact/' . $contact->getRouteKey()))
                ->redirect();
        } catch (Exception $e) {
            return $this->response->message($e->getMessage())
                ->code(400)
                ->status('error')
                ->url(guard_url('contact/contact/' . $contact->getRouteKey()))
                ->redirect();
        }

    }

public function update ( ContactRequest $ request , Contact $ contact ) { try { $ attributes = $ request -> all ( ) ; $ contact -> update ( $ attributes ) ; return $ this -> response -> message ( trans ( 'messages.success.updated' , [ 'Module' => trans ( 'contact::contact.name' ) ] ) ) -> code ( 204 ) -> status ( 'success' ) -> url ( guard_url ( 'contact/contact/' . $ contact -> getRouteKey ( ) ) ) -> redirect ( ) ; } catch ( Exception $ e ) { return $ this -> response -> message ( $ e -> getMessage ( ) ) -> code ( 400 ) -> status ( 'error' ) -> url ( guard_url ( 'contact/contact/' . $ contact -> getRouteKey ( ) ) ) -> redirect ( ) ; } }

Update the contact.

@param Request $request
@param Model   $contact

@return Response


public function destroy(ContactRequest $request, Contact $contact)
    {
        try {

            $contact->delete();
            return $this->response->message(trans('messages.success.deleted', ['Module' => trans('contact::contact.name')]))
                ->code(202)
                ->status('success')
                ->url(guard_url('contact/contact'))
                ->redirect();

        } catch (Exception $e) {

            return $this->response->message($e->getMessage())
                ->code(400)
                ->status('error')
                ->url(guard_url('contact/contact/' . $contact->getRouteKey()))
                ->redirect();
        }

    }

public function destroy ( ContactRequest $ request , Contact $ contact ) { try { $ contact -> delete ( ) ; return $ this -> response -> message ( trans ( 'messages.success.deleted' , [ 'Module' => trans ( 'contact::contact.name' ) ] ) ) -> code ( 202 ) -> status ( 'success' ) -> url ( guard_url ( 'contact/contact' ) ) -> redirect ( ) ; } catch ( Exception $ e ) { return $ this -> response -> message ( $ e -> getMessage ( ) ) -> code ( 400 ) -> status ( 'error' ) -> url ( guard_url ( 'contact/contact/' . $ contact -> getRouteKey ( ) ) ) -> redirect ( ) ; } }

Remove the contact.

@param Model   $contact

@return Response


public function gadget($view = 'admin.contact.gadget', $count = 10)
    {

        if (User::hasRole('user')) {
            $this->contact->pushCriteria(new \Litecms\Litecms\Repositories\Criteria\ContactUserCriteria());
        }

        $contact = $this->contact->scopeQuery(function ($query) use ($count) {
            return $query->orderBy('id', 'DESC')->take($count);
        })->all();

        return view('contact::' . $view, compact('contact'))->render();
    }

public function gadget ( $ view = 'admin.contact.gadget' , $ count = 10 ) { if ( User :: hasRole ( 'user' ) ) { $ this -> contact -> pushCriteria ( new \ Litecms \ Litecms \ Repositories \ Criteria \ ContactUserCriteria ( ) ) ; } $ contact = $ this -> contact -> scopeQuery ( function ( $ query ) use ( $ count ) { return $ query -> orderBy ( 'id' , 'DESC' ) -> take ( $ count ) ; } ) -> all ( ) ; return view ( 'contact::' . $ view , compact ( 'contact' ) ) -> render ( ) ; }

Make gadget View

@param string $view

@param int $count

@return View


public function get($field)
    {
        $data=  $this->contact->scopeQuery(function($query){
            return $query->orderBy('id','DESC');
        })->first([$field]);
        return $data[$field];
    }

public function get ( $ field ) { $ data = $ this -> contact -> scopeQuery ( function ( $ query ) { return $ query -> orderBy ( 'id' , 'DESC' ) ; } ) -> first ( [ $ field ] ) ; return $ data [ $ field ] ; }

Returns field of contact.

@param array $filter

@return int


public function view(User $user, Contact $contact)
    {
        if ($user->canDo('contact.contact.view') && $user->isAdmin()) {
            return true;
        }
    }

public function view ( User $ user , Contact $ contact ) { if ( $ user -> canDo ( 'contact.contact.view' ) && $ user -> isAdmin ( ) ) { return true ; } }

Determine if the given user can view the contact.

@param User $user
@param Contact $contact

@return bool

Determine if the given user can view the contact .


public function update(User $user, Contact $contact)
    {
        if ($user->canDo('contact.contact.update') && $user->isAdmin()) {
            return true;
        }
    }

public function update ( User $ user , Contact $ contact ) { if ( $ user -> canDo ( 'contact.contact.update' ) && $ user -> isAdmin ( ) ) { return true ; } }

Determine if the given user can update the given contact.

@param User $user
@param Contact $contact

@return bool

Determine if the given user can update the given contact .